@ggboy123/dsh-paper-reader 1.13.0 → 1.14.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/README.md +1 -1
- package/dist/babeldoc-install.js +145 -0
- package/dist/translate.js +10 -1
- package/dist/translation-options.js +17 -1
- package/lib/client.js +23 -4
- package/package.json +1 -1
- package/runtime/babeldoc-driver.py +70 -2
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
**English**: [README_EN.md](README_EN.md)
|
|
9
9
|
|
|
10
|
-
[DeepSeek Harness (dsh)](https://github.com/deepseek-ai/deepseek-harness) 插件:**论文伴读工作台** —— 文献库 + PDF 阅读器 + AI 伴读,回答自带页码、点页码跳回原文。当前版本 **v1.
|
|
10
|
+
[DeepSeek Harness (dsh)](https://github.com/deepseek-ai/deepseek-harness) 插件:**论文伴读工作台** —— 文献库 + PDF 阅读器 + AI 伴读,回答自带页码、点页码跳回原文。当前版本 **v1.14.0**。
|
|
11
11
|
|
|
12
12
|
> 💬 **QQ 交流群:1127244508** —— 安装/使用问题、功能建议、bug 反馈都欢迎来聊。
|
|
13
13
|
|
package/dist/babeldoc-install.js
CHANGED
|
@@ -469,3 +469,148 @@ export function ensureBabeldoc(dataDir, home, findExisting, onPhase) {
|
|
|
469
469
|
}
|
|
470
470
|
return inflight;
|
|
471
471
|
}
|
|
472
|
+
// ------------------ GPU 版面检测运行时(按需安装) ------------------
|
|
473
|
+
/**
|
|
474
|
+
* 版面检测 GPU 运行时包名(按设备与平台):
|
|
475
|
+
* - dml/auto + win32 → onnxruntime-directml(DirectML 通用 GPU,约 40MB,N/A/I 卡都能用);
|
|
476
|
+
* - cuda → 不自动装:onnxruntime-gpu 需要系统级 CUDA + cuDNN(2~3GB),失败率高且排障难,
|
|
477
|
+
* 留给用户手动装(文档写明);驱动侧对缺失如实回落 CPU;
|
|
478
|
+
* - 非 win32 → 不装:Linux 无 DirectML,macOS 上游已自动走 CoreML。
|
|
479
|
+
*/
|
|
480
|
+
export function layoutRuntimePackage(device, platform) {
|
|
481
|
+
if (platform !== 'win32')
|
|
482
|
+
return null;
|
|
483
|
+
return device === 'dml' || device === 'auto' ? 'onnxruntime-directml' : null;
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* 是否需要补装 DML 运行时。providers 为 null(探测不了)时一律不装——
|
|
487
|
+
* 宁可让驱动回落 CPU,也不在状态未知的 venv 上盲动。
|
|
488
|
+
* auto 已有任何 GPU provider(如用户手动装过 onnxruntime-gpu)就不装。
|
|
489
|
+
*/
|
|
490
|
+
export function needsDmlInstall(device, providers, platform) {
|
|
491
|
+
if (layoutRuntimePackage(device, platform) === null)
|
|
492
|
+
return false;
|
|
493
|
+
if (providers === null)
|
|
494
|
+
return false;
|
|
495
|
+
if (device === 'auto' && providers.includes('CUDAExecutionProvider'))
|
|
496
|
+
return false;
|
|
497
|
+
return !providers.includes('DmlExecutionProvider');
|
|
498
|
+
}
|
|
499
|
+
/** venv 的 onnxruntime 可用 provider;起不了进程/没有 onnxruntime 时返回 null(不判成错误)。 */
|
|
500
|
+
async function onnxProviders(py) {
|
|
501
|
+
try {
|
|
502
|
+
const out = await run(py, ['-c', 'import json, onnxruntime; print(json.dumps(onnxruntime.get_available_providers()))'], { timeout: 30_000 });
|
|
503
|
+
const parsed = JSON.parse(out.trim().split(/\r?\n/).pop() ?? 'null');
|
|
504
|
+
return Array.isArray(parsed) ? parsed.filter((p) => typeof p === 'string') : null;
|
|
505
|
+
}
|
|
506
|
+
catch {
|
|
507
|
+
return null;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
// 结果缓存(进程内):present/installed 跳过后续探测;安装失败也缓存——重试按翻译次数
|
|
511
|
+
// 反复烧几分钟下载不值,重启进程即重试。探测失败(null)不缓存,下次翻译再探。
|
|
512
|
+
const layoutRuntimeCache = new Map();
|
|
513
|
+
// 单例:多论文并发翻译只跑一次安装,其余等待同一条 promise(并发 pip 会互踩文件锁)。
|
|
514
|
+
let dmlInflight = null;
|
|
515
|
+
/**
|
|
516
|
+
* 按需确保 GPU 版面检测运行时(用户显式选了 dml/auto 才会真正动 venv)。
|
|
517
|
+
* - 已就位 → 'present'(零开销快速路径);
|
|
518
|
+
* - 缺失 → uv 通道装 onnxruntime-directml(uv 建的 venv 没有 pip,主安装链同理走 uv;
|
|
519
|
+
* 官方源失败镜像续装;没有 uv 时 ensurepip 自举后 pip 走国内镜像)→ 复核 provider 后返回 'installed';
|
|
520
|
+
* - 任何失败(网络/文件锁/装完 provider 仍缺)→ 如实 phase 提示 + 返回 'skipped',
|
|
521
|
+
* 驱动侧自动回落 CPU,翻译主流程不受影响。
|
|
522
|
+
* 只对插件自管 venv 的 python(translate.ts resolveDriverPython 解析出的绝对路径)操作;
|
|
523
|
+
* PATH/miniconda 里的 babeldoc 不碰——那是用户自己的环境。
|
|
524
|
+
*/
|
|
525
|
+
export async function ensureOnnxLayoutDevice(py, device, onPhase, home) {
|
|
526
|
+
// DPR_SKIP_ENGINE_ENSURE=1:受限环境/测试钩子,只跑现成引擎,别动 venv
|
|
527
|
+
if (process.env.DPR_SKIP_ENGINE_ENSURE === '1')
|
|
528
|
+
return 'skipped';
|
|
529
|
+
if (!py || !existsSync(py))
|
|
530
|
+
return 'skipped';
|
|
531
|
+
const cacheKey = `${py}\u0000${device}`;
|
|
532
|
+
const cached = layoutRuntimeCache.get(cacheKey);
|
|
533
|
+
if (cached === 'present' || cached === 'installed')
|
|
534
|
+
return cached;
|
|
535
|
+
if (cached === 'failed') {
|
|
536
|
+
onPhase('GPU 版面检测运行时此前安装失败,本次用 CPU 跑版面(重启后重试)…');
|
|
537
|
+
return 'skipped';
|
|
538
|
+
}
|
|
539
|
+
if (!dmlInflight) {
|
|
540
|
+
dmlInflight = (async () => {
|
|
541
|
+
const venvPy = py;
|
|
542
|
+
const pkg = layoutRuntimePackage(device, process.platform);
|
|
543
|
+
if (!pkg)
|
|
544
|
+
return 'skipped';
|
|
545
|
+
const providers = await onnxProviders(venvPy);
|
|
546
|
+
if (!needsDmlInstall(device, providers, process.platform)) {
|
|
547
|
+
if (providers && providers.includes('DmlExecutionProvider')) {
|
|
548
|
+
layoutRuntimeCache.set(cacheKey, 'present');
|
|
549
|
+
return 'present';
|
|
550
|
+
}
|
|
551
|
+
return 'skipped';
|
|
552
|
+
}
|
|
553
|
+
onPhase(`正在安装 GPU 版面检测运行时(${pkg},约 40MB)…`);
|
|
554
|
+
const installViaUv = async (indexEnv, timeout) => {
|
|
555
|
+
const uv = await findUv(home);
|
|
556
|
+
if (!uv)
|
|
557
|
+
throw new Error('uv 不可用');
|
|
558
|
+
await run(uv, ['pip', 'install', '--python', venvPy, pkg], { timeout, env: indexEnv });
|
|
559
|
+
};
|
|
560
|
+
const installViaPip = async () => {
|
|
561
|
+
// uv 建的 venv 默认没有 pip:先 ensurepip 自举再镜像轮询
|
|
562
|
+
await run(venvPy, ['-m', 'ensurepip', '--upgrade'], { timeout: 5 * 60_000 });
|
|
563
|
+
let lastErr = null;
|
|
564
|
+
for (const m of CN_MIRRORS) {
|
|
565
|
+
try {
|
|
566
|
+
await run(venvPy, [
|
|
567
|
+
'-m', 'pip', 'install', '--no-cache-dir', '--timeout', '120', '--retries', '3', '-i', m, pkg,
|
|
568
|
+
], { timeout: 15 * 60_000 });
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
catch (e) {
|
|
572
|
+
lastErr = e; // 换下一个镜像;已装成功的包 pip 会跳过,重试是断点续传式的
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
|
|
576
|
+
};
|
|
577
|
+
try {
|
|
578
|
+
try {
|
|
579
|
+
// 两段式:首段按探速选源、10min 快速失败;官方源失败 → 镜像续装 15min(与主安装链同款)
|
|
580
|
+
const indexEnv = await pickIndexEnv();
|
|
581
|
+
await installViaUv(indexEnv, 10 * 60_000);
|
|
582
|
+
}
|
|
583
|
+
catch (first) {
|
|
584
|
+
console.warn('[dsh-paper-reader] GPU 运行时官方/uv 通道失败,镜像续装:', first instanceof Error ? first.message : first);
|
|
585
|
+
onPhase(`正在安装 GPU 版面检测运行时(${pkg},镜像通道续装)…`);
|
|
586
|
+
try {
|
|
587
|
+
await installViaUv({ UV_DEFAULT_INDEX: UV_MIRROR, UV_INDEX_URL: UV_MIRROR }, 15 * 60_000);
|
|
588
|
+
}
|
|
589
|
+
catch (second) {
|
|
590
|
+
// uv 也没有(findUv 落空)→ venv 自举 pip 走国内镜像
|
|
591
|
+
await installViaPip();
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
catch (e) {
|
|
596
|
+
console.warn('[dsh-paper-reader] GPU 版面检测运行时安装失败,本次回落 CPU:', e instanceof Error ? e.message : e);
|
|
597
|
+
onPhase('GPU 版面检测运行时安装失败,本次用 CPU 跑版面…');
|
|
598
|
+
layoutRuntimeCache.set(cacheKey, 'failed');
|
|
599
|
+
return 'skipped';
|
|
600
|
+
}
|
|
601
|
+
// 装完复核:provider 真的出现才算成功(不粉饰「pip 说装好了」)
|
|
602
|
+
const after = await onnxProviders(venvPy);
|
|
603
|
+
if (after?.includes('DmlExecutionProvider')) {
|
|
604
|
+
layoutRuntimeCache.set(cacheKey, 'installed');
|
|
605
|
+
return 'installed';
|
|
606
|
+
}
|
|
607
|
+
console.warn('[dsh-paper-reader] onnxruntime-directml 安装完成但 DmlExecutionProvider 未出现(驱动/系统不支持?),本次回落 CPU');
|
|
608
|
+
onPhase('GPU 版面检测运行时未生效,本次用 CPU 跑版面…');
|
|
609
|
+
layoutRuntimeCache.set(cacheKey, 'failed');
|
|
610
|
+
return 'skipped';
|
|
611
|
+
})().finally(() => {
|
|
612
|
+
dmlInflight = null;
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
return dmlInflight;
|
|
616
|
+
}
|
package/dist/translate.js
CHANGED
|
@@ -13,7 +13,7 @@ import { join, dirname, basename, extname, isAbsolute } from 'node:path';
|
|
|
13
13
|
import { StringDecoder } from 'node:string_decoder';
|
|
14
14
|
import { fileURLToPath } from 'node:url';
|
|
15
15
|
import { dshHome } from "./library.js";
|
|
16
|
-
import { ensureBabeldoc } from "./babeldoc-install.js";
|
|
16
|
+
import { ensureBabeldoc, ensureOnnxLayoutDevice } from "./babeldoc-install.js";
|
|
17
17
|
import { isOpenCodeEndpoint, openCodeDriverEnv, openCodeSessionId } from "./opencode.js";
|
|
18
18
|
import { DEFAULT_TRANSLATION_RUN_OPTIONS } from "./translation-options.js";
|
|
19
19
|
export function zhPdfPath(ref) {
|
|
@@ -160,6 +160,12 @@ async function runPipeline(ref, dataDir, endpoint, hooks, options) {
|
|
|
160
160
|
return;
|
|
161
161
|
if (!bin)
|
|
162
162
|
throw new Error('找不到 babeldoc 可执行文件');
|
|
163
|
+
// 版面检测 GPU 运行时按需补装:用户显式选了 dml/auto 才动 venv(win32)。
|
|
164
|
+
// 失败如实 phase 提示并继续——驱动侧自动回落 CPU,翻译主流程不受影响。
|
|
165
|
+
// 注意给的是「与 babeldoc 同 venv 的 python」:PATH/用户自管的 babeldoc 不会被碰。
|
|
166
|
+
await ensureOnnxLayoutDevice(resolveDriverPython(bin), options.layoutDevice, setPhase, dshHome());
|
|
167
|
+
if (task.cancelled || tasks.get(ref.pdfPath) !== task)
|
|
168
|
+
return;
|
|
163
169
|
await launch(ref, dataDir, endpoint, bin, task, options);
|
|
164
170
|
}
|
|
165
171
|
catch (e) {
|
|
@@ -409,6 +415,9 @@ async function launch(ref, dataDir, endpoint, bin, task, options) {
|
|
|
409
415
|
PYTHONIOENCODING: 'utf-8',
|
|
410
416
|
DPR_SPLIT_TOKENS: String(options.splitTokens),
|
|
411
417
|
DPR_MAX_OUTPUT_TOKENS: String(options.maxOutputTokens),
|
|
418
|
+
// 版面检测推理设备:cpu=维持 babeldoc 原行为;dml/cuda/auto 交给驱动脚本
|
|
419
|
+
// 换 GPU provider,运行时缺失时驱动会如实回落 CPU 并写日志。
|
|
420
|
+
DPR_ONNX_DEVICE: options.layoutDevice ?? 'cpu',
|
|
412
421
|
...openCodeDriverEnv(ep.baseUrl, ocSession),
|
|
413
422
|
},
|
|
414
423
|
windowsHide: true,
|
|
@@ -3,13 +3,20 @@ export const DEFAULT_TRANSLATION_RUN_OPTIONS = Object.freeze({
|
|
|
3
3
|
splitTokens: 100000,
|
|
4
4
|
maxOutputTokens: 32768,
|
|
5
5
|
qps: 16,
|
|
6
|
+
layoutDevice: 'cpu',
|
|
6
7
|
});
|
|
7
8
|
const RULES = {
|
|
8
9
|
splitTokens: { min: 200, max: 128_000, label: '单段上下文上限' },
|
|
9
10
|
maxOutputTokens: { min: 0, max: 32_768, label: '单次输出上限' },
|
|
10
11
|
qps: { min: 1, max: 32, label: '并发请求数' },
|
|
11
12
|
};
|
|
12
|
-
/**
|
|
13
|
+
/** 版面检测设备的合法取值(含糊输入按默认 cpu 回落/拒绝)。 */
|
|
14
|
+
export const LAYOUT_DEVICES = ['cpu', 'dml', 'cuda', 'auto'];
|
|
15
|
+
function normalizeLayoutDevice(value) {
|
|
16
|
+
const s = typeof value === 'string' ? value.trim().toLowerCase() : '';
|
|
17
|
+
return LAYOUT_DEVICES.includes(s) ? s : null;
|
|
18
|
+
}
|
|
19
|
+
/** 损坏配置逐字段回落默认,不让一个脏数字/脏字符串阻断整篇翻译。 */
|
|
13
20
|
export function sanitizeTranslationRunOptions(input) {
|
|
14
21
|
const rec = typeof input === 'object' && input !== null ? input : {};
|
|
15
22
|
const out = { ...DEFAULT_TRANSLATION_RUN_OPTIONS };
|
|
@@ -20,6 +27,9 @@ export function sanitizeTranslationRunOptions(input) {
|
|
|
20
27
|
const { min, max } = RULES[key];
|
|
21
28
|
out[key] = Math.max(min, Math.min(max, Math.trunc(value)));
|
|
22
29
|
}
|
|
30
|
+
const device = normalizeLayoutDevice(rec.layoutDevice);
|
|
31
|
+
if (device)
|
|
32
|
+
out.layoutDevice = device;
|
|
23
33
|
return out;
|
|
24
34
|
}
|
|
25
35
|
/** HTTP 写入严格校验:不接受字符串、NaN、小数和越界值,避免“保存了但没按预期生效”。 */
|
|
@@ -36,5 +46,11 @@ export function validateTranslationRunOptions(input) {
|
|
|
36
46
|
}
|
|
37
47
|
out[key] = value;
|
|
38
48
|
}
|
|
49
|
+
if (rec.layoutDevice !== undefined) {
|
|
50
|
+
const device = normalizeLayoutDevice(rec.layoutDevice);
|
|
51
|
+
if (!device)
|
|
52
|
+
throw new Error(`版面检测设备必须是 ${LAYOUT_DEVICES.join(' / ')} 之一`);
|
|
53
|
+
out.layoutDevice = device;
|
|
54
|
+
}
|
|
39
55
|
return out;
|
|
40
56
|
}
|
package/lib/client.js
CHANGED
|
@@ -233,6 +233,8 @@ window.__ModuleLoader__.load({
|
|
|
233
233
|
setTranslateSplitTokens: '单段上下文上限(tokens)', setTranslateSplitHint: '超过后自动拆段;调小可减少单次上下文,调大可减少拆段次数。',
|
|
234
234
|
setTranslateMaxOutput: '单次输出上限(tokens)', setTranslateMaxOutputHint: '0 表示跟随端点默认,不传 max_tokens。',
|
|
235
235
|
setTranslateQps: '并发请求数(QPS)', setTranslateQpsHint: '过高容易触发端点限流;遇到 429 时可调低。',
|
|
236
|
+
setTranslateLayoutDevice: '版面检测设备', setTranslateLayoutDeviceHint: '分析版面的推理设备。Windows 选 GPU 后首次翻译会自动安装 onnxruntime-directml(约 40MB,DirectML 通用于 N/A/I 卡);不可用或安装失败会如实回落 CPU 继续翻译。CUDA 需自行安装 onnxruntime-gpu 与 CUDA/cuDNN。实测收益见项目 docs/evidence/gpu-layout-detection.md。',
|
|
237
|
+
setTranslateLayoutCpu: 'CPU(默认)', setTranslateLayoutAuto: '自动(优先 GPU)', setTranslateLayoutDml: 'GPU · DirectML(Windows 通用)', setTranslateLayoutCuda: 'GPU · CUDA(NVIDIA)',
|
|
236
238
|
setTranslateOptionsSave: '保存翻译参数', setTranslateOptionsSaved: '翻译参数已保存,下一篇 PDF 起生效',
|
|
237
239
|
setTranslateManualModel: '手动模型名', setTranslateUse: '使用', setTranslateUsing: '使用中',
|
|
238
240
|
setTranslateFollowSet: '已恢复为跟随 Harness,自定义配置已保留',
|
|
@@ -362,6 +364,8 @@ window.__ModuleLoader__.load({
|
|
|
362
364
|
setTranslateSplitTokens: 'Context per chunk (tokens)', setTranslateSplitHint: 'Longer chunks are split automatically. Lower this to reduce per-request context; raise it for fewer requests.',
|
|
363
365
|
setTranslateMaxOutput: 'Output cap per request (tokens)', setTranslateMaxOutputHint: '0 uses the provider default and omits max_tokens.',
|
|
364
366
|
setTranslateQps: 'Requests per second (QPS)', setTranslateQpsHint: 'High values can trigger rate limits. Lower this after HTTP 429 responses.',
|
|
367
|
+
setTranslateLayoutDevice: 'Layout detection device', setTranslateLayoutDeviceHint: 'Inference device for page layout analysis. On Windows, choosing GPU auto-installs onnxruntime-directml on first translation (~40MB; DirectML works on NVIDIA/AMD/Intel); it falls back to CPU honestly if unavailable or the install fails. CUDA requires manually installing onnxruntime-gpu with CUDA/cuDNN. Measured gains: docs/evidence/gpu-layout-detection.md in the project repo.',
|
|
368
|
+
setTranslateLayoutCpu: 'CPU (default)', setTranslateLayoutAuto: 'Auto (prefer GPU)', setTranslateLayoutDml: 'GPU · DirectML (Windows universal)', setTranslateLayoutCuda: 'GPU · CUDA (NVIDIA)',
|
|
365
369
|
setTranslateOptionsSave: 'Save translation options', setTranslateOptionsSaved: 'Translation options saved; applies to the next PDF task',
|
|
366
370
|
setTranslateManualModel: 'Manual model ID', setTranslateUse: 'Use', setTranslateUsing: 'In use',
|
|
367
371
|
setTranslateFollowSet: 'Translation now follows Harness; custom endpoints are kept',
|
|
@@ -1173,11 +1177,14 @@ window.__ModuleLoader__.load({
|
|
|
1173
1177
|
const S = {
|
|
1174
1178
|
// 侧栏树自己滚动:root 必须是有界 flex 列,head 固定、tree 占满剩余高度并 overflow-y:auto。
|
|
1175
1179
|
// 否则论文一多,整棵树被宿主侧栏 overflow 裁掉,底部条目滚不到也点不到(issue #30-②)。
|
|
1180
|
+
// 注意 flex-basis 必须 auto 不能 0:宿主槽位(桌面端侧栏)不一定给确定高度,
|
|
1181
|
+
// basis:0 在无高父容器里把树塌成 0 高——徽章有数、树整片空白(#32 回归,实测)。
|
|
1182
|
+
// basis:auto 两种环境都对:父高确定→占满并滚动;父高不定→按内容撑开。
|
|
1176
1183
|
root: { padding: '4px 0 8px', fontSize: '13px', color: 'var(--dsw-alias-label-primary, #24292f)', display: 'flex', flexDirection: 'column', height: '100%', maxHeight: '100%', minHeight: 0, overflow: 'hidden', boxSizing: 'border-box' },
|
|
1177
1184
|
head: { display: 'flex', alignItems: 'center', gap: '3px', minHeight: '32px', padding: '3px 8px 5px 12px', fontSize: '12px', fontWeight: 600, color: 'var(--dsw-alias-label-secondary, #656d76)', flex: 'none' },
|
|
1178
1185
|
headTitle: { display: 'flex', alignItems: 'center', gap: '6px', flex: 1, minWidth: 0 },
|
|
1179
1186
|
iconBtn: { width: '24px', height: '24px', flex: 'none', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', border: 'none', borderRadius: '6px', background: 'none', color: 'inherit', padding: 0 },
|
|
1180
|
-
treeScroll: { flex: '1 1
|
|
1187
|
+
treeScroll: { flex: '1 1 auto', minHeight: 0, overflowY: 'auto', overflowX: 'hidden', overscrollBehavior: 'contain' },
|
|
1181
1188
|
// 页内弹窗(Electron 无 window.prompt)与空库入口按钮
|
|
1182
1189
|
// 主按钮固定蓝底白字:部分深色主题把 button-primary-fill/foreground 同时映射成白色(issue #20)。
|
|
1183
1190
|
btnPrimary: { fontSize: '13px', padding: '5px 14px', borderRadius: '6px', border: 'none', cursor: 'pointer', background: '#1f6feb', color: '#fff' },
|
|
@@ -2260,7 +2267,7 @@ window.__ModuleLoader__.load({
|
|
|
2260
2267
|
const [providerId, setProviderId] = useState('deepseek')
|
|
2261
2268
|
const [draft, setDraft] = useState({ id: 'new', baseUrl: TRANSLATE_PROVIDERS[0].baseUrl, model: '', apiKey: '' })
|
|
2262
2269
|
const [models, setModels] = useState([])
|
|
2263
|
-
const [options, setOptions] = useState({ splitTokens: 100000, maxOutputTokens: 32768, qps: 16 })
|
|
2270
|
+
const [options, setOptions] = useState({ splitTokens: 100000, maxOutputTokens: 32768, qps: 16, layoutDevice: 'cpu' })
|
|
2264
2271
|
const [manualModel, setManualModel] = useState(false)
|
|
2265
2272
|
const [busy, setBusy] = useState('')
|
|
2266
2273
|
const [msg, setMsg] = useState(null)
|
|
@@ -2273,7 +2280,7 @@ window.__ModuleLoader__.load({
|
|
|
2273
2280
|
modelRequest.current += 1
|
|
2274
2281
|
return api('/translate/config').then((d) => {
|
|
2275
2282
|
setCfg(d)
|
|
2276
|
-
setOptions(d.options || { splitTokens: 100000, maxOutputTokens: 32768, qps: 16 })
|
|
2283
|
+
setOptions(d.options || { splitTokens: 100000, maxOutputTokens: 32768, qps: 16, layoutDevice: 'cpu' })
|
|
2277
2284
|
setMode(d.mode === 'follow' ? 'follow' : 'custom')
|
|
2278
2285
|
const saved = (d.endpoints || []).filter((e) => e.source !== 'harness')
|
|
2279
2286
|
const active = saved.find((e) => e.id === d.activeId) || saved[0] || null
|
|
@@ -2372,7 +2379,7 @@ window.__ModuleLoader__.load({
|
|
|
2372
2379
|
setBusy('options'); setMsg(null)
|
|
2373
2380
|
try {
|
|
2374
2381
|
const d = await api('/translate/config/options', {
|
|
2375
|
-
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ splitTokens: Number(options.splitTokens), maxOutputTokens: Number(options.maxOutputTokens), qps: Number(options.qps) }),
|
|
2382
|
+
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ splitTokens: Number(options.splitTokens), maxOutputTokens: Number(options.maxOutputTokens), qps: Number(options.qps), layoutDevice: options.layoutDevice || 'cpu' }),
|
|
2376
2383
|
})
|
|
2377
2384
|
setOptions(d.options)
|
|
2378
2385
|
setMsg({ ok: true, text: t('setTranslateOptionsSaved') })
|
|
@@ -2417,6 +2424,17 @@ window.__ModuleLoader__.load({
|
|
|
2417
2424
|
h('p', { style: { ...small, margin: '5px 0 0' } }, hint),
|
|
2418
2425
|
)
|
|
2419
2426
|
|
|
2427
|
+
const LAYOUT_DEVICE_KEY = { cpu: 'setTranslateLayoutCpu', auto: 'setTranslateLayoutAuto', dml: 'setTranslateLayoutDml', cuda: 'setTranslateLayoutCuda' }
|
|
2428
|
+
const layoutDeviceField = () => h('div', { style: { marginTop: 10 } },
|
|
2429
|
+
h('label', { style: { ...SET.label, margin: '0 0 4px' } }, t('setTranslateLayoutDevice')),
|
|
2430
|
+
h('select', {
|
|
2431
|
+
value: options.layoutDevice || 'cpu', 'data-dpr-translate-option': 'layoutDevice',
|
|
2432
|
+
style: SET.input,
|
|
2433
|
+
onChange: (e) => setOptions({ ...options, layoutDevice: e.target.value }),
|
|
2434
|
+
}, Object.keys(LAYOUT_DEVICE_KEY).map((c) => h('option', { key: c, value: c }, t(LAYOUT_DEVICE_KEY[c])))),
|
|
2435
|
+
h('p', { style: { ...small, margin: '5px 0 0' } }, t('setTranslateLayoutDeviceHint')),
|
|
2436
|
+
)
|
|
2437
|
+
|
|
2420
2438
|
return h('div', { style: { ...SET.card, padding: 0, overflow: 'hidden' }, 'data-dsh-plugin': 'dsh-paper-reader', 'data-dsh-part': 'settings-card', 'data-dpr-translate-settings': mode },
|
|
2421
2439
|
h('div', { style: { padding: '16px 16px 14px', borderBottom: '1px solid var(--dsw-alias-border-l1, #e5e7ec)' } },
|
|
2422
2440
|
h('h3', { style: SET.title }, t('setTranslateTitle')),
|
|
@@ -2491,6 +2509,7 @@ window.__ModuleLoader__.load({
|
|
|
2491
2509
|
optionField('splitTokens', t('setTranslateSplitTokens'), t('setTranslateSplitHint'), 200, 128000),
|
|
2492
2510
|
optionField('maxOutputTokens', t('setTranslateMaxOutput'), t('setTranslateMaxOutputHint'), 0, 32768),
|
|
2493
2511
|
optionField('qps', t('setTranslateQps'), t('setTranslateQpsHint'), 1, 32),
|
|
2512
|
+
layoutDeviceField(),
|
|
2494
2513
|
h('button', { type: 'button', 'data-dpr-translate-options-save': '', style: { ...SET.btnGhost, marginTop: 12 }, disabled: busy === 'options', onClick: saveOptions }, busy === 'options' ? t('setSaving') : t('setTranslateOptionsSave')),
|
|
2495
2514
|
),
|
|
2496
2515
|
),
|
package/package.json
CHANGED
|
@@ -19,6 +19,10 @@
|
|
|
19
19
|
DPR_MAX_OUTPUT_TOKENS 单次请求的 max_tokens 上限,默认 32768;0 = 不传该参数
|
|
20
20
|
DPR_SPLIT_TOKENS 触发拆分的输入上限(估算 token),默认 100000
|
|
21
21
|
DPR_OPENCODE_SESSION OpenCode Go 的稳定会话 ID;设置后每次 LLM 请求都带 x-opencode-session
|
|
22
|
+
DPR_ONNX_DEVICE 版面检测(DocLayout-YOLO ONNX)的推理设备:
|
|
23
|
+
cpu=不干预,维持 babeldoc 原行为(上游只挑 CPU provider);
|
|
24
|
+
dml=DirectML、cuda=CUDA、auto=按可用性挑(先 CUDA 后 DML)。
|
|
25
|
+
运行时缺对应 provider 或 session 建不起来时如实回落 CPU 并打日志。
|
|
22
26
|
DPR_DEBUG=1 额外把补丁动作打到 stderr
|
|
23
27
|
"""
|
|
24
28
|
|
|
@@ -54,7 +58,7 @@ def emit(payload: dict) -> None:
|
|
|
54
58
|
|
|
55
59
|
_STDOUT_LOCK = threading.Lock()
|
|
56
60
|
try:
|
|
57
|
-
line = PREFIX + " " + json.dumps(payload, ensure_ascii=False) + "\n"
|
|
61
|
+
line = PREFIX + " " + json.dumps({"ts": round(time.time(), 3), **payload}, ensure_ascii=False) + "\n"
|
|
58
62
|
with _STDOUT_LOCK:
|
|
59
63
|
sys.stdout.write(line)
|
|
60
64
|
sys.stdout.flush()
|
|
@@ -83,6 +87,7 @@ def _env_int(name: str, default: int) -> int:
|
|
|
83
87
|
MAX_OUT = _env_int("DPR_MAX_OUTPUT_TOKENS", 32768)
|
|
84
88
|
SPLIT_TOKENS = max(200, _env_int("DPR_SPLIT_TOKENS", 100000))
|
|
85
89
|
OPENCODE_SESSION = os.environ.get("DPR_OPENCODE_SESSION", "").strip()
|
|
90
|
+
LAYOUT_DEVICE = (os.environ.get("DPR_ONNX_DEVICE", "") or "cpu").strip().lower()
|
|
86
91
|
DEBUG = os.environ.get("DPR_DEBUG", "") not in ("", "0", "false", "False")
|
|
87
92
|
REPORT_MIN_INTERVAL = 0.35 # 进度事件最小间隔(秒),别把 stdout 刷爆
|
|
88
93
|
|
|
@@ -363,14 +368,77 @@ def install_translation() -> None:
|
|
|
363
368
|
return stats
|
|
364
369
|
|
|
365
370
|
|
|
371
|
+
# --------------------------------------------------------------------------
|
|
372
|
+
# 补丁 3:版面检测走 GPU(可选;DPR_ONNX_DEVICE)
|
|
373
|
+
# babeldoc 的 docvision/doclayout.py 出于稳定性只挑 CPU provider(macOS 除外,
|
|
374
|
+
# CoreML 自动启用),所以装了 onnxruntime-gpu/directml 也只会在 CPU 上推理。
|
|
375
|
+
# 这里按用户显式要求替换 provider 列表;GPU 建不起来就如实退回 CPU,不留半开状态。
|
|
376
|
+
# 注意 babeldoc 逐页推理(batch=1),GPU 吃不满,收益见 docs/evidence/gpu-layout-detection.md。
|
|
377
|
+
# --------------------------------------------------------------------------
|
|
378
|
+
_GPU_PROVIDER_BY_DEVICE = {
|
|
379
|
+
"cuda": "CUDAExecutionProvider",
|
|
380
|
+
"dml": "DmlExecutionProvider",
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def resolve_layout_providers() -> list:
|
|
385
|
+
"""把 DPR_ONNX_DEVICE 折算成 provider 列表;空列表 = 维持 babeldoc 原行为。
|
|
386
|
+
|
|
387
|
+
- cpu/未设置:不干预(含 macOS——上游自己会切 CoreML 静态输入路径)。
|
|
388
|
+
- auto:先 CUDA 后 DirectML,装了哪个用哪个;都没有就回 CPU。
|
|
389
|
+
- cuda/dml:点名后端;对应运行时没装就如实回落 CPU 并打日志。
|
|
390
|
+
"""
|
|
391
|
+
if LAYOUT_DEVICE in ("", "cpu"):
|
|
392
|
+
return []
|
|
393
|
+
try:
|
|
394
|
+
import onnxruntime
|
|
395
|
+
except Exception as exc:
|
|
396
|
+
note(f"DPR_ONNX_DEVICE={LAYOUT_DEVICE} but onnxruntime import failed ({exc!r}); staying on CPU")
|
|
397
|
+
return []
|
|
398
|
+
available = list(onnxruntime.get_available_providers())
|
|
399
|
+
if LAYOUT_DEVICE == "auto":
|
|
400
|
+
wanted = [p for p in ("CUDAExecutionProvider", "DmlExecutionProvider") if p in available]
|
|
401
|
+
else:
|
|
402
|
+
wanted = [p for p in (_GPU_PROVIDER_BY_DEVICE.get(LAYOUT_DEVICE, ""),) if p in available]
|
|
403
|
+
if not wanted:
|
|
404
|
+
note(f"DPR_ONNX_DEVICE={LAYOUT_DEVICE} requested but no GPU provider available ({available}); falling back to CPU")
|
|
405
|
+
return []
|
|
406
|
+
note(f"layout detection will use {wanted} (DPR_ONNX_DEVICE={LAYOUT_DEVICE})")
|
|
407
|
+
return wanted + ["CPUExecutionProvider"]
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def install_layout_device(providers: list) -> None:
|
|
411
|
+
if not providers:
|
|
412
|
+
return
|
|
413
|
+
import onnxruntime
|
|
414
|
+
|
|
415
|
+
real_session = onnxruntime.InferenceSession
|
|
416
|
+
|
|
417
|
+
def patched_session(*args, **kwargs):
|
|
418
|
+
# babeldoc 传进来的 providers 恒为 CPU-only;这里整体替换成 GPU 优先列表。
|
|
419
|
+
# session 创建失败(驱动/CUDA DLL 缺失等)→ 退回 CPU 原样重试,别把翻译拖死。
|
|
420
|
+
try:
|
|
421
|
+
return real_session(*args, **{**kwargs, "providers": providers})
|
|
422
|
+
except Exception as exc:
|
|
423
|
+
note(f"GPU InferenceSession failed ({exc!r}); falling back to CPU")
|
|
424
|
+
return real_session(*args, **{**kwargs, "providers": ["CPUExecutionProvider"]})
|
|
425
|
+
|
|
426
|
+
onnxruntime.InferenceSession = patched_session
|
|
427
|
+
if DEBUG:
|
|
428
|
+
note(f"layout device patch installed ({providers})")
|
|
429
|
+
|
|
430
|
+
|
|
366
431
|
def main() -> int:
|
|
367
432
|
_reconfigure_streams()
|
|
368
|
-
|
|
433
|
+
layout_providers = resolve_layout_providers()
|
|
434
|
+
emit({"kind": "driver", "version": 1, "maxOutputTokens": MAX_OUT, "splitTokens": SPLIT_TOKENS,
|
|
435
|
+
"layoutDevice": LAYOUT_DEVICE or "cpu", "layoutProviders": layout_providers})
|
|
369
436
|
import asyncio
|
|
370
437
|
|
|
371
438
|
try:
|
|
372
439
|
install_progress()
|
|
373
440
|
install_translation()
|
|
441
|
+
install_layout_device(layout_providers)
|
|
374
442
|
except Exception as exc: # 补丁失败也要能翻:退回原版 babeldoc
|
|
375
443
|
note(f"patch failed, falling back to plain babeldoc: {exc!r}")
|
|
376
444
|
|