dsh-chaoxing-assistant 2.3.5 → 2.3.6
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/client.js +29 -2
- package/cordis.patch.yml +6 -0
- package/index.js +13 -1
- package/lib/chaoxing.mjs +2 -2
- package/lib/commands.mjs +131 -2
- package/lib/deskv2.mjs +3 -1
- package/lib/pydeps.mjs +439 -0
- package/lib/python.mjs +56 -38
- package/lib/screen.mjs +2 -1
- package/lib/uibridge.mjs +27 -0
- package/lib/work.mjs +1 -1
- package/package.json +1 -1
package/client.js
CHANGED
|
@@ -10,7 +10,7 @@ window.__ModuleLoader__.load({
|
|
|
10
10
|
const useRef = React.useRef;
|
|
11
11
|
const useMemo = React.useMemo;
|
|
12
12
|
const DEF_ID = 'dsh-chaoxing-assistant';
|
|
13
|
-
const VERSION = '2.3.
|
|
13
|
+
const VERSION = '2.3.6';
|
|
14
14
|
const UI_PORT = 9483;
|
|
15
15
|
// 两条传输:优先 DSH 同源路由(dsh-app://app 下无 CORS/无额外端口),失败再退到本机独立端口。
|
|
16
16
|
// v2.2.1 只写死了 http://127.0.0.1:9483,桌面端 Origin 是 dsh-app://app,被桥 403 掉 → 永远「未连接」。
|
|
@@ -169,6 +169,7 @@ window.__ModuleLoader__.load({
|
|
|
169
169
|
const ACTION_LABELS = {};
|
|
170
170
|
ALL_ACTIONS.forEach((a) => { ACTION_LABELS[a.key] = a.label; });
|
|
171
171
|
ACTION_LABELS.focus = '确定';
|
|
172
|
+
ACTION_LABELS['pydeps-install'] = '安装OCR依赖';
|
|
172
173
|
|
|
173
174
|
function labelOf(key) {
|
|
174
175
|
return ACTION_LABELS[key] || key;
|
|
@@ -648,6 +649,10 @@ window.__ModuleLoader__.load({
|
|
|
648
649
|
background:linear-gradient(180deg,rgba(232,205,156,.16),rgba(232,205,156,.055));
|
|
649
650
|
box-shadow:inset 0 1px 0 rgba(255,255,255,.10),0 0 14px -8px rgba(232,205,156,.65)}
|
|
650
651
|
.cx-chip.muted{color:var(--text-3);background:transparent;border-color:rgba(255,255,255,.055);box-shadow:none}
|
|
652
|
+
.cx-chip-btn{cursor:pointer;transition:filter .15s ease,transform .15s ease}
|
|
653
|
+
.cx-chip-btn:hover{filter:brightness(1.22)}
|
|
654
|
+
.cx-chip-btn:active{transform:translateY(.5px)}
|
|
655
|
+
.cx-chip-btn:focus-visible{outline:1px solid rgba(232,205,156,.55);outline-offset:1px}
|
|
651
656
|
.cx-bar{position:relative;height:3px;flex:none;margin-top:1px;border-radius:999px;overflow:hidden;
|
|
652
657
|
background:rgba(0,0,0,.45);box-shadow:inset 0 1px 2px rgba(0,0,0,.6)}
|
|
653
658
|
.cx-bar>i{display:block;height:100%;width:38%;border-radius:999px;
|
|
@@ -929,6 +934,20 @@ window.__ModuleLoader__.load({
|
|
|
929
934
|
if (stats.worksSolved) chips.push({ text: '作业 ' + stats.worksSolved, cls: '' });
|
|
930
935
|
}
|
|
931
936
|
if (state && state.jobs && state.jobs.length) chips.push({ text: '任务 ' + state.jobs.length, cls: 'muted' });
|
|
937
|
+
// OCR 依赖(别的电脑首次用时自动 pip 装,装好之前章节测验/验证码识别不可用)
|
|
938
|
+
const pyd = (state && state.pydeps) || null;
|
|
939
|
+
if (pyd && pyd.state && pyd.state !== 'ready' && mode !== 'desktop') {
|
|
940
|
+
if (pyd.state === 'installing') {
|
|
941
|
+
chips.push({ text: 'OCR 依赖安装中 ' + (Number(pyd.progress) || 0) + '%', cls: 'amber', title: pyd.message || '首次使用会自动下载约 150MB 的识别依赖,装完即可做章节测验' });
|
|
942
|
+
} else {
|
|
943
|
+
chips.push({
|
|
944
|
+
text: 'OCR 依赖缺失 · 点击安装',
|
|
945
|
+
cls: 'amber',
|
|
946
|
+
title: (pyd.message || '章节测验的字体解码和验证码识别需要它') + '(也可在命令里执行 /chaoxing doctor install)',
|
|
947
|
+
onClick: () => act('pydeps-install'),
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
}
|
|
932
951
|
|
|
933
952
|
useEffect(() => {
|
|
934
953
|
try { saveCourse(course); } catch (e) { /* ignore */ }
|
|
@@ -1244,7 +1263,15 @@ window.__ModuleLoader__.load({
|
|
|
1244
1263
|
h(Elapsed, { base: baseSec, at: baseAt, active })
|
|
1245
1264
|
),
|
|
1246
1265
|
chips.length ? h('div', { className: 'cx-chips' },
|
|
1247
|
-
chips.map((c, i) => h('span', {
|
|
1266
|
+
chips.map((c, i) => h('span', {
|
|
1267
|
+
key: i,
|
|
1268
|
+
className: 'cx-chip ' + c.cls + (c.onClick ? ' cx-chip-btn' : ''),
|
|
1269
|
+
title: c.title || undefined,
|
|
1270
|
+
role: c.onClick ? 'button' : undefined,
|
|
1271
|
+
tabIndex: c.onClick ? 0 : undefined,
|
|
1272
|
+
onClick: c.onClick || undefined,
|
|
1273
|
+
onKeyDown: c.onClick ? (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); c.onClick(); } } : undefined,
|
|
1274
|
+
}, c.text))
|
|
1248
1275
|
) : null,
|
|
1249
1276
|
active ? h('div', { className: 'cx-bar', 'aria-hidden': 'true' }, h('i')) : null
|
|
1250
1277
|
) : null,
|
package/cordis.patch.yml
CHANGED
|
@@ -8,6 +8,12 @@
|
|
|
8
8
|
# 留空 = 自动找:环境变量 CHAOXING_PYTHON → DSH 自带 runtime python → PATH 上的 python。
|
|
9
9
|
# 想用自己的虚拟环境就在这里填绝对路径,比如 "C:/py/my-venv/Scripts/python.exe"。
|
|
10
10
|
python: ""
|
|
11
|
+
# 章节测验的字体解码和验证码识别需要 ddddocr + rapidocr_onnxruntime。
|
|
12
|
+
# 留空且默认开着 autoInstall:第一次真要用到时,插件会在 ~/.dsh-chaoxing/py 建独立
|
|
13
|
+
# venv,从清华/阿里镜像装(约 150MB,只装一次,装在用户目录不污染系统 Python)。
|
|
14
|
+
pythonDeps:
|
|
15
|
+
# false = 缺依赖时只提示不安装(离线/内网,或想自己 pip 装到 python 指定的解释器里)
|
|
16
|
+
autoInstall: true
|
|
11
17
|
# 插件启用时(DSH 启动)不自动运行,必须点面板「开始」或调用 chaoxing_auto start
|
|
12
18
|
autoStart: false
|
|
13
19
|
autoAccount: default
|
package/index.js
CHANGED
|
@@ -3,6 +3,7 @@ import { Store, paths, ensureDir } from './lib/paths.mjs';
|
|
|
3
3
|
import { AccountHub } from './lib/browser.mjs';
|
|
4
4
|
import { Engine } from './lib/engine.mjs';
|
|
5
5
|
import { pythonPath } from './lib/python.mjs';
|
|
6
|
+
import { check as pydepsCheck, ensure as pydepsEnsure, status as pydepsStatus, warm as pydepsWarm } from './lib/pydeps.mjs';
|
|
6
7
|
import { createToolDefinitions } from './lib/tools.mjs';
|
|
7
8
|
import { LlmClient } from './lib/llm.mjs';
|
|
8
9
|
import { Autopilot } from './lib/autopilot.mjs';
|
|
@@ -48,6 +49,17 @@ export function apply(ctx, config = {}) {
|
|
|
48
49
|
}
|
|
49
50
|
|
|
50
51
|
const py = pythonPath(config.python);
|
|
52
|
+
// OCR 依赖:别的电脑上没有 ddddocr/rapidocr_onnxruntime 时,章节测验会 quiz-font-abort。
|
|
53
|
+
// 这里只做后台探测 + 暴露安装入口;真正装包发生在第一次需要 OCR 时(或在面板点「安装依赖」)。
|
|
54
|
+
const pyCfg = config.pythonDeps || {};
|
|
55
|
+
if (pyCfg.autoInstall === false) process.env.CHAOXING_PYDEPS_AUTO = '0';
|
|
56
|
+
const pyDepsLog = logs('py');
|
|
57
|
+
const pydeps = {
|
|
58
|
+
status: pydepsStatus,
|
|
59
|
+
check: (o = {}) => pydepsCheck({ explicit: config.python, log: pyDepsLog, ...o }),
|
|
60
|
+
ensure: (o = {}) => pydepsEnsure({ explicit: config.python, log: pyDepsLog, ...o }),
|
|
61
|
+
};
|
|
62
|
+
pydepsWarm({ explicit: config.python, log: pyDepsLog });
|
|
51
63
|
const engine = new Engine({ hub, store, python: py, llm });
|
|
52
64
|
// 鼠标键盘后端:装了 @copylee/dsh-computer-use 就自动改用它(真实 SendInput),
|
|
53
65
|
// 没有就继续用内置 PowerShell(UIA) 驱动。config.desktopInput = 'ps' 可强制走老路径。
|
|
@@ -65,7 +77,7 @@ export function apply(ctx, config = {}) {
|
|
|
65
77
|
|
|
66
78
|
// deps.python 给手动工具(quiz_fetch/work_fetch)用:旧版漏传,exam 路径会退化成扫描运行时的自带
|
|
67
79
|
// python,那个解释器常常没装 rapidocr,导致手动抓题永远乱码。
|
|
68
|
-
const deps = { store, hub, engine, llm, autopilot, deskEngine, cu, paths, config, python: py };
|
|
80
|
+
const deps = { store, hub, engine, llm, autopilot, deskEngine, cu, paths, config, python: py, pydeps };
|
|
69
81
|
// 临时数据清理:用户点「停止」立即清;没点停止则超过 24 小时由后台扫描自动清。
|
|
70
82
|
// 只清任务日志/验证码/截图/桌面临时文件,不碰登录态、字体和 state.json 里的账号/课程/答案。
|
|
71
83
|
const tempCleaner = new TempCleaner({ deps, config, log: logs('cleanup') });
|
package/lib/chaoxing.mjs
CHANGED
|
@@ -435,7 +435,7 @@ export async function solveCaptcha(page, ctx = {}) {
|
|
|
435
435
|
lastImage = file;
|
|
436
436
|
let text = '';
|
|
437
437
|
try {
|
|
438
|
-
const out = await ocrCaptcha(file, { python: ctx.python });
|
|
438
|
+
const out = await ocrCaptcha(file, { python: ctx.python, log });
|
|
439
439
|
text = out.text;
|
|
440
440
|
} catch (e) {
|
|
441
441
|
log({ ev: 'captcha-ocr-fail', try: i + 1, err: truncate(e.message, 140) });
|
|
@@ -486,7 +486,7 @@ export async function resolveFontMap(base64, chars, ctx = {}) {
|
|
|
486
486
|
throw new Error(`字体文件写入失败:${e.message}`);
|
|
487
487
|
}
|
|
488
488
|
const t0 = Date.now();
|
|
489
|
-
const r = await buildFontMap(ttf, out, chars, { python: ctx.python });
|
|
489
|
+
const r = await buildFontMap(ttf, out, chars, { python: ctx.python, log });
|
|
490
490
|
ctx.fontMaps.set(md5, { map: r.map, need: r.need || 0, mapped: r.mapped || 0, chars: String(chars || '') });
|
|
491
491
|
log({ ev: 'font-map', md5, chars: (chars || '').length, need: r.need, mapped: r.mapped, cached: !!r.cached, ms: Date.now() - t0 });
|
|
492
492
|
return { map: r.map, md5, cached: !!r.cached, need: r.need || 0, mapped: r.mapped || 0 };
|
package/lib/commands.mjs
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
// 学习通助手的宿主侧命令:让右侧栏 UI(以及手打斜杠命令)能触发同一套操作。
|
|
2
2
|
// 与 chaoxing_* 工具共用 engine / autopilot / hub 实例,不在 UI 里另写一份逻辑。
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
3
5
|
import { probeLogin, LOGIN_URL } from './chaoxing.mjs';
|
|
4
6
|
import { parseCourseParams, truncate } from './util.mjs';
|
|
5
7
|
|
|
@@ -496,6 +498,124 @@ export function registerChaoxingCommands(ctx, deps, config = {}) {
|
|
|
496
498
|
return `已停止(任务 ${stopped} 个):所有任务终止、队列已清空,不会自动恢复${cleanNote};点「开始」重新扫描`;
|
|
497
499
|
}
|
|
498
500
|
|
|
501
|
+
/** 字体映射缓存:几张表、最后一次生成时间 */
|
|
502
|
+
function fontCacheInfo() {
|
|
503
|
+
let n = 0;
|
|
504
|
+
let last = 0;
|
|
505
|
+
try {
|
|
506
|
+
const dir = deps.paths().fonts;
|
|
507
|
+
for (const f of fs.readdirSync(dir)) {
|
|
508
|
+
if (!f.endsWith('.json')) continue;
|
|
509
|
+
n += 1;
|
|
510
|
+
try {
|
|
511
|
+
const m = fs.statSync(path.join(dir, f)).mtimeMs;
|
|
512
|
+
if (m > last) last = m;
|
|
513
|
+
} catch {
|
|
514
|
+
/* ignore */
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
} catch {
|
|
518
|
+
/* ignore */
|
|
519
|
+
}
|
|
520
|
+
return { n, last };
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/** 最近几次 quiz-font-abort:读最新几个任务日志,找退出原因 */
|
|
524
|
+
function lastFontAbort() {
|
|
525
|
+
let best = null;
|
|
526
|
+
try {
|
|
527
|
+
const dir = deps.paths().logs;
|
|
528
|
+
const files = fs
|
|
529
|
+
.readdirSync(dir)
|
|
530
|
+
.filter((f) => f.endsWith('.jsonl') && f !== 'plugin.jsonl')
|
|
531
|
+
.map((f) => {
|
|
532
|
+
const full = path.join(dir, f);
|
|
533
|
+
try {
|
|
534
|
+
return { full, m: fs.statSync(full).mtimeMs, f };
|
|
535
|
+
} catch {
|
|
536
|
+
return null;
|
|
537
|
+
}
|
|
538
|
+
})
|
|
539
|
+
.filter(Boolean)
|
|
540
|
+
.sort((a, b) => b.m - a.m)
|
|
541
|
+
.slice(0, 3);
|
|
542
|
+
for (const file of files) {
|
|
543
|
+
let text = '';
|
|
544
|
+
try {
|
|
545
|
+
text = fs.readFileSync(file.full, 'utf8');
|
|
546
|
+
} catch {
|
|
547
|
+
continue;
|
|
548
|
+
}
|
|
549
|
+
const lines = text.split(/\r?\n/);
|
|
550
|
+
for (let i = lines.length - 1; i >= 0 && i > lines.length - 800; i--) {
|
|
551
|
+
const line = lines[i];
|
|
552
|
+
if (!line.includes('quiz-font-abort')) continue;
|
|
553
|
+
try {
|
|
554
|
+
const o = JSON.parse(line);
|
|
555
|
+
best = { at: o.at, ev: o.ev, src: o.src, ratio: o.ratio, need: o.need, mapped: o.mapped, file: file.f, job: o.job };
|
|
556
|
+
} catch {
|
|
557
|
+
best = { raw: line.slice(0, 200), file: file.f };
|
|
558
|
+
}
|
|
559
|
+
return best;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
} catch {
|
|
563
|
+
/* ignore */
|
|
564
|
+
}
|
|
565
|
+
return best;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** OCR / 字体链路自检:解释器、依赖、缓存、上次 abort 原因 */
|
|
569
|
+
async function doctorText() {
|
|
570
|
+
const lines = [];
|
|
571
|
+
let st = null;
|
|
572
|
+
try {
|
|
573
|
+
st = deps.pydeps && typeof deps.pydeps.status === 'function' ? deps.pydeps.status() : null;
|
|
574
|
+
} catch (e) {
|
|
575
|
+
lines.push(`依赖状态读取失败:${shortErr(e)}`);
|
|
576
|
+
}
|
|
577
|
+
if (st && st.state !== 'ready' && st.state !== 'installing' && typeof deps.pydeps.check === 'function') {
|
|
578
|
+
try {
|
|
579
|
+
st = await deps.pydeps.check({});
|
|
580
|
+
} catch (e) {
|
|
581
|
+
lines.push(`依赖探测失败:${shortErr(e)}`);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
lines.push('▌ OCR 依赖(章节测验字体解码 / 9010 验证码)');
|
|
585
|
+
if (!st) {
|
|
586
|
+
lines.push(' 状态:未加载(插件版本低于 2.3.6?请升级后再试)');
|
|
587
|
+
} else {
|
|
588
|
+
const stateText =
|
|
589
|
+
{
|
|
590
|
+
ready: `就绪(Python ${st.pyVersion || '?'})`,
|
|
591
|
+
checking: '正在探测…',
|
|
592
|
+
installing: `正在安装(${st.progress || 0}%)`,
|
|
593
|
+
missing: '缺失(首次需要 OCR 时会自动安装)',
|
|
594
|
+
failed: '安装失败',
|
|
595
|
+
unknown: '未知',
|
|
596
|
+
}[st.state] || st.state;
|
|
597
|
+
lines.push(` 状态:${stateText}`);
|
|
598
|
+
lines.push(` 解释器:${st.python || '(未确定)'}`);
|
|
599
|
+
if (st.venv) lines.push(` 插件环境:${st.venv}${st.venvExists ? '' : '(还没创建,首次需要时自动建)'}`);
|
|
600
|
+
if (st.missing && st.missing.length) lines.push(` 缺少模块:${st.missing.join('、')}`);
|
|
601
|
+
if (st.lastError && st.state !== 'ready') lines.push(` 最近错误:${String(st.lastError).slice(0, 200)}`);
|
|
602
|
+
if (st.state !== 'ready' && st.state !== 'installing') lines.push(' 下一步:/chaoxing doctor install(或面板点「安装依赖」)');
|
|
603
|
+
}
|
|
604
|
+
const fc = fontCacheInfo();
|
|
605
|
+
lines.push('▌ 字体映射缓存');
|
|
606
|
+
lines.push(fc.n ? ` ${fc.n} 张映射表,最后一次 ${new Date(fc.last).toLocaleString()}` : ' 还没有映射表(没做过带反爬字体的测验)');
|
|
607
|
+
const ab = lastFontAbort();
|
|
608
|
+
lines.push('▌ 最近一次字体解码失败');
|
|
609
|
+
if (!ab) lines.push(' 没有(说明字体链路目前是通的)');
|
|
610
|
+
else if (ab.ev)
|
|
611
|
+
lines.push(
|
|
612
|
+
` ${ab.at ? new Date(ab.at).toLocaleString() : '?'} 系数 ${ab.ratio ?? '?'}(需解码 ${ab.need ?? '?'} 字、成功 ${ab.mapped ?? '?'} 字,来源 ${ab.src || '?'})` +
|
|
613
|
+
`\n → 低于 0.6 会拒绝交卷;补上 OCR 依赖后重跑这次测验即可。`,
|
|
614
|
+
);
|
|
615
|
+
else lines.push(` ${ab.raw || ''}`);
|
|
616
|
+
return lines.join('\n');
|
|
617
|
+
}
|
|
618
|
+
|
|
499
619
|
async function handler(invocation) {
|
|
500
620
|
const raw = String((invocation && invocation.rawInput) || '').trim();
|
|
501
621
|
const [verb, ...rest] = raw.split(/\s+/);
|
|
@@ -543,6 +663,15 @@ export function registerChaoxingCommands(ctx, deps, config = {}) {
|
|
|
543
663
|
return { kind: 'success', text: await handleAuto() };
|
|
544
664
|
case 'stop':
|
|
545
665
|
return { kind: 'success', text: handleStop() };
|
|
666
|
+
case 'doctor': {
|
|
667
|
+
if (/^install$/i.test(arg.trim())) {
|
|
668
|
+
if (!deps.pydeps) return { kind: 'error', text: '依赖模块未加载:请重启 DSH 后再试' };
|
|
669
|
+
const d = await deps.pydeps.ensure({ force: true });
|
|
670
|
+
if (!d.ok) return { kind: 'error', text: d.message || '安装失败' };
|
|
671
|
+
return { kind: 'success', text: 'OCR 依赖已就绪\n\n' + (await doctorText()) };
|
|
672
|
+
}
|
|
673
|
+
return { kind: 'success', text: await doctorText() };
|
|
674
|
+
}
|
|
546
675
|
case 'courses': {
|
|
547
676
|
const rows = scanList();
|
|
548
677
|
if (!rows.length) return { kind: 'success', text: '还没有扫描记录' };
|
|
@@ -551,7 +680,7 @@ export function registerChaoxingCommands(ctx, deps, config = {}) {
|
|
|
551
680
|
default:
|
|
552
681
|
return {
|
|
553
682
|
kind: 'error',
|
|
554
|
-
text: '用法:/chaoxing status | progress | login | check | courses | scan <course> | run <course> | works <course> | auto | stop',
|
|
683
|
+
text: '用法:/chaoxing status | progress | login | check | courses | scan <course> | run <course> | works <course> | auto | doctor [install] | stop',
|
|
555
684
|
};
|
|
556
685
|
}
|
|
557
686
|
} catch (e) {
|
|
@@ -567,7 +696,7 @@ export function registerChaoxingCommands(ctx, deps, config = {}) {
|
|
|
567
696
|
commands.register({
|
|
568
697
|
name: COMMAND_NAME,
|
|
569
698
|
description: '学习通助手:查看状态、登录检测、扫描课程、刷课、做作业、全自动托管',
|
|
570
|
-
input: { hint: 'status | progress | login | check | courses | scan <course> | run <course> | works <course> | auto | stop' },
|
|
699
|
+
input: { hint: 'status | progress | login | check | courses | scan <course> | run <course> | works <course> | auto | doctor [install] | stop' },
|
|
571
700
|
handler,
|
|
572
701
|
}),
|
|
573
702
|
);
|
package/lib/deskv2.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import path from 'node:path';
|
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
import { sleep } from './util.mjs';
|
|
8
8
|
import { pythonPath } from './python.mjs';
|
|
9
|
+
import { activePython } from './pydeps.mjs';
|
|
9
10
|
import { paths } from './paths.mjs';
|
|
10
11
|
|
|
11
12
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
@@ -176,7 +177,8 @@ export class DeskV2 {
|
|
|
176
177
|
// ---------- 常驻 OCR ----------
|
|
177
178
|
startOcr() {
|
|
178
179
|
if (this._ocr?.pid) return;
|
|
179
|
-
|
|
180
|
+
// 依赖装在插件 venv 里时优先用 venv 的解释器(pydeps 在首次需要 OCR 时才会设置)
|
|
181
|
+
const proc = spawn(activePython() || this.python, [OCRAPI], { stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, PYTHONIOENCODING: 'utf-8' }, windowsHide: true });
|
|
180
182
|
this._ocr = proc;
|
|
181
183
|
this._ocrBuf = '';
|
|
182
184
|
proc.stdout.setEncoding('utf8');
|
package/lib/pydeps.mjs
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
// OCR 依赖(ddddocr / rapidocr_onnxruntime)的探测与按需安装。
|
|
2
|
+
// 为什么需要:插件只带 python/*.py 脚本,不带 Python 依赖包;DSH 自带 runtime python
|
|
3
|
+
// 里也没有这三个包。开发机上能识别是因为有人手工往 runtime 的 site-packages 里丢了
|
|
4
|
+
// zz-chaoxing-ocr.pth 指向开发机 venv —— 换台电脑就只剩 ModuleNotFoundError,
|
|
5
|
+
// 表现为章节测验 quiz-font-abort(不交卷)和 9010 验证码识别失败。
|
|
6
|
+
// 做法:首次真正需要 OCR 时,用 runtime python 建一个 --system-site-packages 的 venv
|
|
7
|
+
//(继承自带的 numpy/Pillow),pip 走国内镜像装 ddddocr + rapidocr_onnxruntime,
|
|
8
|
+
// 失败按清华 → 阿里 → 官方源顺序回退;装好后所有子进程都用这个 venv 的解释器。
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { spawn } from 'node:child_process';
|
|
13
|
+
import { dataDir, ensureDir } from './paths.mjs';
|
|
14
|
+
|
|
15
|
+
/** 需要能 import 成功的模块(onnxruntime 是 rapidocr 的依赖,导入 rapidocr 会连带加载) */
|
|
16
|
+
export const MODULES = ['ddddocr', 'rapidocr_onnxruntime'];
|
|
17
|
+
const PIP_PKGS = ['ddddocr', 'rapidocr_onnxruntime'];
|
|
18
|
+
const MIRRORS = [
|
|
19
|
+
{ name: '清华', url: 'https://pypi.tuna.tsinghua.edu.cn/simple' },
|
|
20
|
+
{ name: '阿里', url: 'https://mirrors.aliyun.com/pypi/simple/' },
|
|
21
|
+
{ name: '官方', url: '' },
|
|
22
|
+
];
|
|
23
|
+
const PROBE_TTL = 10 * 60 * 1000;
|
|
24
|
+
const FAIL_BACKOFF = 5 * 60 * 1000;
|
|
25
|
+
const INSTALL_TIMEOUT = 20 * 60 * 1000;
|
|
26
|
+
|
|
27
|
+
const st = {
|
|
28
|
+
state: 'unknown', // unknown | checking | ready | missing | installing | failed
|
|
29
|
+
python: '',
|
|
30
|
+
pyVersion: '',
|
|
31
|
+
missing: [],
|
|
32
|
+
message: '',
|
|
33
|
+
progress: 0,
|
|
34
|
+
detail: '',
|
|
35
|
+
at: 0,
|
|
36
|
+
installAt: 0,
|
|
37
|
+
lastError: '',
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/** 已确认可用的解释器(venv 或配置里那个)。所有子进程优先用它。 */
|
|
41
|
+
let active = '';
|
|
42
|
+
let probing = null;
|
|
43
|
+
let lastFailAt = 0;
|
|
44
|
+
|
|
45
|
+
function exists(p) {
|
|
46
|
+
try {
|
|
47
|
+
return !!p && fs.existsSync(p);
|
|
48
|
+
} catch {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 依赖安装目录(整个 venv 都在这里) */
|
|
54
|
+
export function depsDir() {
|
|
55
|
+
return path.join(dataDir(), 'py');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** venv 里的解释器路径(Windows: Scripts/python.exe,其它: bin/python3) */
|
|
59
|
+
export function venvPython() {
|
|
60
|
+
const dir = depsDir();
|
|
61
|
+
if (process.platform === 'win32') return path.join(dir, 'Scripts', 'python.exe');
|
|
62
|
+
return path.join(dir, 'bin', 'python3');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 探测到的可用解释器;没有就返回空串 */
|
|
66
|
+
export function activePython() {
|
|
67
|
+
return active;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
let scanAt = 0;
|
|
71
|
+
let baseCached = '';
|
|
72
|
+
|
|
73
|
+
/** 兜底解释器:显式 > CHAOXING_PYTHON > 最近一次扫到的 DSH runtime python > PATH 里的 python */
|
|
74
|
+
export function basePython(explicit) {
|
|
75
|
+
for (const p of [explicit, process.env.CHAOXING_PYTHON, baseCached]) {
|
|
76
|
+
if (exists(p)) return p;
|
|
77
|
+
}
|
|
78
|
+
// 只缓存「真实存在」的绝对路径;PATH 里的裸名字不算命中。
|
|
79
|
+
// 刚扫过仍没找到时短期直接返回 PATH 兜底,避免每次 OCR 都 readdir 一遍运行时目录。
|
|
80
|
+
if (scanAt && Date.now() - scanAt < 60000) return 'python';
|
|
81
|
+
scanAt = Date.now();
|
|
82
|
+
const runtimes = path.join(os.homedir(), '.dsh', 'dsh-runtimes');
|
|
83
|
+
try {
|
|
84
|
+
for (const dir of fs.readdirSync(runtimes)) {
|
|
85
|
+
for (const rel of [
|
|
86
|
+
['dependencies', 'python', 'python.exe'],
|
|
87
|
+
['dependencies', 'python', 'bin', 'python3'],
|
|
88
|
+
['python', 'python.exe'],
|
|
89
|
+
]) {
|
|
90
|
+
const p = path.join(runtimes, dir, ...rel);
|
|
91
|
+
if (exists(p)) {
|
|
92
|
+
baseCached = p;
|
|
93
|
+
return p;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
} catch {
|
|
98
|
+
/* ignore */
|
|
99
|
+
}
|
|
100
|
+
return 'python';
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 跑一个子进程,按行回调(pip 的进度条用 \r 刷新,这里一并切开) */
|
|
104
|
+
function runExe(exe, args, { timeoutMs = 120000, env, onLine } = {}) {
|
|
105
|
+
return new Promise((resolve) => {
|
|
106
|
+
let child;
|
|
107
|
+
try {
|
|
108
|
+
child = spawn(exe, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], env: env || process.env });
|
|
109
|
+
} catch (e) {
|
|
110
|
+
resolve({ code: -1, stdout: '', stderr: String((e && e.message) || e) });
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
let out = '';
|
|
114
|
+
let err = '';
|
|
115
|
+
let finished = false;
|
|
116
|
+
const timer = setTimeout(() => {
|
|
117
|
+
if (finished) return;
|
|
118
|
+
finished = true;
|
|
119
|
+
try {
|
|
120
|
+
child.kill('SIGKILL');
|
|
121
|
+
} catch {
|
|
122
|
+
/* ignore */
|
|
123
|
+
}
|
|
124
|
+
resolve({ code: -2, stdout: out, stderr: `${err}\n(超时 ${timeoutMs}ms)`, timeout: true });
|
|
125
|
+
}, timeoutMs);
|
|
126
|
+
timer.unref?.();
|
|
127
|
+
const feed = (chunk, isErr) => {
|
|
128
|
+
const s = String(chunk);
|
|
129
|
+
if (isErr) err += s;
|
|
130
|
+
else out += s;
|
|
131
|
+
if (err.length > 200000) err = err.slice(-200000);
|
|
132
|
+
if (out.length > 200000) out = out.slice(-200000);
|
|
133
|
+
if (onLine) {
|
|
134
|
+
for (const line of s.split(/[\r\n]+/)) {
|
|
135
|
+
if (line.trim()) {
|
|
136
|
+
try {
|
|
137
|
+
onLine(line.trim(), !!isErr);
|
|
138
|
+
} catch {
|
|
139
|
+
/* ignore */
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
child.stdout.on('data', (d) => feed(d, false));
|
|
146
|
+
child.stderr.on('data', (d) => feed(d, true));
|
|
147
|
+
child.on('error', (e) => {
|
|
148
|
+
if (finished) return;
|
|
149
|
+
finished = true;
|
|
150
|
+
clearTimeout(timer);
|
|
151
|
+
resolve({ code: -1, stdout: out, stderr: `${err}\n${String((e && e.message) || e)}` });
|
|
152
|
+
});
|
|
153
|
+
child.on('close', (code) => {
|
|
154
|
+
if (finished) return;
|
|
155
|
+
finished = true;
|
|
156
|
+
clearTimeout(timer);
|
|
157
|
+
resolve({ code, stdout: out, stderr: err });
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const PROBE_SCRIPT = [
|
|
163
|
+
'import json,sys',
|
|
164
|
+
'r={"py":sys.version.split()[0],"missing":[],"why":{}}',
|
|
165
|
+
'for m in ("ddddocr","rapidocr_onnxruntime"):',
|
|
166
|
+
' try:',
|
|
167
|
+
' __import__(m)',
|
|
168
|
+
' except Exception as e:',
|
|
169
|
+
' r["missing"].append(m); r["why"][m]=(type(e).__name__+": "+str(e))[:300]',
|
|
170
|
+
'print(json.dumps(r))',
|
|
171
|
+
].join('\n');
|
|
172
|
+
|
|
173
|
+
/** 在指定解释器里导入一次依赖,返回 {ok, py, missing, why} */
|
|
174
|
+
export async function probe(exe, { timeoutMs = 120000 } = {}) {
|
|
175
|
+
if (!exe) return { ok: false, missing: MODULES.slice(), why: {}, error: '没有可用的 python' };
|
|
176
|
+
const r = await runExe(exe, ['-c', PROBE_SCRIPT], { timeoutMs, env: { ...process.env, PYTHONIOENCODING: 'utf-8' } });
|
|
177
|
+
if (r.code !== 0) {
|
|
178
|
+
return {
|
|
179
|
+
ok: false,
|
|
180
|
+
py: '',
|
|
181
|
+
missing: MODULES.slice(),
|
|
182
|
+
why: {},
|
|
183
|
+
error: (r.stderr || r.stdout || '').trim().slice(-400) || `python 退出码 ${r.code}`,
|
|
184
|
+
code: r.code,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
let info = null;
|
|
188
|
+
const lines = String(r.stdout || '').split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
|
189
|
+
for (let i = lines.length - 1; i >= 0 && !info; i--) {
|
|
190
|
+
const idx = lines[i].indexOf('{');
|
|
191
|
+
if (idx < 0) continue;
|
|
192
|
+
try {
|
|
193
|
+
info = JSON.parse(lines[i].slice(idx));
|
|
194
|
+
} catch {
|
|
195
|
+
/* 不是这一行 */
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (!info) return { ok: false, py: '', missing: MODULES.slice(), why: {}, error: `探测输出解析失败:${String(r.stdout).slice(-200)}` };
|
|
199
|
+
const missing = Array.isArray(info.missing) ? info.missing : [];
|
|
200
|
+
return { ok: missing.length === 0, py: info.py || '', missing, why: info.why || {} };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function nowIso() {
|
|
204
|
+
return new Date().toISOString();
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function markReady(exe, info) {
|
|
208
|
+
active = exe;
|
|
209
|
+
st.state = 'ready';
|
|
210
|
+
st.python = exe;
|
|
211
|
+
st.pyVersion = info.py || st.pyVersion;
|
|
212
|
+
st.missing = [];
|
|
213
|
+
st.message = '';
|
|
214
|
+
st.progress = 0;
|
|
215
|
+
st.detail = '';
|
|
216
|
+
st.at = Date.now();
|
|
217
|
+
st.installAt = st.installAt || 0;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function missingText(info) {
|
|
221
|
+
const why = info.why || {};
|
|
222
|
+
const bits = (info.missing || []).map((m) => `${m}(${String(why[m] || '未安装').slice(0, 120)})`);
|
|
223
|
+
return bits.join(';');
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** 只探测、不安装:插件启动时用,避免陌生机器一开插件就偷偷下 150MB */
|
|
227
|
+
export async function check({ explicit, log } = {}) {
|
|
228
|
+
if (st.state === 'ready' && active && Date.now() - st.at < PROBE_TTL) return status();
|
|
229
|
+
if (probing) return probing;
|
|
230
|
+
probing = (async () => {
|
|
231
|
+
st.state = 'checking';
|
|
232
|
+
st.at = Date.now();
|
|
233
|
+
const tried = [];
|
|
234
|
+
for (const exe of [explicit, process.env.CHAOXING_PYTHON, active, venvPython(), basePython(explicit)]) {
|
|
235
|
+
if (!exe || tried.includes(exe)) continue;
|
|
236
|
+
tried.push(exe);
|
|
237
|
+
// PATH 里的裸 'python' 只有最后才试一次
|
|
238
|
+
if (exe === 'python' && tried.length < 2) continue;
|
|
239
|
+
const info = await probe(exe);
|
|
240
|
+
if (info.ok) {
|
|
241
|
+
markReady(exe, info);
|
|
242
|
+
log?.({ ev: 'pydeps-ready', python: exe, py: info.py });
|
|
243
|
+
return status();
|
|
244
|
+
}
|
|
245
|
+
st.lastError = info.error || missingText(info);
|
|
246
|
+
st.missing = info.missing || [];
|
|
247
|
+
st.pyVersion = info.py || st.pyVersion;
|
|
248
|
+
}
|
|
249
|
+
st.state = 'missing';
|
|
250
|
+
st.python = '';
|
|
251
|
+
st.message = depsMissingText();
|
|
252
|
+
st.at = Date.now();
|
|
253
|
+
log?.({ ev: 'pydeps-missing', tried: tried.length, why: st.lastError.slice(0, 200) });
|
|
254
|
+
return status();
|
|
255
|
+
})().finally(() => {
|
|
256
|
+
probing = null;
|
|
257
|
+
});
|
|
258
|
+
return probing;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function depsMissingText() {
|
|
262
|
+
return (
|
|
263
|
+
'缺少 OCR 依赖(ddddocr / rapidocr_onnxruntime):章节测验的字体解码和验证码识别会失败。' +
|
|
264
|
+
'首次需要时会自动安装(约 150MB,走国内镜像),也可以在面板点「安装依赖」立即装。'
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** 确保依赖可用;缺了就装(镜像回退)。成功返回 {ok:true, python} */
|
|
269
|
+
export async function ensure({ explicit, force = false, log, onProgress } = {}) {
|
|
270
|
+
if (!force && st.state === 'ready' && active) return { ok: true, python: active, state: 'ready', installed: false, missing: [], message: '' };
|
|
271
|
+
if (!force && process.env.CHAOXING_PYDEPS_AUTO === '0') {
|
|
272
|
+
return {
|
|
273
|
+
ok: false,
|
|
274
|
+
python: active,
|
|
275
|
+
state: 'missing',
|
|
276
|
+
installed: false,
|
|
277
|
+
missing: st.missing.slice(),
|
|
278
|
+
message:
|
|
279
|
+
'OCR 依赖未安装,且自动安装已被关闭(config.pythonDeps.autoInstall=false):' +
|
|
280
|
+
'请自行安装 ddddocr 与 rapidocr_onnxruntime,或设置 CHAOXING_PYTHON 指向已装好的 python。',
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
if (lastFailAt && Date.now() - lastFailAt < FAIL_BACKOFF && !force) {
|
|
284
|
+
return { ok: false, python: active, state: 'failed', installed: false, missing: st.missing, message: st.message, backoff: true };
|
|
285
|
+
}
|
|
286
|
+
const t0 = Date.now();
|
|
287
|
+
const snap = await check({ explicit, log });
|
|
288
|
+
if (snap.state === 'ready') return { ok: true, python: active, state: 'ready', installed: false, missing: [], message: '' };
|
|
289
|
+
const s = await install({ explicit, log, onProgress });
|
|
290
|
+
return { ...s, ms: Date.now() - t0 };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function progressFn(onProgress, log) {
|
|
294
|
+
let last = 0;
|
|
295
|
+
return (line) => {
|
|
296
|
+
const m = /(\d{1,3})%/.exec(line);
|
|
297
|
+
if (m) {
|
|
298
|
+
const pct = Math.min(100, Number(m[1]));
|
|
299
|
+
if (pct !== st.progress) st.progress = pct;
|
|
300
|
+
if (Date.now() - last > 4000) {
|
|
301
|
+
last = Date.now();
|
|
302
|
+
log?.({ ev: 'pydeps-progress', pct });
|
|
303
|
+
try {
|
|
304
|
+
onProgress?.(pct);
|
|
305
|
+
} catch {
|
|
306
|
+
/* ignore */
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
if (/error|Errno|失败|Could not|No matching|Downloading/i.test(line) && !/^\s*$/.test(line)) {
|
|
312
|
+
st.detail = line.slice(0, 200);
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** 建 venv(--system-site-packages 继承 numpy/Pillow)+ 按镜像顺序 pip 安装 */
|
|
318
|
+
async function install({ explicit, log, onProgress }) {
|
|
319
|
+
const dir = depsDir();
|
|
320
|
+
ensureDir(dir);
|
|
321
|
+
const builder = basePython(explicit);
|
|
322
|
+
if (!builder) {
|
|
323
|
+
st.state = 'failed';
|
|
324
|
+
st.message = '找不到可用的 python:请设置 CHAOXING_PYTHON 指向已装好依赖的 python。';
|
|
325
|
+
return { ok: false, python: '', state: 'failed', installed: false, missing: MODULES.slice(), message: st.message };
|
|
326
|
+
}
|
|
327
|
+
st.state = 'installing';
|
|
328
|
+
st.progress = 0;
|
|
329
|
+
st.message = '正在准备 OCR 运行环境(首次约 1-3 分钟,需要联网)…';
|
|
330
|
+
st.at = Date.now();
|
|
331
|
+
log?.({ ev: 'pydeps-install-start', builder, dir });
|
|
332
|
+
const py = venvPython();
|
|
333
|
+
let baseOk = false;
|
|
334
|
+
try {
|
|
335
|
+
const b = await probe(builder, { timeoutMs: 60000 });
|
|
336
|
+
baseOk = !!b.py;
|
|
337
|
+
} catch {
|
|
338
|
+
baseOk = false;
|
|
339
|
+
}
|
|
340
|
+
if (!baseOk) {
|
|
341
|
+
st.state = 'failed';
|
|
342
|
+
st.lastError = `基础 python 不可用:${builder}`;
|
|
343
|
+
st.message = `OCR 依赖安装失败:${st.lastError}。请检查 python 是否可执行,或设置 CHAOXING_PYTHON。`;
|
|
344
|
+
log?.({ ev: 'pydeps-install-fail', why: st.lastError });
|
|
345
|
+
return { ok: false, python: '', state: 'failed', installed: false, missing: MODULES.slice(), message: st.message };
|
|
346
|
+
}
|
|
347
|
+
// 老 venv 可能指向已经没了的 runtime python(DSH 升级/换版本):先探一下,坏的直接删掉重建
|
|
348
|
+
if (exists(py)) {
|
|
349
|
+
const alive = await runExe(py, ['-c', 'import sys; print(sys.version.split()[0])'], { timeoutMs: 30000 });
|
|
350
|
+
if (alive.code !== 0) {
|
|
351
|
+
try {
|
|
352
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
353
|
+
} catch {
|
|
354
|
+
/* ignore */
|
|
355
|
+
}
|
|
356
|
+
log?.({ ev: 'pydeps-venv-stale', dir });
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
// venv 坏掉(DSH 升级删了 runtime python / 半装状态)就重建
|
|
360
|
+
if (!exists(py)) {
|
|
361
|
+
const mk = await runExe(builder, ['-m', 'venv', '--system-site-packages', dir], { env: { ...process.env, PYTHONIOENCODING: 'utf-8' }, timeoutMs: 180000 });
|
|
362
|
+
if (mk.code !== 0 || !exists(py)) {
|
|
363
|
+
st.state = 'failed';
|
|
364
|
+
st.lastError = (mk.stderr || mk.stdout || '').trim().slice(-400) || `venv 创建失败(${mk.code})`;
|
|
365
|
+
st.message = `OCR 依赖安装失败:无法创建 python 环境(${st.lastError.slice(0, 160)})`;
|
|
366
|
+
log?.({ ev: 'pydeps-venv-fail', why: st.lastError });
|
|
367
|
+
return { ok: false, python: '', state: 'failed', installed: false, missing: MODULES.slice(), message: st.message };
|
|
368
|
+
}
|
|
369
|
+
log?.({ ev: 'pydeps-venv', dir });
|
|
370
|
+
}
|
|
371
|
+
const onLine = progressFn(onProgress, log);
|
|
372
|
+
let lastErr = '';
|
|
373
|
+
for (const mirror of MIRRORS) {
|
|
374
|
+
st.detail = `正在从${mirror.name}源安装…`;
|
|
375
|
+
log?.({ ev: 'pydeps-pip', mirror: mirror.name });
|
|
376
|
+
const args = [
|
|
377
|
+
'-m', 'pip', 'install',
|
|
378
|
+
'--disable-pip-version-check', '--no-input', '--no-warn-script-location',
|
|
379
|
+
'--timeout', '30', '--retries', '2',
|
|
380
|
+
];
|
|
381
|
+
if (mirror.url) args.push('-i', mirror.url);
|
|
382
|
+
args.push(...PIP_PKGS);
|
|
383
|
+
const r = await runExe(py, args, { env: { ...process.env, PYTHONIOENCODING: 'utf-8' }, timeoutMs: INSTALL_TIMEOUT, onLine });
|
|
384
|
+
if (r.code === 0) {
|
|
385
|
+
const info = await probe(py);
|
|
386
|
+
if (info.ok) {
|
|
387
|
+
st.installAt = Date.now();
|
|
388
|
+
lastFailAt = 0;
|
|
389
|
+
markReady(py, info);
|
|
390
|
+
log?.({ ev: 'pydeps-install-ok', mirror: mirror.name, python: py, py: info.py });
|
|
391
|
+
return { ok: true, python: py, state: 'ready', installed: true, missing: [], message: '' };
|
|
392
|
+
}
|
|
393
|
+
lastErr = `装完了但导入失败:${missingText(info)}`;
|
|
394
|
+
break; // 装进去却 import 不了(通常是 VC++ 运行库/DLL 问题),换源没用
|
|
395
|
+
}
|
|
396
|
+
lastErr = (r.stderr || r.stdout || '').trim().split(/\r?\n/).slice(-6).join(' ').slice(-400) || `pip 退出码 ${r.code}`;
|
|
397
|
+
log?.({ ev: 'pydeps-pip-fail', mirror: mirror.name, code: r.code, why: lastErr.slice(0, 200) });
|
|
398
|
+
}
|
|
399
|
+
st.state = 'failed';
|
|
400
|
+
st.lastError = lastErr;
|
|
401
|
+
st.message =
|
|
402
|
+
`OCR 依赖安装失败:${lastErr.slice(0, 300)}。` +
|
|
403
|
+
'章节测验的字体解码和验证码识别需要 ddddocr + rapidocr_onnxruntime:可检查网络后点面板「安装依赖」重试,' +
|
|
404
|
+
'或设置环境变量 CHAOXING_PYTHON 指向已装好依赖的 python。';
|
|
405
|
+
lastFailAt = Date.now();
|
|
406
|
+
st.at = Date.now();
|
|
407
|
+
return { ok: false, python: '', state: 'failed', installed: false, missing: MODULES.slice(), message: st.message };
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** 给面板/doctor 用的快照(同步,不触发探测) */
|
|
411
|
+
export function status() {
|
|
412
|
+
return {
|
|
413
|
+
state: st.state,
|
|
414
|
+
python: active || st.python || '',
|
|
415
|
+
base: baseCached || '',
|
|
416
|
+
venv: venvPython(),
|
|
417
|
+
venvExists: exists(venvPython()),
|
|
418
|
+
pyVersion: st.pyVersion,
|
|
419
|
+
missing: st.missing.slice(),
|
|
420
|
+
message: st.message,
|
|
421
|
+
detail: st.detail,
|
|
422
|
+
progress: st.progress,
|
|
423
|
+
lastError: st.lastError,
|
|
424
|
+
installAt: st.installAt,
|
|
425
|
+
at: st.at,
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** 在线程外跑一次「装好没有」的探测并写面板状态(apply 时后台调用) */
|
|
430
|
+
export function warm({ explicit, log } = {}) {
|
|
431
|
+
setTimeout(() => {
|
|
432
|
+
check({ explicit, log }).catch(() => {});
|
|
433
|
+
}, 5000).unref?.();
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** 判断一个报错是不是「依赖没装」而不是别的问题 */
|
|
437
|
+
export function isDepsError(msg) {
|
|
438
|
+
return /ModuleNotFoundError|No module named|ImportError|DLL load failed|onnxruntime|ddddocr|rapidocr/i.test(String(msg || ''));
|
|
439
|
+
}
|
package/lib/python.mjs
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
|
-
//
|
|
1
|
+
// 调用 Python 做 OCR(验证码 / 反爬字体映射)。
|
|
2
|
+
// 解释器顺序:显式配置 > CHAOXING_PYTHON > 已装好 OCR 依赖的插件 venv > DSH runtime python > PATH。
|
|
3
|
+
// 依赖(ddddocr / rapidocr_onnxruntime)由 pydeps.mjs 在首次需要时自动安装,见那个文件。
|
|
2
4
|
import fs from 'node:fs';
|
|
3
|
-
import os from 'node:os';
|
|
4
5
|
import path from 'node:path';
|
|
5
6
|
import { spawn } from 'node:child_process';
|
|
6
7
|
import { captchaScript, fontmapScript } from './paths.mjs';
|
|
7
|
-
|
|
8
|
-
let cachedPython = '';
|
|
9
|
-
let scanAt = 0;
|
|
8
|
+
import { activePython, basePython, ensure, isDepsError, status as pydepsStatus } from './pydeps.mjs';
|
|
10
9
|
|
|
11
10
|
function exists(p) {
|
|
12
11
|
try {
|
|
@@ -16,39 +15,51 @@ function exists(p) {
|
|
|
16
15
|
}
|
|
17
16
|
}
|
|
18
17
|
|
|
19
|
-
/** 找可用 python
|
|
18
|
+
/** 找可用 python:显式 > 环境变量 > 已就绪的 venv > DSH runtime python > PATH */
|
|
20
19
|
export function pythonPath(explicit) {
|
|
21
|
-
for (const p of [explicit, process.env.CHAOXING_PYTHON,
|
|
20
|
+
for (const p of [explicit, process.env.CHAOXING_PYTHON, activePython(), basePython(explicit)]) {
|
|
22
21
|
if (exists(p)) return p;
|
|
23
22
|
}
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
const
|
|
23
|
+
return 'python';
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** 依赖缺失时抛出的错误:带上可执行的下一步,别让用户只看到 ModuleNotFoundError */
|
|
27
|
+
function depsError(dep, cause) {
|
|
28
|
+
const msg =
|
|
29
|
+
(dep && dep.message) ||
|
|
30
|
+
`OCR 依赖未就绪(${String((cause && cause.message) || cause || '').slice(0, 200)})`;
|
|
31
|
+
const e = new Error(msg);
|
|
32
|
+
e.deps = dep || null;
|
|
33
|
+
e.code = 'CHAOXING_OCR_DEPS';
|
|
34
|
+
return e;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 先跑;碰到「依赖没装」再装上重跑一次。装不上就把可读原因抛出去。 */
|
|
38
|
+
async function runWithDeps(run, opts = {}) {
|
|
39
|
+
const log = typeof opts.log === 'function' ? opts.log : null;
|
|
40
|
+
// 已知缺失/上次装失败:先补装,省得先抛一次 ModuleNotFoundError
|
|
41
|
+
const pre = pydepsStatus();
|
|
42
|
+
if (pre.state === 'missing' || pre.state === 'failed') {
|
|
43
|
+
log?.({ ev: 'ocr-deps-install', why: '首次需要字体解码/验证码识别,正在自动安装识别依赖(约 150MB,只装一次)' });
|
|
44
|
+
const d = await ensure({ explicit: opts.python, log });
|
|
45
|
+
if (!d.ok) throw depsError(d);
|
|
46
|
+
log?.({ ev: 'ocr-deps-ready', python: d.python, ms: d.ms });
|
|
47
|
+
}
|
|
30
48
|
try {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
return p;
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
} catch {
|
|
45
|
-
/* ignore */
|
|
49
|
+
return await run();
|
|
50
|
+
} catch (e) {
|
|
51
|
+
if (!isDepsError(e.message)) throw e;
|
|
52
|
+
log?.({ ev: 'ocr-deps-missing', err: String(e.message || '').slice(0, 200) });
|
|
53
|
+
log?.({ ev: 'ocr-deps-install', why: '缺少识别依赖,正在自动安装(约 150MB,只装一次),稍等' });
|
|
54
|
+
const d = await ensure({ explicit: opts.python, force: true, log });
|
|
55
|
+
if (!d.ok) throw depsError(d, e);
|
|
56
|
+
log?.({ ev: 'ocr-deps-ready', python: d.python, ms: d.ms });
|
|
57
|
+
return run();
|
|
46
58
|
}
|
|
47
|
-
return 'python';
|
|
48
59
|
}
|
|
49
60
|
|
|
50
61
|
export function runPython(script, args, { timeoutMs = 300000, python } = {}) {
|
|
51
|
-
const exe = pythonPath(python);
|
|
62
|
+
const exe = activePython() || pythonPath(python);
|
|
52
63
|
if (!exe) return Promise.reject(new Error('找不到可用的 python,请设置环境变量 CHAOXING_PYTHON'));
|
|
53
64
|
return new Promise((resolve, reject) => {
|
|
54
65
|
const child = spawn(exe, [script, ...args], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
@@ -105,14 +116,16 @@ function lastJsonLine(text) {
|
|
|
105
116
|
return null;
|
|
106
117
|
}
|
|
107
118
|
|
|
108
|
-
/** 识别 4 位验证码图片 → { text, engine } */
|
|
119
|
+
/** 识别 4 位验证码图片 → { text, engine }(依赖缺失时自动装一次再重试) */
|
|
109
120
|
export async function ocrCaptcha(imagePath, opts = {}) {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
121
|
+
return runWithDeps(async () => {
|
|
122
|
+
const r = await runPython(captchaScript, ['--image', imagePath], { timeoutMs: opts.timeoutMs || 30000, python: opts.python, log: opts.log });
|
|
123
|
+
const json = lastJsonLine(r.stdout);
|
|
124
|
+
if (!json || !json.text) {
|
|
125
|
+
throw new Error(`验证码识别失败(code=${r.code}):${(r.stderr || r.stdout || '').slice(-300)}`);
|
|
126
|
+
}
|
|
127
|
+
return { text: String(json.text).trim(), engine: json.engine || 'ddddocr', raw: r.stdout.slice(-300) };
|
|
128
|
+
}, opts);
|
|
116
129
|
}
|
|
117
130
|
|
|
118
131
|
/** 从 stdout 里找最后一行可解析的 JSON 对象(fontmap.py --json-stdout 把映射表打成一行) */
|
|
@@ -161,7 +174,7 @@ function mapStats(map, result) {
|
|
|
161
174
|
* 建立字体映射:ttf → { 乱码字: 真字 }。
|
|
162
175
|
* outJson 已存在且字符覆盖时直接复用。
|
|
163
176
|
*/
|
|
164
|
-
|
|
177
|
+
async function buildFontMapOnce(ttfPath, outJson, chars, opts = {}) {
|
|
165
178
|
if (exists(outJson)) {
|
|
166
179
|
try {
|
|
167
180
|
const cached = JSON.parse(fs.readFileSync(outJson, 'utf8'));
|
|
@@ -211,6 +224,11 @@ export async function buildFontMap(ttfPath, outJson, chars, opts = {}) {
|
|
|
211
224
|
return { map, cached: false, ...mapStats(map, result), stdout: r.stdout.slice(-200) };
|
|
212
225
|
}
|
|
213
226
|
|
|
227
|
+
/** 建字体映射(依赖缺失时自动装一次再重试) */
|
|
228
|
+
export async function buildFontMap(ttfPath, outJson, chars, opts = {}) {
|
|
229
|
+
return runWithDeps(() => buildFontMapOnce(ttfPath, outJson, chars, opts), opts);
|
|
230
|
+
}
|
|
231
|
+
|
|
214
232
|
/** 用映射表解码一串乱码文字 */
|
|
215
233
|
export function decodeText(text, map) {
|
|
216
234
|
if (!text || !map) return String(text || '');
|
package/lib/screen.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import path from 'node:path';
|
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
5
|
import { sleep } from './util.mjs';
|
|
6
6
|
import { pythonPath } from './python.mjs';
|
|
7
|
+
import { activePython } from './pydeps.mjs';
|
|
7
8
|
import { paths } from './paths.mjs';
|
|
8
9
|
|
|
9
10
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
@@ -27,7 +28,7 @@ export class Screen {
|
|
|
27
28
|
|
|
28
29
|
async ocr(file) {
|
|
29
30
|
const shot = await this.shot(file);
|
|
30
|
-
const r = spawnSync(this.python, [OCR_SCRIPT, shot], {
|
|
31
|
+
const r = spawnSync(activePython() || this.python, [OCR_SCRIPT, shot], {
|
|
31
32
|
encoding: 'utf8',
|
|
32
33
|
timeout: 120000,
|
|
33
34
|
maxBuffer: 64 * 1024 * 1024,
|
package/lib/uibridge.mjs
CHANGED
|
@@ -371,6 +371,14 @@ export function startUiBridge({ deps, config = {}, log = () => {}, webServer = n
|
|
|
371
371
|
return null;
|
|
372
372
|
}
|
|
373
373
|
})(),
|
|
374
|
+
// OCR 依赖状态:面板据此显示「缺依赖 / 正在装 / 装失败」,不用等测验 abort 了才发现
|
|
375
|
+
pydeps: (() => {
|
|
376
|
+
try {
|
|
377
|
+
return deps.pydeps && typeof deps.pydeps.status === 'function' ? deps.pydeps.status() : null;
|
|
378
|
+
} catch {
|
|
379
|
+
return null;
|
|
380
|
+
}
|
|
381
|
+
})(),
|
|
374
382
|
// 桌面版结构化状态:面板据此渲染阶段/统计,不用再从展示文本里正则刮
|
|
375
383
|
desktop: (() => {
|
|
376
384
|
try {
|
|
@@ -1036,6 +1044,7 @@ export function startUiBridge({ deps, config = {}, log = () => {}, webServer = n
|
|
|
1036
1044
|
// 面板连通过来的请求计数:/health 里能直接看到面板到底有没有在轮询(诊断「未连接」用)
|
|
1037
1045
|
const hits = { server: 0, route: 0 };
|
|
1038
1046
|
let inputBusy = false;
|
|
1047
|
+
let pyInstalling = false;
|
|
1039
1048
|
|
|
1040
1049
|
const makeHandler = (via) => (req, res) => {
|
|
1041
1050
|
const origin = originOf(req);
|
|
@@ -1169,6 +1178,23 @@ export function startUiBridge({ deps, config = {}, log = () => {}, webServer = n
|
|
|
1169
1178
|
if (inflight.has(name)) {
|
|
1170
1179
|
return send(200, JSON.stringify({ ok: false, busy: true, text: `「${ACTION_LABELS[name] || name}」正在执行,请稍候再试` }));
|
|
1171
1180
|
}
|
|
1181
|
+
if (name === 'pydeps-install') {
|
|
1182
|
+
// 装依赖要几分钟:立刻回话、后台继续装,进度由 /state 的 pydeps 字段推给面板,
|
|
1183
|
+
// 免得面板的 90 秒请求超时先弹一个假的「失败」,而其实还在装。
|
|
1184
|
+
if (pyInstalling) return send(200, JSON.stringify({ ok: false, busy: true, text: 'OCR 依赖正在安装中,稍等,顶部会显示进度' }));
|
|
1185
|
+
const cur = deps.pydeps && typeof deps.pydeps.status === 'function' ? deps.pydeps.status() : null;
|
|
1186
|
+
if (cur && cur.state === 'ready') return send(200, JSON.stringify({ ok: true, text: 'OCR 依赖已经就绪,不需要重装' }));
|
|
1187
|
+
pyInstalling = true;
|
|
1188
|
+
Promise.resolve()
|
|
1189
|
+
.then(() => (deps.pydeps && typeof deps.pydeps.ensure === 'function' ? deps.pydeps.ensure({ force: true }) : { ok: false, message: '依赖模块未加载:请重启 DSH 后再试' }))
|
|
1190
|
+
.then((d) => log({ ev: 'ui-pydeps-install', ok: !!d.ok, message: d.ok ? '' : String(d.message || '').slice(0, 200) }))
|
|
1191
|
+
.catch((e) => log({ ev: 'ui-pydeps-install', ok: false, message: redact(String((e && e.message) || e)).slice(0, 200) }))
|
|
1192
|
+
.finally(() => {
|
|
1193
|
+
pyInstalling = false;
|
|
1194
|
+
invalidateMemo();
|
|
1195
|
+
});
|
|
1196
|
+
return send(200, JSON.stringify({ ok: true, text: '已开始安装 OCR 依赖(约 150MB,只装一次);顶部会显示进度,装完就能做章节测验了' }));
|
|
1197
|
+
};
|
|
1172
1198
|
inflight.add(name);
|
|
1173
1199
|
const run = actionChain.then(() => action(name, body));
|
|
1174
1200
|
actionChain = run.then(
|
|
@@ -1244,6 +1270,7 @@ export function startUiBridge({ deps, config = {}, log = () => {}, webServer = n
|
|
|
1244
1270
|
progress: '刷新进度',
|
|
1245
1271
|
web: '网页版',
|
|
1246
1272
|
desktop: '桌面版',
|
|
1273
|
+
'pydeps-install': '安装OCR依赖',
|
|
1247
1274
|
};
|
|
1248
1275
|
const inflight = new Set();
|
|
1249
1276
|
let actionChain = Promise.resolve();
|
package/lib/work.mjs
CHANGED
|
@@ -188,7 +188,7 @@ export async function solveWorkCaptcha(page, ctx = {}) {
|
|
|
188
188
|
}
|
|
189
189
|
let text = '';
|
|
190
190
|
try {
|
|
191
|
-
const out = await ocrCaptcha(file, { python: ctx.python });
|
|
191
|
+
const out = await ocrCaptcha(file, { python: ctx.python, log });
|
|
192
192
|
text = out.text;
|
|
193
193
|
} catch (e) {
|
|
194
194
|
log({ ev: 'work-captcha-ocr-fail', err: truncate(e.message, 140) });
|