@ggboy123/dsh-paper-reader 1.8.1 → 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 +5 -5
- package/dist/host.js +58 -9
- package/dist/translate-config.js +101 -23
- package/dist/translate.js +57 -11
- package/package.json +1 -1
- package/reader/index.html +185 -34
- 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
|
|
|
@@ -28,12 +28,12 @@
|
|
|
28
28
|
- 🤖 **可选教练式带读**:专用 preset 制定分步计划;你读原文、作答,AI 点评追问,当前阶段答好才继续,学习进度跨会话累积
|
|
29
29
|
- 🀄 **一键中文版**:原文 ↔ 纯中文原地切换,译文 PDF 一键导出(纯中文 / 中英对照),翻译引擎零预装自动安装
|
|
30
30
|
- 📏 **长段落不截断 + 实时进度**:翻译由 `babeldoc-driver.py` 驱动 babeldoc —— 按输入估算输出预算(不再吃 babeldoc 写死的 2048),`finish_reason=length` 自动拆段重译;顶栏进度条实时显示「翻译段落 76%(521/798)」这样的阶段进度,端点拒绝关闭推理时自动降推理强度重试
|
|
31
|
-
- 🈯 **划词翻译(公式保留)**(v1.8.
|
|
32
|
-
- 🖥️ **中英对照 / 分屏**(v1.8.
|
|
33
|
-
- 📝 **笔记**(v1.8.
|
|
31
|
+
- 🈯 **划词翻译(公式保留)**(v1.8.2):选中点「译」出纯译文气泡;选区含公式时用 MinerU 识别的 LaTeX 替换文本层乱码、要求模型原样保留
|
|
32
|
+
- 🖥️ **中英对照 / 分屏**(v1.8.2):并排对照页或左右分屏同步滚动,随时切换、按文献记忆
|
|
33
|
+
- 📝 **笔记**(v1.8.2):划词仍直接弹回「选中即问」气泡(与旧版一致),气泡里新增「笔记」「全局搜索」小按钮;记过的文字下方画蓝色波浪线,鼠标停上去看笔记内容、点一下改或删;笔记窗口与查找窗同一套交互(可拖动、拖边框缩放、位置记忆),批量列表按页排序、点条目跳回原文。笔记存在 `<文献>.notes.json`(跟文献走,换浏览器不丢)
|
|
34
34
|
- ⚡ **长文档也流畅**:滚动模式只画视口附近的页、页离开视口即释放画布(其余保留等高占位,滚动条与页码始终准);原文 ↔ 中文切换只摘挂缓存好的页节点,不重新解析不重绘;切语言 / 重开论文不重传 PDF(ETag 304)。前提与已知边界见 [docs/features.md](docs/features.md)
|
|
35
35
|
- 🗂️ **文献管理**:专题/论文改名、删除进回收站可恢复
|
|
36
|
-
- 🛰️ **OpenCode Go 端点**(v1.8.
|
|
36
|
+
- 🛰️ **OpenCode Go 端点**(v1.8.2):翻译端点供应商预设新增「OpenCode Go」(订阅后复制 API Key 即用,模型名以控制台为准);对 opencode.ai 域的请求自动带稳定 `x-opencode-session` 会话头(同一篇论文的整篇与划词共用同一 ID、跨重启稳定,ID 由本机 0600 secret 派生不含论文名),其它端点不多发任何头
|
|
37
37
|
- ➕ **可选增强**(默认关):MinerU 解析——扫描件可读、公式可点引用可检索;嵌入端点——大白话命中术语段落
|
|
38
38
|
|
|
39
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";
|
|
@@ -1317,23 +1317,64 @@ export function registerRoutes(ctx, config) {
|
|
|
1317
1317
|
return;
|
|
1318
1318
|
throw err;
|
|
1319
1319
|
}
|
|
1320
|
-
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);
|
|
1321
1327
|
const r = body.force
|
|
1322
1328
|
? await restartTranslation(ref, dataDir, endpoint)
|
|
1323
1329
|
: await startTranslation(ref, dataDir, endpoint);
|
|
1324
1330
|
json(res, r.started ? 200 : 409, r);
|
|
1325
1331
|
return;
|
|
1326
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
|
+
}
|
|
1327
1349
|
// ── 翻译端点配置(阅读器浮层的读写口)─────────────────────────────
|
|
1328
1350
|
// GET 只回显掩码 key:明文永不离开服务端
|
|
1329
1351
|
if (sub === '/api/translate/config' && req.method === 'GET') {
|
|
1330
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
|
+
}
|
|
1331
1370
|
json(res, 200, {
|
|
1332
1371
|
baseUrl: endpoint.baseUrl ?? '',
|
|
1333
1372
|
model: endpoint.model ?? '',
|
|
1334
1373
|
hasApiKey: Boolean(endpoint.apiKey),
|
|
1335
1374
|
apiKeyHint: endpoint.apiKey ? maskApiKey(endpoint.apiKey) : '',
|
|
1336
1375
|
source,
|
|
1376
|
+
activeId: source === 'none' ? null : source === 'profile' ? 'profile' : store.activeId,
|
|
1377
|
+
endpoints,
|
|
1337
1378
|
});
|
|
1338
1379
|
return;
|
|
1339
1380
|
}
|
|
@@ -1343,9 +1384,13 @@ export function registerRoutes(ctx, config) {
|
|
|
1343
1384
|
const body = (await readBody(req));
|
|
1344
1385
|
const baseUrl = body.baseUrl?.trim() ?? '';
|
|
1345
1386
|
const model = body.model?.trim() ?? '';
|
|
1346
|
-
// 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);
|
|
1347
1392
|
const prev = await readTranslateConfig();
|
|
1348
|
-
const apiKey = body.apiKey?.trim() || prev?.apiKey || '';
|
|
1393
|
+
const apiKey = body.apiKey?.trim() || editing?.apiKey || (!body.id ? prev?.apiKey : '') || '';
|
|
1349
1394
|
if (!/^https?:\/\//i.test(baseUrl)) {
|
|
1350
1395
|
json(res, 400, { error: '端点 URL 需要以 http:// 或 https:// 开头' });
|
|
1351
1396
|
return;
|
|
@@ -1363,13 +1408,17 @@ export function registerRoutes(ctx, config) {
|
|
|
1363
1408
|
json(res, 400, { error: `连接测试失败:${test.detail ?? '未知原因'}` });
|
|
1364
1409
|
return;
|
|
1365
1410
|
}
|
|
1366
|
-
await
|
|
1367
|
-
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 });
|
|
1368
1413
|
return;
|
|
1369
1414
|
}
|
|
1370
|
-
// DELETE
|
|
1415
|
+
// DELETE:带 id 只删一个;不带 id 清空文件配置(旧客户端语义),回落到 profile。
|
|
1371
1416
|
if (sub === '/api/translate/config' && req.method === 'DELETE') {
|
|
1372
|
-
|
|
1417
|
+
const id = url.searchParams.get('id');
|
|
1418
|
+
if (id)
|
|
1419
|
+
await deleteTranslateEndpoint(id);
|
|
1420
|
+
else
|
|
1421
|
+
await clearTranslateConfig();
|
|
1373
1422
|
json(res, 200, { ok: true });
|
|
1374
1423
|
return;
|
|
1375
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
|
})();
|
package/package.json
CHANGED
package/reader/index.html
CHANGED
|
@@ -310,7 +310,7 @@
|
|
|
310
310
|
|
|
311
311
|
/* ---------- 翻译端点设置浮层 ---------- */
|
|
312
312
|
/* 阅读器在窄 iframe 里,宽度要能收缩 */
|
|
313
|
-
#cfg-pop, #theme-pop { position: fixed; z-index: 60; display: none; background: var(--panel); border: 1px solid var(--border); border-radius: 10px; box-shadow: 0 6px 24px rgba(0,0,0,.16); padding: 10px; width: min(320px, calc(100vw - 32px)); }
|
|
313
|
+
#cfg-pop, #theme-pop, #generate-pop { position: fixed; z-index: 60; display: none; background: var(--panel); border: 1px solid var(--border); border-radius: 10px; box-shadow: 0 6px 24px rgba(0,0,0,.16); padding: 10px; width: min(320px, calc(100vw - 32px)); }
|
|
314
314
|
#cfg-pop h3, #theme-pop h3 { margin: 0; font-size: 13px; }
|
|
315
315
|
#cfg-hint { font-size: 12px; color: var(--text-2); margin: 4px 0 2px; }
|
|
316
316
|
#cfg-pop label, #theme-pop label { display: block; font-size: 12px; color: var(--text-2); margin: 8px 0 2px; }
|
|
@@ -322,9 +322,10 @@
|
|
|
322
322
|
#cfg-pop input, #cfg-pop select, #theme-pop input, #theme-pop select { width: 100%; border: 1px solid var(--border); border-radius: 6px; padding: 6px 8px; font: inherit; background: var(--panel); color: var(--text); }
|
|
323
323
|
#cfg-model-hint, #cfg-source { font-size: 11.5px; color: var(--text-2); margin-top: 4px; line-height: 1.5; }
|
|
324
324
|
#cfg-source:empty { display: none; }
|
|
325
|
-
#cfg-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 10px; }
|
|
326
|
-
#cfg-
|
|
327
|
-
#cfg-save
|
|
325
|
+
#cfg-actions, #generate-actions, #cfg-list-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 10px; }
|
|
326
|
+
#cfg-list-actions { justify-content: flex-start; margin-top: 4px; }
|
|
327
|
+
#cfg-save, #generate-start { background: var(--accent); color: #fff; border: none; border-radius: 6px; padding: 5px 14px; cursor: pointer; }
|
|
328
|
+
#cfg-save:disabled, #generate-start:disabled { opacity: .5; cursor: default; }
|
|
328
329
|
#cfg-cancel { background: none; border: none; color: var(--text-2); cursor: pointer; }
|
|
329
330
|
|
|
330
331
|
#toast { position: fixed; left: 50%; bottom: 28px; transform: translateX(-50%); background: rgba(30,30,30,.92); color: #fff; padding: 8px 16px; border-radius: 8px; font-size: 13px; display: none; z-index: 99; max-width: 70%; }
|
|
@@ -357,6 +358,7 @@
|
|
|
357
358
|
<!-- 翻译进度条:只在 babeldoc 跑着时出现(宽度=overall,文字=阶段+百分比),
|
|
358
359
|
窄列下先让位给按钮(flex:0 1 auto + min-width:0),别把控件挤出去 -->
|
|
359
360
|
<span id="zh-prog" hidden><span class="track"><span class="fill"></span></span><span class="txt"></span></span>
|
|
361
|
+
<button id="zh-cancel" class="tbtn" style="display:none" title="取消当前翻译,之后可换端点重试">取消</button>
|
|
360
362
|
<!-- 路径不再占顶栏:藏于此(tucked),悬停状态文字可见完整路径、点击状态文字复制(见下方绑定) -->
|
|
361
363
|
<button id="pdf-path" class="tucked" style="display:none" title="点击复制文件路径"></button>
|
|
362
364
|
<span class="bar-sep"></span>
|
|
@@ -507,6 +509,12 @@
|
|
|
507
509
|
<h3>翻译端点</h3>
|
|
508
510
|
<div id="cfg-hint">选预设供应商,或选「自定义」填任意 OpenAI 兼容端点(通义 / 本地 vLLM 等)。OpenCode Go 需先在 OpenCode Console 订阅并复制 API Key。保存前会先测试连接。</div>
|
|
509
511
|
<div id="cfg-source"></div>
|
|
512
|
+
<label for="cfg-saved">已保存端点</label>
|
|
513
|
+
<select id="cfg-saved"></select>
|
|
514
|
+
<div id="cfg-list-actions">
|
|
515
|
+
<button id="cfg-new" class="tbtn">新增端点</button>
|
|
516
|
+
<button id="cfg-delete" class="tbtn">删除当前</button>
|
|
517
|
+
</div>
|
|
510
518
|
<label for="cfg-provider">供应商</label>
|
|
511
519
|
<select id="cfg-provider"></select>
|
|
512
520
|
<label for="cfg-url">端点 URL</label>
|
|
@@ -519,10 +527,23 @@
|
|
|
519
527
|
<div id="cfg-model-hint">glm-5.x / k3 / deepseek-flash 是推理型模型,服务端已自动关闭思考;选自定义端点时建议用非推理模型,否则会慢好几倍。</div>
|
|
520
528
|
<div id="cfg-actions">
|
|
521
529
|
<button id="cfg-cancel">取消</button>
|
|
530
|
+
<button id="cfg-save-new">另存为新端点</button>
|
|
522
531
|
<button id="cfg-save">保存</button>
|
|
523
532
|
</div>
|
|
524
533
|
</div>
|
|
525
534
|
|
|
535
|
+
<div id="generate-pop">
|
|
536
|
+
<h3>选择翻译模型</h3>
|
|
537
|
+
<div id="generate-hint">本次整篇翻译使用哪个已保存端点?Key 只会显示掩码。</div>
|
|
538
|
+
<label for="generate-endpoint">模型 / API Key</label>
|
|
539
|
+
<select id="generate-endpoint"></select>
|
|
540
|
+
<div id="generate-actions">
|
|
541
|
+
<button id="generate-manage" class="tbtn">管理端点</button>
|
|
542
|
+
<button id="generate-cancel" class="tbtn">取消</button>
|
|
543
|
+
<button id="generate-start">开始翻译</button>
|
|
544
|
+
</div>
|
|
545
|
+
</div>
|
|
546
|
+
|
|
526
547
|
<!-- PDF 深色模式(方案 §A2.3 入口 2):与 dsh 设置面板**共用同一个后端配置**(/api/theme/config),
|
|
527
548
|
两处不各存一份;改动即时生效,无需点保存。独立于设置面板——「A」按钮专属配置。 -->
|
|
528
549
|
<div id="theme-pop">
|
|
@@ -2106,7 +2127,10 @@ window.dprNotesDebug = () => ({
|
|
|
2106
2127
|
/* ================= 中英切换 ================= */
|
|
2107
2128
|
/** 翻译进度条(只在 busy 时出现):宽度跟着后端 progress.overall,文字给阶段+百分比。 */
|
|
2108
2129
|
function updateZhProgress() { const box = $('zh-prog');
|
|
2109
|
-
const
|
|
2130
|
+
const busy = Boolean(zhState && zhState.busy);
|
|
2131
|
+
const p = busy ? zhState.progress : null;
|
|
2132
|
+
$('zh-cancel').style.display = busy ? '' : 'none';
|
|
2133
|
+
if (!busy) { zhCancelArmed = false; $('zh-cancel').textContent = '取消'; }
|
|
2110
2134
|
if (!p) { box.hidden = true; return; }
|
|
2111
2135
|
const pct = typeof p.overall === 'number' ? Math.max(0, Math.min(100, p.overall)) : null;
|
|
2112
2136
|
box.hidden = false;
|
|
@@ -2116,6 +2140,29 @@ function updateZhProgress() { const box = $('zh-prog');
|
|
|
2116
2140
|
: `${p.label || '翻译'} ${Math.round(pct)}%`;
|
|
2117
2141
|
box.title = p.text || '';
|
|
2118
2142
|
}
|
|
2143
|
+
let zhCancelArmed = false;
|
|
2144
|
+
$('zh-cancel').onclick = async () => {
|
|
2145
|
+
if (!zhState.busy) return;
|
|
2146
|
+
if (!zhCancelArmed) {
|
|
2147
|
+
zhCancelArmed = true;
|
|
2148
|
+
$('zh-cancel').textContent = '确认取消?';
|
|
2149
|
+
setTimeout(() => { if (zhCancelArmed) { zhCancelArmed = false; $('zh-cancel').textContent = '取消'; } }, 3000);
|
|
2150
|
+
return;
|
|
2151
|
+
}
|
|
2152
|
+
zhCancelArmed = false;
|
|
2153
|
+
$('zh-cancel').disabled = true;
|
|
2154
|
+
try {
|
|
2155
|
+
await api('/zh/cancel', {
|
|
2156
|
+
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(current),
|
|
2157
|
+
});
|
|
2158
|
+
toast('已取消翻译,可以换端点重试');
|
|
2159
|
+
} catch (e) { toast('取消失败:' + e.message, 8000); }
|
|
2160
|
+
finally {
|
|
2161
|
+
$('zh-cancel').disabled = false;
|
|
2162
|
+
$('zh-cancel').textContent = '取消';
|
|
2163
|
+
await refreshZhState();
|
|
2164
|
+
}
|
|
2165
|
+
};
|
|
2119
2166
|
// 别人启动的翻译(另开会话/刷新页面后进来)也要能看到进度:busy 就自动挂一个低成本轮询
|
|
2120
2167
|
let zhWatch = null;
|
|
2121
2168
|
let zhGenerating = false;
|
|
@@ -2145,9 +2192,17 @@ async function refreshZhState() {
|
|
|
2145
2192
|
if (zhState.busy && zhState.phase) {
|
|
2146
2193
|
statusEl.textContent = zhState.phase;
|
|
2147
2194
|
statusEl.dataset.phaseShown = '1';
|
|
2148
|
-
} else if (
|
|
2195
|
+
} else if (zhState.error && zhState.error !== '已取消翻译') {
|
|
2196
|
+
// 失败原因持续留在顶栏(完整文本放 title),刷新/后台任务也能看到,不靠一次性 toast。
|
|
2197
|
+
statusEl.textContent = '翻译失败:' + zhState.error;
|
|
2198
|
+
statusEl.title = zhState.error;
|
|
2199
|
+
statusEl.dataset.errorShown = '1';
|
|
2200
|
+
if (prev.error !== zhState.error) toast('生成失败:' + zhState.error, 12000);
|
|
2201
|
+
} else if (!zhState.busy && (statusEl.dataset.phaseShown || statusEl.dataset.errorShown)) {
|
|
2149
2202
|
delete statusEl.dataset.phaseShown;
|
|
2203
|
+
delete statusEl.dataset.errorShown;
|
|
2150
2204
|
if (statusMeta) statusEl.textContent = statusMeta;
|
|
2205
|
+
statusEl.title = $('pdf-path').textContent ? `${$('pdf-path').textContent}(点击复制)` : '';
|
|
2151
2206
|
}
|
|
2152
2207
|
updateZhProgress();
|
|
2153
2208
|
ensureZhWatch();
|
|
@@ -2225,7 +2280,7 @@ $('zh-toggle').onclick = async () => {
|
|
|
2225
2280
|
await setViewMode(zhVariant === null ? (zhState.zh ? 'zh' : 'dual') : 'orig');
|
|
2226
2281
|
return;
|
|
2227
2282
|
}
|
|
2228
|
-
await
|
|
2283
|
+
await openGeneratePop(false);
|
|
2229
2284
|
};
|
|
2230
2285
|
|
|
2231
2286
|
/* ================= 视图模式(模式 A 对照 / 模式 B 分屏)=================
|
|
@@ -2284,12 +2339,55 @@ async function setViewMode(mode) {
|
|
|
2284
2339
|
$('dual-toggle').onclick = () => setViewMode(viewMode === 'dual' ? 'orig' : 'dual');
|
|
2285
2340
|
$('split-toggle').onclick = () => setViewMode(viewMode === 'split' ? 'orig' : 'split');
|
|
2286
2341
|
|
|
2342
|
+
let generateForce = false;
|
|
2343
|
+
let generateEndpoints = [];
|
|
2344
|
+
function endpointDisplay(e) {
|
|
2345
|
+
const provider = providerOf(e.baseUrl).name;
|
|
2346
|
+
return `${e.label || provider} · ${e.model || '未填模型'} · ${e.apiKeyHint || '无 Key'}`;
|
|
2347
|
+
}
|
|
2348
|
+
function closeGeneratePop() { $('generate-pop').style.display = 'none'; }
|
|
2349
|
+
async function openGeneratePop(force) {
|
|
2350
|
+
generateForce = force;
|
|
2351
|
+
let cfg;
|
|
2352
|
+
try { cfg = await api('/translate/config'); }
|
|
2353
|
+
catch (e) { toast('读取翻译端点失败:' + e.message, 8000); return; }
|
|
2354
|
+
generateEndpoints = (cfg.endpoints || []).filter((e) => e.complete);
|
|
2355
|
+
if (!generateEndpoints.length) {
|
|
2356
|
+
cfgRetryForce = force;
|
|
2357
|
+
await openCfgPop(true);
|
|
2358
|
+
return;
|
|
2359
|
+
}
|
|
2360
|
+
const sel = $('generate-endpoint');
|
|
2361
|
+
sel.innerHTML = '';
|
|
2362
|
+
for (const e of generateEndpoints) {
|
|
2363
|
+
const opt = document.createElement('option');
|
|
2364
|
+
opt.value = e.id; opt.textContent = endpointDisplay(e);
|
|
2365
|
+
sel.appendChild(opt);
|
|
2366
|
+
}
|
|
2367
|
+
sel.value = generateEndpoints.some((e) => e.id === cfg.activeId) ? cfg.activeId : generateEndpoints[0].id;
|
|
2368
|
+
const pop = $('generate-pop');
|
|
2369
|
+
pop.style.display = 'block';
|
|
2370
|
+
pop.style.left = Math.max(8, (window.innerWidth - pop.offsetWidth) / 2) + 'px';
|
|
2371
|
+
pop.style.top = Math.max(8, (window.innerHeight - pop.offsetHeight) / 3) + 'px';
|
|
2372
|
+
}
|
|
2373
|
+
$('generate-start').onclick = () => {
|
|
2374
|
+
const id = $('generate-endpoint').value;
|
|
2375
|
+
closeGeneratePop();
|
|
2376
|
+
void startGenerate(generateForce, id);
|
|
2377
|
+
};
|
|
2378
|
+
$('generate-cancel').onclick = closeGeneratePop;
|
|
2379
|
+
$('generate-manage').onclick = () => {
|
|
2380
|
+
closeGeneratePop();
|
|
2381
|
+
cfgRetryForce = generateForce;
|
|
2382
|
+
void openCfgPop(true);
|
|
2383
|
+
};
|
|
2384
|
+
|
|
2287
2385
|
// 生成/重翻共用:force=true 时服务端先删旧译文再启动;成功后轮询到完成
|
|
2288
|
-
async function startGenerate(force) {
|
|
2386
|
+
async function startGenerate(force, endpointId) {
|
|
2289
2387
|
try {
|
|
2290
2388
|
const r = await api('/zh/generate', {
|
|
2291
2389
|
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
2292
|
-
body: JSON.stringify(
|
|
2390
|
+
body: JSON.stringify({ ...current, ...(force ? { force: true } : {}), ...(endpointId ? { endpointId } : {}) }),
|
|
2293
2391
|
});
|
|
2294
2392
|
const m = zhState.model ? `(${zhState.model})` : '';
|
|
2295
2393
|
toast(r.firstRun
|
|
@@ -2298,6 +2396,7 @@ async function startGenerate(force) {
|
|
|
2298
2396
|
} catch (e) {
|
|
2299
2397
|
// 没配端点 → 直接弹配置表单;填好保存后自动回来重试(记住是不是重翻)
|
|
2300
2398
|
if (e.code === 'no-endpoint') { cfgRetryForce = force; openCfgPop(true); return; }
|
|
2399
|
+
if (e.code === 'endpoint-not-found') { toast(e.message, 6000); await openGeneratePop(force); return; }
|
|
2301
2400
|
toast(e.message, 8000); return;
|
|
2302
2401
|
}
|
|
2303
2402
|
$('zh-toggle').disabled = true; $('zh-toggle').innerHTML = iconHtml('spin');
|
|
@@ -2320,7 +2419,7 @@ async function startGenerate(force) {
|
|
|
2320
2419
|
else if (zhVariant) await activateView(zhVariant); // 单文档:缓存已被 refreshZhState 失效,重新加载新译文
|
|
2321
2420
|
else $('zh-toggle').click();
|
|
2322
2421
|
}
|
|
2323
|
-
else
|
|
2422
|
+
else if (!zhState.error) toast('生成失败:未知原因', 8000); // 具体错误已由 refreshZhState 持续展示并提示
|
|
2324
2423
|
}
|
|
2325
2424
|
}, 1000);
|
|
2326
2425
|
}
|
|
@@ -2339,7 +2438,7 @@ $('zh-regen').onclick = async () => {
|
|
|
2339
2438
|
const btn = $('zh-regen');
|
|
2340
2439
|
if (regenArmTimer) { // 第二击:确认执行
|
|
2341
2440
|
disarmRegen();
|
|
2342
|
-
await
|
|
2441
|
+
await openGeneratePop(true);
|
|
2343
2442
|
return;
|
|
2344
2443
|
}
|
|
2345
2444
|
btn.textContent = '重翻?'; // 第一击:进入待确认态
|
|
@@ -2384,6 +2483,61 @@ const providerOf = (baseUrl) => PROVIDERS.find((p) => p.id !== 'custom' && normU
|
|
|
2384
2483
|
let cfgRetryGenerate = false;
|
|
2385
2484
|
let cfgRetryForce = false; // 待重试的是不是「重翻」(regen 图标进来时旧译文还在,zh-toggle 点击语义不对,必须带 force)
|
|
2386
2485
|
let cfgRetryTranslate = false; // 待重试的是不是「划词翻译」(点「译」发现没配端点 → 填完自动重试这次翻译)
|
|
2486
|
+
let cfgEndpoints = [];
|
|
2487
|
+
let cfgEditingId = 'new';
|
|
2488
|
+
let cfgDeleteArmed = false;
|
|
2489
|
+
|
|
2490
|
+
function fillCfgEndpoint(e) {
|
|
2491
|
+
cfgEditingId = e?.id || 'new';
|
|
2492
|
+
cfgDeleteArmed = false;
|
|
2493
|
+
$('cfg-delete').textContent = '删除当前';
|
|
2494
|
+
$('cfg-delete').disabled = !e || e.source === 'profile';
|
|
2495
|
+
$('cfg-url').value = e?.baseUrl || '';
|
|
2496
|
+
$('cfg-model').value = e?.model || '';
|
|
2497
|
+
const sel = $('cfg-provider');
|
|
2498
|
+
sel.value = providerOf(e?.baseUrl).id;
|
|
2499
|
+
const keepUrl = $('cfg-url').value, keepModel = $('cfg-model').value;
|
|
2500
|
+
sel.onchange();
|
|
2501
|
+
$('cfg-url').value = keepUrl || $('cfg-url').value;
|
|
2502
|
+
$('cfg-model').value = keepModel || $('cfg-model').value;
|
|
2503
|
+
$('cfg-key').value = '';
|
|
2504
|
+
$('cfg-key').placeholder = e?.hasApiKey ? `已保存(${e.apiKeyHint}),留空则不修改` : 'sk-...';
|
|
2505
|
+
$('cfg-source').textContent = e
|
|
2506
|
+
? `${e.source === 'profile' ? 'profile 默认配置(保存会另存为本界面配置)' : '本界面保存的配置'}(key ${e.apiKeyHint || '未填'})`
|
|
2507
|
+
: '新端点:保存前会先做连接测试';
|
|
2508
|
+
}
|
|
2509
|
+
function fillCfgList(activeId) {
|
|
2510
|
+
const sel = $('cfg-saved');
|
|
2511
|
+
sel.innerHTML = '';
|
|
2512
|
+
for (const e of cfgEndpoints) {
|
|
2513
|
+
const opt = document.createElement('option');
|
|
2514
|
+
opt.value = e.id; opt.textContent = endpointDisplay(e) + (e.complete ? '' : '(不完整)');
|
|
2515
|
+
sel.appendChild(opt);
|
|
2516
|
+
}
|
|
2517
|
+
const add = document.createElement('option');
|
|
2518
|
+
add.value = 'new'; add.textContent = '+ 新建端点…';
|
|
2519
|
+
sel.appendChild(add);
|
|
2520
|
+
const selected = cfgEndpoints.find((e) => e.id === activeId) || null;
|
|
2521
|
+
sel.value = selected?.id || 'new';
|
|
2522
|
+
fillCfgEndpoint(selected);
|
|
2523
|
+
}
|
|
2524
|
+
$('cfg-saved').onchange = () => fillCfgEndpoint(cfgEndpoints.find((e) => e.id === $('cfg-saved').value) || null);
|
|
2525
|
+
$('cfg-new').onclick = () => { $('cfg-saved').value = 'new'; fillCfgEndpoint(null); };
|
|
2526
|
+
$('cfg-delete').onclick = async () => {
|
|
2527
|
+
const e = cfgEndpoints.find((x) => x.id === cfgEditingId);
|
|
2528
|
+
if (!e || e.source === 'profile') return;
|
|
2529
|
+
if (!cfgDeleteArmed) {
|
|
2530
|
+
cfgDeleteArmed = true;
|
|
2531
|
+
$('cfg-delete').textContent = '确认删除?';
|
|
2532
|
+
setTimeout(() => { cfgDeleteArmed = false; $('cfg-delete').textContent = '删除当前'; }, 3000);
|
|
2533
|
+
return;
|
|
2534
|
+
}
|
|
2535
|
+
try {
|
|
2536
|
+
await api('/translate/config?id=' + encodeURIComponent(e.id), { method: 'DELETE' });
|
|
2537
|
+
toast('端点已删除');
|
|
2538
|
+
await openCfgPop(false);
|
|
2539
|
+
} catch (err) { toast('删除失败:' + err.message, 8000); }
|
|
2540
|
+
};
|
|
2387
2541
|
|
|
2388
2542
|
async function openCfgPop(retryGenerate) {
|
|
2389
2543
|
$('theme-pop').style.display = 'none'; // 与深色面板互斥:同时只开一个
|
|
@@ -2392,23 +2546,8 @@ async function openCfgPop(retryGenerate) {
|
|
|
2392
2546
|
try {
|
|
2393
2547
|
cfg = await api('/translate/config');
|
|
2394
2548
|
} catch (e) { toast('读取配置失败:' + e.message, 8000); return; }
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
// 按已存 URL 回显供应商,并触发一次 onchange 补齐模型候选(但不覆盖已存模型/URL)
|
|
2398
|
-
const sel = $('cfg-provider');
|
|
2399
|
-
sel.value = providerOf(cfg.baseUrl).id;
|
|
2400
|
-
const keepUrl = $('cfg-url').value, keepModel = $('cfg-model').value;
|
|
2401
|
-
sel.onchange();
|
|
2402
|
-
$('cfg-url').value = keepUrl || $('cfg-url').value;
|
|
2403
|
-
$('cfg-model').value = keepModel || $('cfg-model').value;
|
|
2404
|
-
// 明文 key 不回传:留空 = 沿用已存的那把
|
|
2405
|
-
$('cfg-key').value = '';
|
|
2406
|
-
$('cfg-key').placeholder = cfg.hasApiKey ? `已保存(${cfg.apiKeyHint}),留空则不修改` : 'sk-...';
|
|
2407
|
-
// 生效配置的来源:界面保存的文件 优先于 profile 的 YAML 默认值——两条来源都有时不说明会分不清生效的是谁
|
|
2408
|
-
$('cfg-source').textContent =
|
|
2409
|
-
cfg.source === 'file' ? `当前生效:本界面保存的配置(key ${cfg.apiKeyHint})`
|
|
2410
|
-
: cfg.source === 'profile' ? '当前生效:profile 默认配置(在本界面保存后会被覆盖)'
|
|
2411
|
-
: '';
|
|
2549
|
+
cfgEndpoints = cfg.endpoints || [];
|
|
2550
|
+
fillCfgList(cfg.activeId);
|
|
2412
2551
|
const pop = $('cfg-pop');
|
|
2413
2552
|
pop.style.display = 'block';
|
|
2414
2553
|
// 先显示再量尺寸(不像 #ask-pop 那样写死尺寸常量,免得跟 CSS 漂移)
|
|
@@ -2431,16 +2570,19 @@ document.addEventListener('click', (e) => {
|
|
|
2431
2570
|
});
|
|
2432
2571
|
$('cfg-cancel').onclick = closeCfgPop;
|
|
2433
2572
|
|
|
2434
|
-
|
|
2573
|
+
async function saveCfg(saveAsNew) {
|
|
2435
2574
|
// retry/force/translate 先捞出来:closeCfgPop 会把这三个待确认态清零
|
|
2436
|
-
const btn = $('cfg-save'), label = btn.textContent
|
|
2575
|
+
const btn = saveAsNew ? $('cfg-save-new') : $('cfg-save'), label = btn.textContent;
|
|
2576
|
+
const retry = cfgRetryGenerate, force = cfgRetryForce, retryTr = cfgRetryTranslate;
|
|
2437
2577
|
btn.disabled = true; btn.textContent = '测试中…';
|
|
2578
|
+
let saved;
|
|
2438
2579
|
try {
|
|
2439
2580
|
// 服务端先打一发极小的 chat/completions 验证 url/key/model,通过才落盘
|
|
2440
|
-
await api('/translate/config', {
|
|
2581
|
+
saved = await api('/translate/config', {
|
|
2441
2582
|
method: 'POST',
|
|
2442
2583
|
headers: { 'content-type': 'application/json' },
|
|
2443
2584
|
body: JSON.stringify({
|
|
2585
|
+
id: saveAsNew ? 'new' : cfgEditingId,
|
|
2444
2586
|
baseUrl: $('cfg-url').value.trim(),
|
|
2445
2587
|
apiKey: $('cfg-key').value.trim(),
|
|
2446
2588
|
model: $('cfg-model').value.trim(),
|
|
@@ -2454,10 +2596,12 @@ $('cfg-save').onclick = async () => {
|
|
|
2454
2596
|
}
|
|
2455
2597
|
closeCfgPop();
|
|
2456
2598
|
await refreshZhState();
|
|
2457
|
-
if (retry) startGenerate(force); //
|
|
2599
|
+
if (retry) startGenerate(force, saved.id); // 用刚保存的端点继续,不让旧 active 抢回去
|
|
2458
2600
|
else if (retryTr) translateSelection(); // 划词翻译发现没配端点 → 填完自动重试这一次翻译(§3.7①)
|
|
2459
2601
|
else toast('翻译端点已保存');
|
|
2460
|
-
}
|
|
2602
|
+
}
|
|
2603
|
+
$('cfg-save').onclick = () => saveCfg(false);
|
|
2604
|
+
$('cfg-save-new').onclick = () => saveCfg(true);
|
|
2461
2605
|
|
|
2462
2606
|
/* ================= PDF 渲染(pdf.js:缩放 + devicePixelRatio 高清,移植自 pdfqa) ================= */
|
|
2463
2607
|
/* pdf.js 6.x 本地 vendor:动态 import(缓存的 Promise),loadPdf 先 await 再用——
|
|
@@ -3611,6 +3755,13 @@ function renderEqPanel() {
|
|
|
3611
3755
|
}
|
|
3612
3756
|
}
|
|
3613
3757
|
|
|
3758
|
+
function transcribeResultText(t) {
|
|
3759
|
+
const chars = typeof t.chars === 'number' ? `(${t.chars} 字符)` : '';
|
|
3760
|
+
const engine = t.producer === 'mineru-local' || t.producer === 'mineru-cloud' ? 'MinerU' : 'pdf.js';
|
|
3761
|
+
if (t.source === 'cache') return `已有 ${engine} 转录缓存,直接复用${chars}`;
|
|
3762
|
+
return `${engine} 转录完成${chars}`;
|
|
3763
|
+
}
|
|
3764
|
+
|
|
3614
3765
|
$('transcribe-open').onclick = async () => {
|
|
3615
3766
|
if (!current) return;
|
|
3616
3767
|
const ref = { ...current };
|
|
@@ -3632,7 +3783,7 @@ $('transcribe-open').onclick = async () => {
|
|
|
3632
3783
|
statusMeta = `${ref.name} · ${t.pageCount ?? '?'} 页`;
|
|
3633
3784
|
$('status').textContent = statusMeta;
|
|
3634
3785
|
syncTranscribeButton();
|
|
3635
|
-
toast(t
|
|
3786
|
+
toast(transcribeResultText(t));
|
|
3636
3787
|
await loadFormulas();
|
|
3637
3788
|
if (pdfDoc) await rerender();
|
|
3638
3789
|
} catch (e) {
|
|
@@ -145,6 +145,15 @@ _TOO_LONG_RE = re.compile(
|
|
|
145
145
|
re.I,
|
|
146
146
|
)
|
|
147
147
|
_THINKING_RE = re.compile(r"始终思考|不支持关闭思考|thinking|推理", re.I)
|
|
148
|
+
_QUOTA_EXHAUSTED_RE = re.compile(
|
|
149
|
+
r"每周/每月使用上限|(?:weekly|monthly).*(?:quota|limit)|['\"]code['\"]:\s*['\"]1310['\"]",
|
|
150
|
+
re.I,
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def is_quota_exhausted(error: BaseException) -> bool:
|
|
155
|
+
"""周期配额耗尽不是瞬时限流:重试一百次也不会成功,必须尽快把原因带回 UI。"""
|
|
156
|
+
return bool(_QUOTA_EXHAUSTED_RE.search(str(error)))
|
|
148
157
|
|
|
149
158
|
|
|
150
159
|
def rough_tokens(text: str) -> int:
|
|
@@ -209,7 +218,7 @@ def install_translation() -> None:
|
|
|
209
218
|
import openai
|
|
210
219
|
from tenacity import before_sleep_log
|
|
211
220
|
from tenacity import retry
|
|
212
|
-
from tenacity import
|
|
221
|
+
from tenacity import retry_if_exception
|
|
213
222
|
from tenacity import stop_after_attempt
|
|
214
223
|
from tenacity import wait_exponential
|
|
215
224
|
|
|
@@ -280,7 +289,9 @@ def install_translation() -> None:
|
|
|
280
289
|
raise
|
|
281
290
|
|
|
282
291
|
@retry(
|
|
283
|
-
retry=
|
|
292
|
+
retry=retry_if_exception(
|
|
293
|
+
lambda exc: isinstance(exc, openai.RateLimitError) and not is_quota_exhausted(exc)
|
|
294
|
+
),
|
|
284
295
|
stop=stop_after_attempt(100),
|
|
285
296
|
wait=wait_exponential(multiplier=1, min=1, max=15),
|
|
286
297
|
before_sleep=before_sleep_log(log, logging.WARNING),
|