@ggboy123/dsh-paper-reader 1.8.0 → 1.8.2
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 +10 -6
- package/dist/host.js +72 -10
- package/dist/translate-config.js +101 -23
- package/dist/translate.js +57 -11
- package/package.json +1 -1
- package/reader/index.html +900 -108
- package/runtime/babeldoc-driver.py +13 -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.8.
|
|
10
|
+
[DeepSeek Harness (dsh)](https://github.com/deepseek-ai/deepseek-harness) 插件:**论文伴读工作台** —— 文献库 + PDF 阅读器 + AI 伴读,回答自带页码、点页码跳回原文。当前版本 **v1.8.2**。
|
|
11
11
|
|
|
12
12
|
> 💬 **QQ 交流群:1127244508** —— 安装/使用问题、功能建议、bug 反馈都欢迎来聊。
|
|
13
13
|
|
|
@@ -21,15 +21,19 @@
|
|
|
21
21
|
|
|
22
22
|
- 📚 **三栏工作台**:专题文献库 + PDF 阅读器 + 右侧原生对话;安装后不改动官方界面,侧栏只多一行开关
|
|
23
23
|
- 💬 **带页码的伴读**:回答必带页码,点页码跳回原文并高亮;选中文字即问;支持历史对话
|
|
24
|
-
- 🌙 **PDF 深色模式**:dsh 切深色时 PDF 一起变深(默认跟随);设置面板与阅读器「A」按钮同源、四档强度可调。实现是整页反色 + 色相回正,**图片/照片会明显褪色偏色**(实测纯红 `[255,0,0]` → 浅粉 `[229,134,134]
|
|
24
|
+
- 🌙 **PDF 深色模式**:dsh 切深色时 PDF 一起变深(默认跟随);设置面板与阅读器「A」按钮同源、四档强度可调。实现是整页反色 + 色相回正,**图片/照片会明显褪色偏色**(实测纯红 `[255,0,0]` → 浅粉 `[229,134,134]`,不是真负片;已知代价,可一键关闭);下载/导出始终是原文
|
|
25
|
+
- 🗂️ **按论文分文件夹**:每篇论文的 PDF/译文/转录/学习档案收进 `<专题>/<论文>/`;旧库有一条**幂等、可中断、可回滚**的迁移(先复制后删,先出干跑报告再执行)
|
|
26
|
+
- 🌳 **嵌套子专题**:专题下可建子专题、任意层嵌套;可改名、可移动到另一父专题;删除非空专题仍走「清空计划 + 手输确认」
|
|
27
|
+
- 🎯 **按范围提问**:提问时可指定范围(本篇 / 所在专题含子专题),只把该范围的目录内容与检索命中交给模型;范围外内容不出现,截断会明确说明
|
|
25
28
|
- 🤖 **可选教练式带读**:专用 preset 制定分步计划;你读原文、作答,AI 点评追问,当前阶段答好才继续,学习进度跨会话累积
|
|
26
29
|
- 🀄 **一键中文版**:原文 ↔ 纯中文原地切换,译文 PDF 一键导出(纯中文 / 中英对照),翻译引擎零预装自动安装
|
|
27
30
|
- 📏 **长段落不截断 + 实时进度**:翻译由 `babeldoc-driver.py` 驱动 babeldoc —— 按输入估算输出预算(不再吃 babeldoc 写死的 2048),`finish_reason=length` 自动拆段重译;顶栏进度条实时显示「翻译段落 76%(521/798)」这样的阶段进度,端点拒绝关闭推理时自动降推理强度重试
|
|
28
|
-
- 🈯 **划词翻译(公式保留)**(v1.8.
|
|
29
|
-
- 🖥️ **中英对照 / 分屏**(v1.8.
|
|
30
|
-
- 📝 **笔记**(v1.8.
|
|
31
|
+
- 🈯 **划词翻译(公式保留)**(v1.8.2):选中点「译」出纯译文气泡;选区含公式时用 MinerU 识别的 LaTeX 替换文本层乱码、要求模型原样保留
|
|
32
|
+
- 🖥️ **中英对照 / 分屏**(v1.8.2):并排对照页或左右分屏同步滚动,随时切换、按文献记忆
|
|
33
|
+
- 📝 **笔记**(v1.8.2):划词仍直接弹回「选中即问」气泡(与旧版一致),气泡里新增「笔记」「全局搜索」小按钮;记过的文字下方画蓝色波浪线,鼠标停上去看笔记内容、点一下改或删;笔记窗口与查找窗同一套交互(可拖动、拖边框缩放、位置记忆),批量列表按页排序、点条目跳回原文。笔记存在 `<文献>.notes.json`(跟文献走,换浏览器不丢)
|
|
34
|
+
- ⚡ **长文档也流畅**:滚动模式只画视口附近的页、页离开视口即释放画布(其余保留等高占位,滚动条与页码始终准);原文 ↔ 中文切换只摘挂缓存好的页节点,不重新解析不重绘;切语言 / 重开论文不重传 PDF(ETag 304)。前提与已知边界见 [docs/features.md](docs/features.md)
|
|
31
35
|
- 🗂️ **文献管理**:专题/论文改名、删除进回收站可恢复
|
|
32
|
-
- 🛰️ **OpenCode Go 端点**(v1.8.
|
|
36
|
+
- 🛰️ **OpenCode Go 端点**(v1.8.2):翻译端点供应商预设新增「OpenCode Go」(订阅后复制 API Key 即用,模型名以控制台为准);对 opencode.ai 域的请求自动带稳定 `x-opencode-session` 会话头(同一篇论文的整篇与划词共用同一 ID、跨重启稳定,ID 由本机 0600 secret 派生不含论文名),其它端点不多发任何头
|
|
33
37
|
- ➕ **可选增强**(默认关):MinerU 解析——扫描件可读、公式可点引用可检索;嵌入端点——大白话命中术语段落
|
|
34
38
|
|
|
35
39
|
各功能的前提与配置细节见 [docs/features.md](docs/features.md)。
|
package/dist/host.js
CHANGED
|
@@ -11,8 +11,8 @@ import { buildScopeContext } from "./scope.js";
|
|
|
11
11
|
import { MAX_CHUNKS, MAX_LATEX_CHARS, MAX_TEXT_CHARS, MAX_TOTAL_CHARS, SelectionTranslateError, assembleSource, formulaStatusOf, translateSelection, } from "./translate-selection.js";
|
|
12
12
|
import { MineruError, sanitizeDetail } from "./mineru.js";
|
|
13
13
|
import { readTranscript, transcribePaper, ScannedPdfError, ShortTextError } from "./transcribe.js";
|
|
14
|
-
import { pdfVariantPath, restartTranslation, startTranslation, zhStatus } from "./translate.js";
|
|
15
|
-
import { clearTranslateConfig, maskApiKey, readTranslateConfig, resolveTranslateEndpoint,
|
|
14
|
+
import { cancelTranslation, pdfVariantPath, restartTranslation, startTranslation, zhStatus } from "./translate.js";
|
|
15
|
+
import { clearTranslateConfig, deleteTranslateEndpoint, maskApiKey, readTranslateConfig, readTranslateEndpointStore, resolveTranslateEndpoint, saveTranslateEndpoint, selectTranslateEndpoint, testTranslateEndpoint, } from "./translate-config.js";
|
|
16
16
|
import { clearTypesafeConfig, readTypesafeConfig, resolveTypesafeConfig, testTypesafeEndpoint, writeTypesafeConfig, } from "./typesafe-config.js";
|
|
17
17
|
import { clearEmbedConfig, maskApiKey as maskEmbedApiKey, readEmbedConfig, resolveEmbedConfig, testEmbedEndpoint, writeEmbedConfig, } from "./embed-config.js";
|
|
18
18
|
import { clearMineruConfig, mergeMineruBody, precheckMineruConfig, resolveMineruConfig, testMineruCloud, testMineruLocal, writeMineruConfig, } from "./mineru-config.js";
|
|
@@ -1264,11 +1264,24 @@ export function registerRoutes(ctx, config) {
|
|
|
1264
1264
|
const ref = locate(url);
|
|
1265
1265
|
const pdfPath = pdfVariantPath(ref, url.searchParams.get('variant'));
|
|
1266
1266
|
const st = await stat(pdfPath); // 变体不存在时 404/500 由外层兜底
|
|
1267
|
+
// ETag = 文件 mtime + size:重新翻译/替换 PDF 后自动变化;客户端带 If-None-Match 直接 304。
|
|
1268
|
+
// 之前是 cache-control: no-cache 且无校验器,切语言/缩放都会把整份 PDF 重传一遍。
|
|
1269
|
+
const etag = `"${Math.trunc(st.mtimeMs).toString(16)}-${st.size.toString(16)}"`;
|
|
1270
|
+
const cacheHeaders = {
|
|
1271
|
+
etag,
|
|
1272
|
+
'last-modified': st.mtime.toUTCString(),
|
|
1273
|
+
'cache-control': 'private, max-age=0, must-revalidate',
|
|
1274
|
+
};
|
|
1275
|
+
if (req.headers['if-none-match'] === etag) {
|
|
1276
|
+
res.writeHead(304, cacheHeaders);
|
|
1277
|
+
res.end();
|
|
1278
|
+
return;
|
|
1279
|
+
}
|
|
1267
1280
|
// download=1 → 附件下载(导出译文/原文);文件名即磁盘名 <名>.pdf / -zh.pdf / -dual.pdf
|
|
1268
1281
|
const headers = {
|
|
1269
1282
|
'content-type': 'application/pdf',
|
|
1270
1283
|
'content-length': st.size,
|
|
1271
|
-
|
|
1284
|
+
...cacheHeaders,
|
|
1272
1285
|
};
|
|
1273
1286
|
if (url.searchParams.get('download') === '1') {
|
|
1274
1287
|
const name = basename(pdfPath);
|
|
@@ -1304,23 +1317,64 @@ export function registerRoutes(ctx, config) {
|
|
|
1304
1317
|
return;
|
|
1305
1318
|
throw err;
|
|
1306
1319
|
}
|
|
1307
|
-
const { endpoint } = await resolveTranslateEndpoint(config.translate);
|
|
1320
|
+
const { endpoint, source } = await resolveTranslateEndpoint(config.translate, undefined, body.endpointId);
|
|
1321
|
+
if (body.endpointId && source === 'none') {
|
|
1322
|
+
json(res, 400, { error: '所选翻译端点不存在或配置不完整,请重新选择', code: 'endpoint-not-found' });
|
|
1323
|
+
return;
|
|
1324
|
+
}
|
|
1325
|
+
if (body.endpointId && source !== 'none')
|
|
1326
|
+
await selectTranslateEndpoint(body.endpointId);
|
|
1308
1327
|
const r = body.force
|
|
1309
1328
|
? await restartTranslation(ref, dataDir, endpoint)
|
|
1310
1329
|
: await startTranslation(ref, dataDir, endpoint);
|
|
1311
1330
|
json(res, r.started ? 200 : 409, r);
|
|
1312
1331
|
return;
|
|
1313
1332
|
}
|
|
1333
|
+
// 取消在途翻译:立即允许重新生成;旧进程回调由任务序号隔离,不得覆盖后续任务。
|
|
1334
|
+
if (sub === '/api/zh/cancel' && req.method === 'POST') {
|
|
1335
|
+
const body = (await readBody(req));
|
|
1336
|
+
let ref;
|
|
1337
|
+
try {
|
|
1338
|
+
ref = locateForWrite(body);
|
|
1339
|
+
}
|
|
1340
|
+
catch (err) {
|
|
1341
|
+
if (manageFail(res, err))
|
|
1342
|
+
return;
|
|
1343
|
+
throw err;
|
|
1344
|
+
}
|
|
1345
|
+
const cancelled = cancelTranslation(ref);
|
|
1346
|
+
json(res, cancelled ? 200 : 409, { cancelled, ...(cancelled ? {} : { error: '当前没有可取消的翻译任务' }) });
|
|
1347
|
+
return;
|
|
1348
|
+
}
|
|
1314
1349
|
// ── 翻译端点配置(阅读器浮层的读写口)─────────────────────────────
|
|
1315
1350
|
// GET 只回显掩码 key:明文永不离开服务端
|
|
1316
1351
|
if (sub === '/api/translate/config' && req.method === 'GET') {
|
|
1317
1352
|
const { endpoint, source } = await resolveTranslateEndpoint(config.translate);
|
|
1353
|
+
const store = await readTranslateEndpointStore();
|
|
1354
|
+
const endpoints = store.endpoints.map((e) => ({
|
|
1355
|
+
id: e.id,
|
|
1356
|
+
label: e.label ?? '',
|
|
1357
|
+
baseUrl: e.baseUrl ?? '',
|
|
1358
|
+
model: e.model ?? '',
|
|
1359
|
+
hasApiKey: Boolean(e.apiKey),
|
|
1360
|
+
apiKeyHint: e.apiKey ? maskApiKey(e.apiKey) : '',
|
|
1361
|
+
complete: Boolean(e.baseUrl && e.apiKey && e.model),
|
|
1362
|
+
source: 'file',
|
|
1363
|
+
}));
|
|
1364
|
+
if (config.translate?.baseUrl && config.translate.apiKey && config.translate.model) {
|
|
1365
|
+
endpoints.push({
|
|
1366
|
+
id: 'profile', label: 'profile 默认配置', baseUrl: config.translate.baseUrl, model: config.translate.model,
|
|
1367
|
+
hasApiKey: true, apiKeyHint: maskApiKey(config.translate.apiKey), complete: true, source: 'profile',
|
|
1368
|
+
});
|
|
1369
|
+
}
|
|
1318
1370
|
json(res, 200, {
|
|
1319
1371
|
baseUrl: endpoint.baseUrl ?? '',
|
|
1320
1372
|
model: endpoint.model ?? '',
|
|
1321
1373
|
hasApiKey: Boolean(endpoint.apiKey),
|
|
1322
1374
|
apiKeyHint: endpoint.apiKey ? maskApiKey(endpoint.apiKey) : '',
|
|
1323
1375
|
source,
|
|
1376
|
+
activeId: source === 'none' ? null : source === 'profile' ? 'profile' : store.activeId,
|
|
1377
|
+
endpoints,
|
|
1324
1378
|
});
|
|
1325
1379
|
return;
|
|
1326
1380
|
}
|
|
@@ -1330,9 +1384,13 @@ export function registerRoutes(ctx, config) {
|
|
|
1330
1384
|
const body = (await readBody(req));
|
|
1331
1385
|
const baseUrl = body.baseUrl?.trim() ?? '';
|
|
1332
1386
|
const model = body.model?.trim() ?? '';
|
|
1333
|
-
// key 留空 =
|
|
1387
|
+
// key 留空 = 沿用正在编辑的那个端点,而不是误用当前活跃端点的 key。
|
|
1388
|
+
const store = await readTranslateEndpointStore();
|
|
1389
|
+
const editing = body.id && body.id !== 'new'
|
|
1390
|
+
? store.endpoints.find((e) => e.id === body.id)
|
|
1391
|
+
: store.endpoints.find((e) => e.id === store.activeId);
|
|
1334
1392
|
const prev = await readTranslateConfig();
|
|
1335
|
-
const apiKey = body.apiKey?.trim() || prev?.apiKey || '';
|
|
1393
|
+
const apiKey = body.apiKey?.trim() || editing?.apiKey || (!body.id ? prev?.apiKey : '') || '';
|
|
1336
1394
|
if (!/^https?:\/\//i.test(baseUrl)) {
|
|
1337
1395
|
json(res, 400, { error: '端点 URL 需要以 http:// 或 https:// 开头' });
|
|
1338
1396
|
return;
|
|
@@ -1350,13 +1408,17 @@ export function registerRoutes(ctx, config) {
|
|
|
1350
1408
|
json(res, 400, { error: `连接测试失败:${test.detail ?? '未知原因'}` });
|
|
1351
1409
|
return;
|
|
1352
1410
|
}
|
|
1353
|
-
await
|
|
1354
|
-
json(res, 200, { ok: true });
|
|
1411
|
+
const saved = await saveTranslateEndpoint({ baseUrl, apiKey, model }, { ...(body.id ? { id: body.id } : {}), ...(body.label ? { label: body.label } : {}) });
|
|
1412
|
+
json(res, 200, { ok: true, id: saved.id });
|
|
1355
1413
|
return;
|
|
1356
1414
|
}
|
|
1357
|
-
// DELETE
|
|
1415
|
+
// DELETE:带 id 只删一个;不带 id 清空文件配置(旧客户端语义),回落到 profile。
|
|
1358
1416
|
if (sub === '/api/translate/config' && req.method === 'DELETE') {
|
|
1359
|
-
|
|
1417
|
+
const id = url.searchParams.get('id');
|
|
1418
|
+
if (id)
|
|
1419
|
+
await deleteTranslateEndpoint(id);
|
|
1420
|
+
else
|
|
1421
|
+
await clearTranslateConfig();
|
|
1360
1422
|
json(res, 200, { ok: true });
|
|
1361
1423
|
return;
|
|
1362
1424
|
}
|
package/dist/translate-config.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// dataDir 是文献库目录,可能被 git / 云盘同步出去,密钥不该跟着走。
|
|
5
5
|
// 优先级:文件 > profile 的 cordis.patch.yml config.translate(后者退为部署方默认值)。
|
|
6
6
|
// 密钥只落盘、只回显掩码:任何读接口都不返回明文(apiKeyHint 是掩码后的展示串)。
|
|
7
|
+
import { randomUUID } from 'node:crypto';
|
|
7
8
|
import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
8
9
|
import { dirname, join } from 'node:path';
|
|
9
10
|
import { dshHome } from "./library.js";
|
|
@@ -35,45 +36,122 @@ function pick(...sources) {
|
|
|
35
36
|
}
|
|
36
37
|
return out;
|
|
37
38
|
}
|
|
38
|
-
|
|
39
|
-
|
|
39
|
+
function endpointFields(rec) {
|
|
40
|
+
const raw = rec;
|
|
41
|
+
const out = {};
|
|
42
|
+
if (typeof raw['baseUrl'] === 'string')
|
|
43
|
+
out.baseUrl = raw['baseUrl'];
|
|
44
|
+
if (typeof raw['apiKey'] === 'string')
|
|
45
|
+
out.apiKey = raw['apiKey'];
|
|
46
|
+
if (typeof raw['model'] === 'string')
|
|
47
|
+
out.model = raw['model'];
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
/** 新格式是多端点;旧版单对象自动视为 id=legacy 的第一项,读取无需用户重配。 */
|
|
51
|
+
function parseStore(data) {
|
|
52
|
+
if (typeof data !== 'object' || data === null)
|
|
53
|
+
return { activeId: null, endpoints: [] };
|
|
54
|
+
const rec = data;
|
|
55
|
+
const endpoints = [];
|
|
56
|
+
if (Array.isArray(rec['endpoints'])) {
|
|
57
|
+
for (const item of rec['endpoints']) {
|
|
58
|
+
if (typeof item !== 'object' || item === null)
|
|
59
|
+
continue;
|
|
60
|
+
const e = item;
|
|
61
|
+
if (typeof e['id'] !== 'string' || !e['id'])
|
|
62
|
+
continue;
|
|
63
|
+
endpoints.push({
|
|
64
|
+
id: e['id'],
|
|
65
|
+
...(typeof e['label'] === 'string' && e['label'] ? { label: e['label'] } : {}),
|
|
66
|
+
...endpointFields(e),
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
const legacy = endpointFields(rec);
|
|
72
|
+
if (legacy.baseUrl || legacy.apiKey || legacy.model)
|
|
73
|
+
endpoints.push({ id: 'legacy', ...legacy });
|
|
74
|
+
}
|
|
75
|
+
const requested = typeof rec['activeId'] === 'string' ? rec['activeId'] : null;
|
|
76
|
+
const activeId = requested === 'profile' || endpoints.some((e) => e.id === requested) ? requested : (endpoints[0]?.id ?? null);
|
|
77
|
+
return { activeId, endpoints };
|
|
78
|
+
}
|
|
79
|
+
export async function readTranslateEndpointStore(home = dshHome()) {
|
|
40
80
|
try {
|
|
41
|
-
|
|
42
|
-
if (typeof data !== 'object' || data === null)
|
|
43
|
-
return null;
|
|
44
|
-
const rec = data;
|
|
45
|
-
const out = {};
|
|
46
|
-
if (typeof rec['baseUrl'] === 'string')
|
|
47
|
-
out.baseUrl = rec['baseUrl'];
|
|
48
|
-
if (typeof rec['apiKey'] === 'string')
|
|
49
|
-
out.apiKey = rec['apiKey'];
|
|
50
|
-
if (typeof rec['model'] === 'string')
|
|
51
|
-
out.model = rec['model'];
|
|
52
|
-
return out;
|
|
81
|
+
return parseStore(JSON.parse(await readFile(translateConfigPath(home), 'utf8')));
|
|
53
82
|
}
|
|
54
83
|
catch {
|
|
55
|
-
return null;
|
|
84
|
+
return { activeId: null, endpoints: [] };
|
|
56
85
|
}
|
|
57
86
|
}
|
|
58
|
-
|
|
59
|
-
export async function writeTranslateConfig(cfg, home = dshHome()) {
|
|
87
|
+
async function writeStore(store, home) {
|
|
60
88
|
const file = translateConfigPath(home);
|
|
61
89
|
await mkdir(dirname(file), { recursive: true });
|
|
62
|
-
await writeFile(file, JSON.stringify(
|
|
63
|
-
await chmod(file, 0o600);
|
|
90
|
+
await writeFile(file, JSON.stringify(store, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 });
|
|
91
|
+
await chmod(file, 0o600);
|
|
92
|
+
}
|
|
93
|
+
/** 兼容旧调用方:读出当前选中端点。 */
|
|
94
|
+
export async function readTranslateConfig(home = dshHome()) {
|
|
95
|
+
const store = await readTranslateEndpointStore(home);
|
|
96
|
+
const active = store.activeId === 'profile' ? null : store.endpoints.find((e) => e.id === store.activeId) ?? store.endpoints[0];
|
|
97
|
+
return active ? endpointFields(active) : null;
|
|
98
|
+
}
|
|
99
|
+
/** 兼容旧调用方:单端点写入会替换整个文件;UI 多端点保存走 saveTranslateEndpoint。 */
|
|
100
|
+
export async function writeTranslateConfig(cfg, home = dshHome()) {
|
|
101
|
+
await writeStore({ activeId: 'legacy', endpoints: [{ id: 'legacy', ...cfg }] }, home);
|
|
102
|
+
}
|
|
103
|
+
/** 新建/更新并选中一个端点;id='new' 强制新增,缺省 id 更新当前项(旧 UI 语义)。 */
|
|
104
|
+
export async function saveTranslateEndpoint(cfg, options = {}) {
|
|
105
|
+
const home = options.home ?? dshHome();
|
|
106
|
+
const store = await readTranslateEndpointStore(home);
|
|
107
|
+
const existing = options.id === 'new'
|
|
108
|
+
? undefined
|
|
109
|
+
: store.endpoints.find((e) => e.id === (options.id ?? store.activeId));
|
|
110
|
+
const label = options.label?.trim() || existing?.label;
|
|
111
|
+
const entry = {
|
|
112
|
+
id: existing?.id ?? randomUUID(),
|
|
113
|
+
...(label ? { label } : {}),
|
|
114
|
+
...cfg,
|
|
115
|
+
};
|
|
116
|
+
const endpoints = existing
|
|
117
|
+
? store.endpoints.map((e) => e.id === existing.id ? entry : e)
|
|
118
|
+
: [...store.endpoints, entry];
|
|
119
|
+
await writeStore({ activeId: entry.id, endpoints }, home);
|
|
120
|
+
return entry;
|
|
121
|
+
}
|
|
122
|
+
/** 记住生成时选择的端点,划词翻译与下次打开选择器也沿用同一项。 */
|
|
123
|
+
export async function selectTranslateEndpoint(id, home = dshHome()) {
|
|
124
|
+
const store = await readTranslateEndpointStore(home);
|
|
125
|
+
if (id !== 'profile' && !store.endpoints.some((e) => e.id === id))
|
|
126
|
+
throw new Error('翻译端点不存在');
|
|
127
|
+
await writeStore({ ...store, activeId: id }, home);
|
|
128
|
+
}
|
|
129
|
+
/** 删除单个端点;删当前项后选中下一项。无剩余文件端点时 resolve 会回落 profile。 */
|
|
130
|
+
export async function deleteTranslateEndpoint(id, home = dshHome()) {
|
|
131
|
+
const store = await readTranslateEndpointStore(home);
|
|
132
|
+
const endpoints = store.endpoints.filter((e) => e.id !== id);
|
|
133
|
+
await writeStore({ activeId: store.activeId === id ? (endpoints[0]?.id ?? null) : store.activeId, endpoints }, home);
|
|
64
134
|
}
|
|
65
135
|
/** 删除配置(回落到 profile 的 translate)。文件不存在也算成功。 */
|
|
66
136
|
export async function clearTranslateConfig(home = dshHome()) {
|
|
67
137
|
await rm(translateConfigPath(home), { force: true });
|
|
68
138
|
}
|
|
69
139
|
/** 解析生效端点:文件配全则用文件,否则用 profile,都配不全则返回能凑到的部分供报错。 */
|
|
70
|
-
export async function resolveTranslateEndpoint(profile, home = dshHome()) {
|
|
71
|
-
const
|
|
140
|
+
export async function resolveTranslateEndpoint(profile, home = dshHome(), endpointId) {
|
|
141
|
+
const store = await readTranslateEndpointStore(home);
|
|
142
|
+
if (endpointId === 'profile' || (!endpointId && store.activeId === 'profile'))
|
|
143
|
+
return isComplete(profile)
|
|
144
|
+
? { endpoint: profile, source: 'profile' }
|
|
145
|
+
: { endpoint: {}, source: 'none' };
|
|
146
|
+
const selected = endpointId
|
|
147
|
+
? store.endpoints.find((e) => e.id === endpointId)
|
|
148
|
+
: store.endpoints.find((e) => e.id === store.activeId) ?? store.endpoints[0];
|
|
149
|
+
const file = selected ? endpointFields(selected) : null;
|
|
72
150
|
if (isComplete(file))
|
|
73
151
|
return { endpoint: file, source: 'file' };
|
|
74
|
-
if (isComplete(profile))
|
|
152
|
+
if (!endpointId && isComplete(profile))
|
|
75
153
|
return { endpoint: profile, source: 'profile' };
|
|
76
|
-
return { endpoint: pick(profile, file), source: 'none' };
|
|
154
|
+
return { endpoint: endpointId ? (file ?? {}) : pick(profile, file), source: 'none' };
|
|
77
155
|
}
|
|
78
156
|
/** 掩码展示:只露头 3 尾 4,够用户认出是哪把 key,又不足以还原。 */
|
|
79
157
|
export function maskApiKey(key) {
|
package/dist/translate.js
CHANGED
|
@@ -24,6 +24,25 @@ export function dualPdfPath(ref) {
|
|
|
24
24
|
/** 进程内每篇文献一个翻译任务(幂等:进行中/已生成直接返回)。 */
|
|
25
25
|
// key=pdfPath;null=进行中(无阶段说明);{phase,progress}=进行中;{error}=已失败
|
|
26
26
|
const busy = new Map();
|
|
27
|
+
/** 每篇文献的当前任务句柄;换任务后旧回调凭对象同一性失效。 */
|
|
28
|
+
const tasks = new Map();
|
|
29
|
+
function setTaskBusy(ref, task, state) {
|
|
30
|
+
if (tasks.get(ref.pdfPath) === task)
|
|
31
|
+
busy.set(ref.pdfPath, state);
|
|
32
|
+
}
|
|
33
|
+
/** 用户主动取消:立即放开重试入口,子进程退出后的旧回调不得再改状态或搬产物。 */
|
|
34
|
+
export function cancelTranslation(ref) {
|
|
35
|
+
const task = tasks.get(ref.pdfPath);
|
|
36
|
+
if (!task || task.cancelled || !zhStatus(ref).busy)
|
|
37
|
+
return false;
|
|
38
|
+
task.cancelled = true;
|
|
39
|
+
try {
|
|
40
|
+
task.kill?.();
|
|
41
|
+
}
|
|
42
|
+
catch { /* 进程已退出 */ }
|
|
43
|
+
setTaskBusy(ref, task, { error: '已取消翻译' });
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
27
46
|
/** 整篇翻译的硬超时(babeldoc 自己不死,靠这里收尸)。 */
|
|
28
47
|
const TRANSLATE_TIMEOUT_MS = 45 * 60 * 1000;
|
|
29
48
|
/** 失败时保留的日志尾巴长度。 */
|
|
@@ -132,7 +151,9 @@ function precheck(endpoint) {
|
|
|
132
151
|
}
|
|
133
152
|
/** 后台流水线:确保 babeldoc 可用(缺失则自动安装)→ 拉起翻译。 */
|
|
134
153
|
async function runPipeline(ref, dataDir, endpoint) {
|
|
135
|
-
const
|
|
154
|
+
const task = { cancelled: false, kill: null };
|
|
155
|
+
tasks.set(ref.pdfPath, task);
|
|
156
|
+
const setPhase = (phase) => setTaskBusy(ref, task, { phase });
|
|
136
157
|
try {
|
|
137
158
|
setPhase('正在检查翻译引擎…');
|
|
138
159
|
// DPR_SKIP_ENGINE_ENSURE=1:跳过「自检 + 缺失则自动安装」,只用现成的 babeldoc
|
|
@@ -140,14 +161,21 @@ async function runPipeline(ref, dataDir, endpoint) {
|
|
|
140
161
|
const bin = process.env.DPR_SKIP_ENGINE_ENSURE === '1'
|
|
141
162
|
? await findBabeldoc(dataDir)
|
|
142
163
|
: await ensureBabeldoc(dataDir, dshHome(), () => findBabeldoc(dataDir), setPhase);
|
|
164
|
+
if (task.cancelled || tasks.get(ref.pdfPath) !== task)
|
|
165
|
+
return;
|
|
143
166
|
if (!bin)
|
|
144
167
|
throw new Error('找不到 babeldoc 可执行文件');
|
|
145
|
-
await launch(ref, dataDir, endpoint, bin);
|
|
168
|
+
await launch(ref, dataDir, endpoint, bin, task);
|
|
146
169
|
}
|
|
147
170
|
catch (e) {
|
|
148
171
|
const msg = e instanceof Error ? e.message : String(e);
|
|
149
|
-
|
|
150
|
-
|
|
172
|
+
if (!task.cancelled)
|
|
173
|
+
console.error('[dsh-paper-reader] babeldoc 自动安装失败:', msg);
|
|
174
|
+
setTaskBusy(ref, task, { error: task.cancelled ? '已取消翻译' : `翻译引擎安装失败:${msg}` });
|
|
175
|
+
}
|
|
176
|
+
finally {
|
|
177
|
+
if (tasks.get(ref.pdfPath) === task)
|
|
178
|
+
tasks.delete(ref.pdfPath);
|
|
151
179
|
}
|
|
152
180
|
}
|
|
153
181
|
/**
|
|
@@ -242,12 +270,12 @@ function resolveDriverPython(bin) {
|
|
|
242
270
|
return candidates.find((c) => existsSync(c)) ?? null;
|
|
243
271
|
}
|
|
244
272
|
/** 真正拉起 babeldoc 子进程(bin 已就绪、产物不存在/已删)。 */
|
|
245
|
-
async function launch(ref, dataDir, endpoint, bin) {
|
|
273
|
+
async function launch(ref, dataDir, endpoint, bin, task) {
|
|
246
274
|
// 走到这里之前 precheck 已保证三项齐全;收窄一次,后续按 string 用
|
|
247
275
|
const ep = endpoint;
|
|
248
276
|
const tmpDir = join(dataDir, '.pdf2zh-tmp');
|
|
249
277
|
await mkdir(tmpDir, { recursive: true });
|
|
250
|
-
|
|
278
|
+
setTaskBusy(ref, task, null); // 清掉安装阶段说明,回到「翻译进行中」
|
|
251
279
|
const stem = basename(ref.pdfPath, extname(ref.pdfPath));
|
|
252
280
|
const dstStem = ref.pdfPath.slice(0, -extname(ref.pdfPath).length);
|
|
253
281
|
// OpenCode Go:整篇翻译是一个「会话」,同一篇论文(含之后的划词翻译)共用一个稳定 ID,
|
|
@@ -293,6 +321,10 @@ async function launch(ref, dataDir, endpoint, bin) {
|
|
|
293
321
|
const cmd = useDriver && python ? python : bin;
|
|
294
322
|
const args = useDriver ? [DRIVER_PATH, ...babelArgs] : babelArgs;
|
|
295
323
|
await new Promise((resolveDone) => {
|
|
324
|
+
if (task.cancelled || tasks.get(ref.pdfPath) !== task) {
|
|
325
|
+
resolveDone();
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
296
328
|
const stages = [];
|
|
297
329
|
let tail = '';
|
|
298
330
|
let settled = false;
|
|
@@ -314,6 +346,12 @@ async function launch(ref, dataDir, endpoint, bin) {
|
|
|
314
346
|
windowsHide: true,
|
|
315
347
|
stdio: ['ignore', logFd, logFd],
|
|
316
348
|
});
|
|
349
|
+
task.kill = () => {
|
|
350
|
+
try {
|
|
351
|
+
child?.kill();
|
|
352
|
+
}
|
|
353
|
+
catch { /* 已退出 */ }
|
|
354
|
+
};
|
|
317
355
|
if (logFd >= 0)
|
|
318
356
|
try {
|
|
319
357
|
closeSync(logFd);
|
|
@@ -324,6 +362,8 @@ async function launch(ref, dataDir, endpoint, bin) {
|
|
|
324
362
|
child?.kill();
|
|
325
363
|
}, TRANSLATE_TIMEOUT_MS);
|
|
326
364
|
const handleLine = (line) => {
|
|
365
|
+
if (task.cancelled || tasks.get(ref.pdfPath) !== task)
|
|
366
|
+
return;
|
|
327
367
|
const raw = line.trim();
|
|
328
368
|
if (!raw)
|
|
329
369
|
return;
|
|
@@ -356,7 +396,7 @@ async function launch(ref, dataDir, endpoint, bin) {
|
|
|
356
396
|
if (event.type === 'finish' || event.type === 'progress_end')
|
|
357
397
|
return;
|
|
358
398
|
const progress = buildProgress(event, stages);
|
|
359
|
-
|
|
399
|
+
setTaskBusy(ref, task, { phase: `${progress.text}…`, progress });
|
|
360
400
|
};
|
|
361
401
|
// 增量 tail 日志文件(按字节偏移读,用 StringDecoder 防多字节字符被切断)
|
|
362
402
|
const decoder = new StringDecoder('utf8');
|
|
@@ -417,10 +457,15 @@ async function launch(ref, dataDir, endpoint, bin) {
|
|
|
417
457
|
}
|
|
418
458
|
catch { /* 无所谓 */ }
|
|
419
459
|
void (async () => {
|
|
460
|
+
if (task.cancelled || tasks.get(ref.pdfPath) !== task) {
|
|
461
|
+
setTaskBusy(ref, task, { error: '已取消翻译' });
|
|
462
|
+
resolveDone();
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
420
465
|
if (error || code !== 0) {
|
|
421
466
|
const detail = (tail.trim() || error?.message || '').slice(-MAX_TAIL_CHARS);
|
|
422
467
|
console.error('[dsh-paper-reader] babeldoc failed:', detail);
|
|
423
|
-
|
|
468
|
+
setTaskBusy(ref, task, { error: `babeldoc 执行失败: ${detail || `退出码 ${code}`}` });
|
|
424
469
|
resolveDone();
|
|
425
470
|
return;
|
|
426
471
|
}
|
|
@@ -436,15 +481,16 @@ async function launch(ref, dataDir, endpoint, bin) {
|
|
|
436
481
|
}
|
|
437
482
|
if (!existsSync(zhPdfPath(ref)) && !existsSync(dualPdfPath(ref))) {
|
|
438
483
|
const why = tail.trim().split('\n').pop() ?? '';
|
|
439
|
-
|
|
484
|
+
setTaskBusy(ref, task, { error: `babeldoc 未产出译文 PDF${why ? `:${why}` : ''}` });
|
|
440
485
|
resolveDone();
|
|
441
486
|
return;
|
|
442
487
|
}
|
|
443
|
-
|
|
488
|
+
if (tasks.get(ref.pdfPath) === task)
|
|
489
|
+
busy.delete(ref.pdfPath);
|
|
444
490
|
console.log(`[dsh-paper-reader] babeldoc done: ${ref.name}`);
|
|
445
491
|
}
|
|
446
492
|
catch (e) {
|
|
447
|
-
|
|
493
|
+
setTaskBusy(ref, task, { error: `移动译文产物失败: ${e instanceof Error ? e.message : String(e)}` });
|
|
448
494
|
}
|
|
449
495
|
resolveDone();
|
|
450
496
|
})();
|