dsh-pdf-workbench 1.4.1 → 1.5.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 +29 -7
- package/client.js +4106 -469
- package/docs/LAYOUT.md +56 -0
- package/docs/RELEASE.md +8 -0
- package/docs/TESTING.md +16 -0
- package/docs/ci.md +18 -13
- package/docs/copy/templates.md +4 -4
- package/docs/decisions.md +119 -0
- package/docs/features.md +14 -8
- package/docs/requirements/2026-11-25-v1.5/346/224/271/350/277/233/351/234/200/346/261/202.md +622 -0
- package/docs/roles/{release-manager.md → ci.md} +37 -47
- package/docs/roles/programmer.md +45 -59
- package/docs/roles/requirements.md +68 -0
- package/docs/todo.md +590 -32
- package/index.js +337 -1
- package/package.json +1 -1
- package/src/host/backup.js +172 -33
- package/src/host/book-wizard.js +454 -0
- package/src/host/digest.js +4 -0
- package/src/host/engine.js +88 -0
- package/src/host/exports.js +159 -0
- package/src/host/http.js +28 -1
- package/src/host/imports.js +650 -0
- package/src/host/index-source.js +117 -11
- package/src/host/library-export.js +162 -0
- package/src/host/pdf-source.js +6 -2
- package/src/host/routes.js +1020 -120
- package/src/host/shortcut.js +238 -0
- package/src/host/storage.js +421 -0
- package/src/host/translate-blocks.js +49 -45
- package/src/host/translate-job.js +37 -10
- package/src/host/translate.js +19 -45
- package/src/host/translation-cache.js +209 -0
- package/src/host/typst-install.js +132 -0
- package/src/host/zip.js +486 -4
- package/tools/latex_to_typst.py +1353 -0
- package/tools/md2overlay.py +147 -152
- package/tools/md2overlay_typst.py +312 -0
- package/tools/md2typst.py +818 -0
- package/tools/overlay_layout.py +332 -0
- package/tools/pdf_blocks.py +82 -10
- package/tools/realign_overlay.py +4 -1
- package/tools/rebuild_overlay.py +3 -1
- package/tools/split_pdf.py +158 -0
- package/tools/typst_runtime.py +98 -0
- package/vendor/katex/LICENSE +21 -0
- package/vendor/katex/fonts/KaTeX_AMS-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Main-Bold.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Main-Italic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Main-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Math-Italic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Script-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Size1-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Size2-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Size3-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Size4-Regular.woff2 +0 -0
- package/vendor/katex/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
- package/vendor/katex/katex.min.css +1 -0
- package/vendor/katex/katex.min.js +1 -0
- package//345/256/211/350/243/205/344/270/216/345/210/206/345/217/221.md +9 -1
- package/docs/boss-handover.md +0 -84
- package/docs/roles/auditor.md +0 -123
- package/docs/roles/boss.md +0 -162
- package/docs/roles/code-reviewer.md +0 -132
- package/docs/roles/feature-inventory.md +0 -119
- package/docs/roles/feedback-collector.md +0 -105
- package/docs/roles/tester.md +0 -140
- package/docs/roles/ui-copywriter.md +0 -122
- package/src/host/book-import.js +0 -98
|
@@ -4,12 +4,12 @@
|
|
|
4
4
|
* The model gets the page image once plus the block list, and returns a JSON
|
|
5
5
|
* object mapping block id to translated Markdown. Cost stays close to the
|
|
6
6
|
* whole-page call; only missing or invalid blocks are retried.
|
|
7
|
+
*
|
|
8
|
+
* The caller owns the transport: it stores the page image and passes the same
|
|
9
|
+
* `chat` function `translate.js` uses, so both paths always call one model.
|
|
7
10
|
* @module dsh-pdf-workbench/translate-blocks
|
|
8
11
|
*/
|
|
9
12
|
|
|
10
|
-
const API_URL = 'https://api.deepseek.com/chat/completions'
|
|
11
|
-
const MODEL = 'deepseek-flash'
|
|
12
|
-
|
|
13
13
|
function promptFor(target, blocks) {
|
|
14
14
|
const language = target === 'zh' ? 'Simplified Chinese' : 'English'
|
|
15
15
|
const list = blocks.map(block => `${block.id}: ${block.text}`).join('\n')
|
|
@@ -18,8 +18,11 @@ function promptFor(target, blocks) {
|
|
|
18
18
|
`Translate each block below into ${language}.`,
|
|
19
19
|
'Keep every mathematical formula as LaTeX ($...$ inline, $$...$$ display).',
|
|
20
20
|
'Do not translate variable names or theorem numbers.',
|
|
21
|
+
// The overlay places one translated block back on one original block, so a
|
|
22
|
+
// merged or split answer silently shifts every box on the page.
|
|
23
|
+
'Translate each block independently: never merge two blocks and never split one block into two entries.',
|
|
24
|
+
'Every block id must appear exactly once; keep an empty string for a block with nothing to translate.',
|
|
21
25
|
'Reply with a JSON object only: block id -> translated Markdown string.',
|
|
22
|
-
'Every block id must appear exactly once; keep empty strings for blocks without text.',
|
|
23
26
|
'',
|
|
24
27
|
'BLOCKS:',
|
|
25
28
|
list,
|
|
@@ -79,54 +82,55 @@ function unwrap(parsed) {
|
|
|
79
82
|
}
|
|
80
83
|
|
|
81
84
|
/**
|
|
82
|
-
* @param {{
|
|
85
|
+
* @param {{ chat: Function, image: object, blocks: object[], target: 'zh'|'en', signal?: AbortSignal, onUsage?: Function }} options - the Host channel, the stored page image, and the block list.
|
|
83
86
|
* @returns {Promise<object[]>} blocks with `md` filled in.
|
|
84
87
|
*/
|
|
85
88
|
export async function translatePageBlocks(options) {
|
|
86
|
-
if (typeof options.
|
|
87
|
-
throw new Error('
|
|
89
|
+
if (typeof options.chat !== 'function') {
|
|
90
|
+
throw new Error('翻译通道不可用:请在 设置 → AI 模型 选择翻译模型')
|
|
88
91
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
role: 'user',
|
|
101
|
-
content: [
|
|
102
|
-
{ type: 'text', text: promptFor(options.target, options.blocks) },
|
|
103
|
-
{ type: 'image_url', image_url: { url: options.image } },
|
|
104
|
-
],
|
|
105
|
-
},
|
|
106
|
-
],
|
|
107
|
-
}),
|
|
108
|
-
})
|
|
109
|
-
if (!response.ok) {
|
|
110
|
-
const detail = await response.text().catch(() => '')
|
|
111
|
-
throw new Error(`DeepSeek API ${response.status}: ${detail.slice(0, 300)}`)
|
|
112
|
-
}
|
|
113
|
-
const data = await response.json()
|
|
114
|
-
if (typeof options.onUsage === 'function' && data !== null && typeof data === 'object' && data.usage) {
|
|
115
|
-
const usage = data.usage
|
|
116
|
-
options.onUsage({
|
|
117
|
-
input: Number(usage.prompt_tokens) || 0,
|
|
118
|
-
output: Number(usage.completion_tokens) || 0,
|
|
119
|
-
total: Number(usage.total_tokens) || 0,
|
|
92
|
+
/**
|
|
93
|
+
* One request for one list of blocks.
|
|
94
|
+
* @param {object[]} list - the blocks to translate.
|
|
95
|
+
* @returns {Promise<object>} the parsed id → Markdown mapping.
|
|
96
|
+
*/
|
|
97
|
+
const ask = async list => {
|
|
98
|
+
const content = await options.chat({
|
|
99
|
+
prompt: promptFor(options.target, list),
|
|
100
|
+
image: options.image,
|
|
101
|
+
signal: options.signal,
|
|
102
|
+
onUsage: options.onUsage,
|
|
120
103
|
})
|
|
104
|
+
if (typeof content !== 'string' || content.trim() === '') throw new Error('模型返回了空内容')
|
|
105
|
+
return unwrap(parseJson(content))
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const blocks = options.blocks
|
|
109
|
+
let mapping = await ask(blocks)
|
|
110
|
+
const ids = new Set(blocks.map(block => block.id))
|
|
111
|
+
const matched = () => Object.keys(mapping).filter(key => ids.has(key) && typeof mapping[key] === 'string')
|
|
112
|
+
if (matched().length === 0) {
|
|
113
|
+
// An answer that names no block id is a format failure, not a partial page:
|
|
114
|
+
// retry the same list once, then give up so the job falls back to whole-page.
|
|
115
|
+
mapping = await ask(blocks)
|
|
116
|
+
if (matched().length === 0) throw new Error('模型没有按块返回(键名与块 id 不匹配)')
|
|
117
|
+
}
|
|
118
|
+
// Retry only the blocks this answer skipped. One extra image request beats a
|
|
119
|
+
// silent hole in the overlay, which used to look like a successful page.
|
|
120
|
+
const missing = blocks.filter(block => typeof mapping[block.id] !== 'string')
|
|
121
|
+
if (missing.length > 0) {
|
|
122
|
+
try {
|
|
123
|
+
const retried = await ask(missing)
|
|
124
|
+
for (const block of missing) {
|
|
125
|
+
if (typeof retried[block.id] === 'string') mapping[block.id] = retried[block.id]
|
|
126
|
+
}
|
|
127
|
+
} catch {
|
|
128
|
+
// Keep the first answer; the caller marks whatever stayed empty.
|
|
129
|
+
}
|
|
121
130
|
}
|
|
122
|
-
|
|
123
|
-
if (typeof content !== 'string' || content.trim() === '') throw new Error('DeepSeek API 返回了空内容')
|
|
124
|
-
const mapping = unwrap(parseJson(content))
|
|
125
|
-
const known = new Set(options.blocks.map(block => block.id))
|
|
126
|
-
const matched = Object.keys(mapping).filter(key => known.has(key))
|
|
127
|
-
if (matched.length === 0) throw new Error('模型没有按块返回(键名与块 id 不匹配)')
|
|
128
|
-
return options.blocks.map(block => ({
|
|
131
|
+
return blocks.map(block => ({
|
|
129
132
|
...block,
|
|
130
133
|
md: typeof mapping[block.id] === 'string' ? mapping[block.id] : '',
|
|
134
|
+
missing: typeof mapping[block.id] !== 'string',
|
|
131
135
|
}))
|
|
132
136
|
}
|
|
@@ -70,10 +70,19 @@ function fontClassOf(fontPt) {
|
|
|
70
70
|
|
|
71
71
|
/**
|
|
72
72
|
* Start a chapter translation; resolves nothing, writes progress to `jobPath`.
|
|
73
|
-
* @param {{ rasterScript: string, md2texScript: string,
|
|
73
|
+
* @param {{ rasterScript: string, md2texScript: string, ai: object, source: string, outPath: string, jobPath: string, target: 'zh'|'en', book: string, code: string }} options - job inputs.
|
|
74
74
|
* @returns {Promise<string>} the job id.
|
|
75
75
|
*/
|
|
76
76
|
export async function startChapterJob(options) {
|
|
77
|
+
if (options.ai === null || options.ai === undefined || typeof options.ai.chat !== 'function' || typeof options.ai.image !== 'function') {
|
|
78
|
+
throw new Error('没有可用的翻译模型:请在 设置 → AI 模型 选择')
|
|
79
|
+
}
|
|
80
|
+
// The engine (v1.5 D) chooses its overlay script and hands Typst's location to
|
|
81
|
+
// the Python child; the defaults keep the LaTeX kernels for old callers/tests.
|
|
82
|
+
const overlayScript = typeof options.overlayScript === 'string' && options.overlayScript !== ''
|
|
83
|
+
? options.overlayScript
|
|
84
|
+
: join(options.toolsDir, 'md2overlay.py')
|
|
85
|
+
const typstEnv = options.typstEnv !== null && typeof options.typstEnv === 'object' ? options.typstEnv : {}
|
|
77
86
|
const jobId = `tr-${Date.now().toString(36)}`
|
|
78
87
|
const state = {
|
|
79
88
|
id: jobId,
|
|
@@ -81,6 +90,7 @@ export async function startChapterJob(options) {
|
|
|
81
90
|
book: options.book,
|
|
82
91
|
code: options.code,
|
|
83
92
|
target: options.target,
|
|
93
|
+
model: options.ai.label,
|
|
84
94
|
total: 0,
|
|
85
95
|
done: 0,
|
|
86
96
|
failed: 0,
|
|
@@ -136,7 +146,9 @@ export async function startChapterJob(options) {
|
|
|
136
146
|
// no cached page: translate it below
|
|
137
147
|
}
|
|
138
148
|
}
|
|
139
|
-
|
|
149
|
+
// One image per page: the block call and the whole-page fallback share
|
|
150
|
+
// the same stored attachment, so a retry costs no extra storage.
|
|
151
|
+
const image = await options.ai.image(await readFile(join(temporary, files[index])))
|
|
140
152
|
let pageMarkdown = ''
|
|
141
153
|
let blockError = ''
|
|
142
154
|
if (typeof options.cacheDir === 'string' && typeof options.toolsDir === 'string') {
|
|
@@ -145,13 +157,19 @@ export async function startChapterJob(options) {
|
|
|
145
157
|
const blocks = JSON.parse(raw)
|
|
146
158
|
if (Array.isArray(blocks) && blocks.length > 0) {
|
|
147
159
|
const translated = await translatePageBlocks({
|
|
148
|
-
|
|
160
|
+
chat: options.ai.chat,
|
|
149
161
|
image,
|
|
150
162
|
blocks,
|
|
151
163
|
target: options.target,
|
|
152
164
|
onUsage: addUsage,
|
|
153
165
|
})
|
|
154
166
|
const name = `page-${String(index + 1).padStart(3, '0')}.blocks.json`
|
|
167
|
+
// A page that came back with holes is not a success: the overlay
|
|
168
|
+
// would show an empty box and the note would stay silent.
|
|
169
|
+
const missingBlocks = translated.filter(block => block.missing === true).length
|
|
170
|
+
if (missingBlocks > 0) {
|
|
171
|
+
blockError = `第 ${index + 1} 页有 ${missingBlocks} 个块没有返回译文`
|
|
172
|
+
}
|
|
155
173
|
pageMarkdown = translated.map(block => block.md).filter(part => part !== '').join('\n\n')
|
|
156
174
|
if (pageMarkdown.trim() !== '') {
|
|
157
175
|
await writeFile(join(options.cacheDir, name), JSON.stringify(translated), 'utf8').catch(() => {})
|
|
@@ -175,10 +193,12 @@ export async function startChapterJob(options) {
|
|
|
175
193
|
}
|
|
176
194
|
if (pageMarkdown.trim() === '') {
|
|
177
195
|
try {
|
|
178
|
-
pageMarkdown = await translatePage({
|
|
179
|
-
} catch {
|
|
196
|
+
pageMarkdown = await translatePage({ chat: options.ai.chat, image, target: options.target, onUsage: addUsage })
|
|
197
|
+
} catch (error) {
|
|
180
198
|
// One page failing must not throw away the pages that worked: keep
|
|
181
|
-
// the page empty, remember
|
|
199
|
+
// the page empty, remember why, and let the chapter finish.
|
|
200
|
+
const message = String(error !== null && error !== undefined && error.message ? error.message : error)
|
|
201
|
+
state.blockErrors = Array.from(new Set([...(state.blockErrors ?? []), `第 ${index + 1} 页:整页翻译失败:${message}`]))
|
|
182
202
|
pageMarkdown = ''
|
|
183
203
|
}
|
|
184
204
|
}
|
|
@@ -193,7 +213,10 @@ export async function startChapterJob(options) {
|
|
|
193
213
|
}
|
|
194
214
|
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, files.length) }, () => worker()))
|
|
195
215
|
if (chunks.every(chunk => chunk.trim() === '')) {
|
|
196
|
-
|
|
216
|
+
// "All pages empty" alone told the user nothing; carry the first real
|
|
217
|
+
// reason (provider error, missing session header, auth, …) into the job.
|
|
218
|
+
const first = Array.isArray(state.blockErrors) && state.blockErrors.length > 0 ? String(state.blockErrors[0]) : ''
|
|
219
|
+
throw new Error(`所有页面都没有返回译文(${options.ai.label})${first === '' ? '' : `:${first.slice(0, 300)}`}`)
|
|
197
220
|
}
|
|
198
221
|
if (typeof options.cacheDir === 'string' && options.cacheDir !== '') {
|
|
199
222
|
await mkdir(options.cacheDir, { recursive: true })
|
|
@@ -227,13 +250,13 @@ export async function startChapterJob(options) {
|
|
|
227
250
|
if (typeof options.cacheDir === 'string' && options.cacheDir !== '') {
|
|
228
251
|
try {
|
|
229
252
|
const blocksFile = join(options.cacheDir, `page-${String(index + 1).padStart(3, '0')}.blocks.json`)
|
|
230
|
-
await capture(
|
|
253
|
+
await capture(overlayScript, [
|
|
231
254
|
blocksFile,
|
|
232
255
|
miniPdf,
|
|
233
256
|
String(size[0]),
|
|
234
257
|
String(size[1]),
|
|
235
258
|
fontClass,
|
|
236
|
-
])
|
|
259
|
+
], typstEnv)
|
|
237
260
|
positioned = true
|
|
238
261
|
} catch {
|
|
239
262
|
positioned = false
|
|
@@ -243,6 +266,7 @@ export async function startChapterJob(options) {
|
|
|
243
266
|
reflowPages.push(index + 1)
|
|
244
267
|
await writeFile(miniMd, chunks[index], 'utf8')
|
|
245
268
|
await renderMarkdown(options.md2texScript, miniMd, miniPdf, {
|
|
269
|
+
...typstEnv,
|
|
246
270
|
MATH_DESK_NO_TITLE: '1',
|
|
247
271
|
MATH_DESK_PAPER: `${size[0] / 72},${size[1] / 72}`,
|
|
248
272
|
MATH_DESK_FONTSIZE: fontClass,
|
|
@@ -255,8 +279,10 @@ export async function startChapterJob(options) {
|
|
|
255
279
|
// The overlay is only positionally aligned when every page came from
|
|
256
280
|
// its block boxes. Say so instead of letting the boxes look broken.
|
|
257
281
|
if (reflowPages.length > 0) state.overlayReflowPages = reflowPages
|
|
258
|
-
} catch {
|
|
282
|
+
} catch (error) {
|
|
259
283
|
// The overlay PDF is optional; the natural reading PDF still exists.
|
|
284
|
+
// Say why it is missing instead of silently falling back next time.
|
|
285
|
+
state.overlayError = String(error !== null && error !== undefined && error.message ? error.message : error).slice(0, 400)
|
|
260
286
|
}
|
|
261
287
|
}
|
|
262
288
|
const title = basename(options.outPath, '.pdf').replace(/_translated$/i, '')
|
|
@@ -286,6 +312,7 @@ export async function startChapterJob(options) {
|
|
|
286
312
|
markdownPath,
|
|
287
313
|
options.outPath,
|
|
288
314
|
{
|
|
315
|
+
...typstEnv,
|
|
289
316
|
// The translated pages keep the book's headings; a generated one
|
|
290
317
|
// would print the chapter's file name on top of page 1.
|
|
291
318
|
MATH_DESK_NO_TITLE: '1',
|
package/src/host/translate.js
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Translate one rendered PDF page
|
|
2
|
+
* Translate one rendered PDF page through the Host model channel.
|
|
3
3
|
*
|
|
4
|
-
* The
|
|
5
|
-
*
|
|
4
|
+
* The caller owns the model: it stores the page image once with
|
|
5
|
+
* `ctx.attachments`, picks the provider/model from the user's "whole-chapter
|
|
6
|
+
* translation" choice, and passes a `chat` function here. This module only keeps
|
|
7
|
+
* the prompt and the post-processing, so switching models never changes how a
|
|
8
|
+
* page is described or how its Markdown is repaired.
|
|
9
|
+
*
|
|
10
|
+
* The model returns Markdown with LaTeX formulas preserved; the caller renders
|
|
11
|
+
* that Markdown with `md2tex.py`.
|
|
6
12
|
* @module dsh-pdf-workbench/translate
|
|
7
13
|
*/
|
|
8
14
|
|
|
9
|
-
const API_URL = 'https://api.deepseek.com/chat/completions'
|
|
10
|
-
const MODEL = 'deepseek-flash'
|
|
11
|
-
|
|
12
15
|
function promptFor(target) {
|
|
13
16
|
const direction = target === 'zh' ? 'Simplified Chinese' : 'English'
|
|
14
17
|
return [
|
|
@@ -29,8 +32,8 @@ function promptFor(target) {
|
|
|
29
32
|
*/
|
|
30
33
|
function balanceMath(markdown) {
|
|
31
34
|
let text = markdown
|
|
32
|
-
.replace(/\\\[/g, '$$')
|
|
33
|
-
.replace(/\\\]/g, '$$')
|
|
35
|
+
.replace(/\\\[/g, () => '$$')
|
|
36
|
+
.replace(/\\\]/g, () => '$$')
|
|
34
37
|
.replace(/\\\(/g, '$')
|
|
35
38
|
.replace(/\\\)/g, '$')
|
|
36
39
|
// Split on display delimiters: odd chunks are inside `$$...$$`, so their
|
|
@@ -45,50 +48,21 @@ function balanceMath(markdown) {
|
|
|
45
48
|
}
|
|
46
49
|
|
|
47
50
|
/**
|
|
48
|
-
* @param {{
|
|
51
|
+
* @param {{ chat: Function, image: object, target: 'zh'|'en', signal?: AbortSignal, onUsage?: Function }} options - the Host channel, the stored page image, and the target language.
|
|
49
52
|
* @returns {Promise<string>} Markdown produced by the model.
|
|
50
53
|
*/
|
|
51
54
|
export async function translatePage(options) {
|
|
52
|
-
if (typeof options.
|
|
53
|
-
throw new Error('
|
|
55
|
+
if (typeof options.chat !== 'function') {
|
|
56
|
+
throw new Error('翻译通道不可用:请在 设置 → AI 模型 选择翻译模型')
|
|
54
57
|
}
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
'Content-Type': 'application/json',
|
|
59
|
-
Authorization: `Bearer ${options.apiKey}`,
|
|
60
|
-
},
|
|
61
|
-
body: JSON.stringify({
|
|
62
|
-
model: MODEL,
|
|
63
|
-
temperature: 0.2,
|
|
64
|
-
messages: [
|
|
65
|
-
{
|
|
66
|
-
role: 'user',
|
|
67
|
-
content: [
|
|
68
|
-
{ type: 'text', text: promptFor(options.target) },
|
|
69
|
-
{ type: 'image_url', image_url: { url: options.image } },
|
|
70
|
-
],
|
|
71
|
-
},
|
|
72
|
-
],
|
|
73
|
-
}),
|
|
58
|
+
const content = await options.chat({
|
|
59
|
+
prompt: promptFor(options.target),
|
|
60
|
+
image: options.image,
|
|
74
61
|
signal: options.signal,
|
|
62
|
+
onUsage: options.onUsage,
|
|
75
63
|
})
|
|
76
|
-
if (!response.ok) {
|
|
77
|
-
const detail = await response.text().catch(() => '')
|
|
78
|
-
throw new Error(`DeepSeek API ${response.status}: ${detail.slice(0, 300)}`)
|
|
79
|
-
}
|
|
80
|
-
const data = await response.json()
|
|
81
|
-
if (typeof options.onUsage === 'function' && data !== null && typeof data === 'object' && data.usage) {
|
|
82
|
-
const usage = data.usage
|
|
83
|
-
options.onUsage({
|
|
84
|
-
input: Number(usage.prompt_tokens) || 0,
|
|
85
|
-
output: Number(usage.completion_tokens) || 0,
|
|
86
|
-
total: Number(usage.total_tokens) || 0,
|
|
87
|
-
})
|
|
88
|
-
}
|
|
89
|
-
const content = data?.choices?.[0]?.message?.content
|
|
90
64
|
if (typeof content !== 'string' || content.trim() === '') {
|
|
91
|
-
throw new Error('
|
|
65
|
+
throw new Error('模型返回了空内容')
|
|
92
66
|
}
|
|
93
67
|
return balanceMath(content.trim())
|
|
94
68
|
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where one chapter's translation cache lives, and the one-time move from the
|
|
3
|
+
* old global folder.
|
|
4
|
+
*
|
|
5
|
+
* Until v1.5 the per-page cache sat under `%DSH_HOME%/pdfdesk/translation/<书id>/
|
|
6
|
+
* <章>/`, keyed only by the book id. Two libraries can hold two different books
|
|
7
|
+
* that share an id (or the same book added twice), and those two chapters then
|
|
8
|
+
* read each other's pages. DEC-0014 §5 moves the cache into the library itself,
|
|
9
|
+
* so the folder is scoped by library and book: `<书库>/.pdfdesk/translation/`.
|
|
10
|
+
*
|
|
11
|
+
* The migration runs once per process, never deletes data it cannot place, and
|
|
12
|
+
* leaves `.migrated-from-global` behind for diagnosis.
|
|
13
|
+
*
|
|
14
|
+
* @module dsh-pdf-workbench/translation-cache
|
|
15
|
+
*/
|
|
16
|
+
import { copyFile, mkdir, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
17
|
+
import { join } from 'node:path'
|
|
18
|
+
|
|
19
|
+
/** Library-owned plugin data folder (documents, annotations, caches). */
|
|
20
|
+
const LIBRARY_DATA = '.pdfdesk'
|
|
21
|
+
|
|
22
|
+
/** Folder inside a library that holds per-page translation caches. */
|
|
23
|
+
const TRANSLATION = 'translation'
|
|
24
|
+
|
|
25
|
+
/** Marker written next to one migrated book's cache. */
|
|
26
|
+
export const MIGRATION_MARKER = '.migrated-from-global'
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The translation cache root of one library.
|
|
30
|
+
* @param {{ libraryDir: string }} library - a library entry.
|
|
31
|
+
* @returns {string} `<libraryDir>/.pdfdesk/translation`.
|
|
32
|
+
*/
|
|
33
|
+
export function translationRoot(library) {
|
|
34
|
+
return join(library.libraryDir, LIBRARY_DATA, TRANSLATION)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The cache folder of one chapter.
|
|
39
|
+
* @param {{ libraryDir: string }} library - a library entry.
|
|
40
|
+
* @param {string} bookId - book id.
|
|
41
|
+
* @param {string} code - chapter code (`c01`); normalized to lower case.
|
|
42
|
+
* @returns {string} the absolute folder.
|
|
43
|
+
*/
|
|
44
|
+
export function chapterCacheDir(library, bookId, code) {
|
|
45
|
+
return join(translationRoot(library), String(bookId), String(code ?? '').toLowerCase())
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The pre-v1.5 global cache root.
|
|
50
|
+
* @param {string} dataDir - `%DSH_HOME%/pdfdesk`.
|
|
51
|
+
* @returns {string} `<dataDir>/translation`.
|
|
52
|
+
*/
|
|
53
|
+
export function legacyTranslationRoot(dataDir) {
|
|
54
|
+
return join(dataDir, TRANSLATION)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Move one file, falling back to copy+delete when the two roots are on
|
|
59
|
+
* different volumes (the usual case: plugin data on C:, library on D:).
|
|
60
|
+
* @param {string} source - existing file.
|
|
61
|
+
* @param {string} target - destination path.
|
|
62
|
+
* @returns {Promise<void>}
|
|
63
|
+
*/
|
|
64
|
+
async function moveFile(source, target) {
|
|
65
|
+
try {
|
|
66
|
+
await rename(source, target)
|
|
67
|
+
return
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (error === null || error.code !== 'EXDEV') throw error
|
|
70
|
+
}
|
|
71
|
+
await copyFile(source, target)
|
|
72
|
+
const copied = await stat(target).catch(() => null)
|
|
73
|
+
const original = await stat(source).catch(() => null)
|
|
74
|
+
if (copied === null || original === null || copied.size !== original.size) {
|
|
75
|
+
throw new Error(`复制校验失败:${source}`)
|
|
76
|
+
}
|
|
77
|
+
await rm(source, { force: true })
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Book ids a library currently holds: `分片/<id>/` folders plus whole PDFs in
|
|
82
|
+
* `整本/` (a whole book's id is its file stem).
|
|
83
|
+
* @param {{ libraryDir: string, fragmentDir?: string }} library - a library entry.
|
|
84
|
+
* @returns {Promise<Set<string>>} the ids.
|
|
85
|
+
*/
|
|
86
|
+
async function bookIdsOf(library) {
|
|
87
|
+
const ids = new Set()
|
|
88
|
+
const fragmentDir = typeof library.fragmentDir === 'string' && library.fragmentDir !== ''
|
|
89
|
+
? library.fragmentDir
|
|
90
|
+
: join(library.libraryDir, '分片')
|
|
91
|
+
for (const name of await readdir(fragmentDir).catch(() => [])) {
|
|
92
|
+
const info = await stat(join(fragmentDir, name)).catch(() => null)
|
|
93
|
+
if (info !== null && info.isDirectory()) ids.add(name)
|
|
94
|
+
}
|
|
95
|
+
for (const name of await readdir(join(library.libraryDir, '整本')).catch(() => [])) {
|
|
96
|
+
if (/\.pdf$/i.test(name)) ids.add(name.replace(/\.pdf$/i, ''))
|
|
97
|
+
}
|
|
98
|
+
return ids
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* One chapter folder from the legacy cache, merged into the new place.
|
|
103
|
+
* @param {string} sourceChapter - legacy chapter folder.
|
|
104
|
+
* @param {string} targetChapter - destination chapter folder.
|
|
105
|
+
* @param {{ moved: number, kept: number, warnings: string[] }} counters - report counters.
|
|
106
|
+
* @returns {Promise<void>}
|
|
107
|
+
*/
|
|
108
|
+
async function mergeChapter(sourceChapter, targetChapter, counters) {
|
|
109
|
+
await mkdir(targetChapter, { recursive: true })
|
|
110
|
+
for (const file of await readdir(sourceChapter).catch(() => [])) {
|
|
111
|
+
const source = join(sourceChapter, file)
|
|
112
|
+
const target = join(targetChapter, file)
|
|
113
|
+
const sourceInfo = await stat(source).catch(() => null)
|
|
114
|
+
if (sourceInfo === null || !sourceInfo.isFile()) continue
|
|
115
|
+
const existing = await stat(target).catch(() => null)
|
|
116
|
+
if (existing !== null) {
|
|
117
|
+
// The new folder already has this page: same size means the same bytes,
|
|
118
|
+
// so the legacy copy is only a duplicate; different bytes are kept in the
|
|
119
|
+
// legacy folder for a human to decide (never silently overwrite).
|
|
120
|
+
if (existing.size === sourceInfo.size) {
|
|
121
|
+
await rm(source, { force: true })
|
|
122
|
+
counters.kept += 1
|
|
123
|
+
} else {
|
|
124
|
+
counters.warnings.push(`同名缓存内容不同,已保留旧文件:${target}`)
|
|
125
|
+
}
|
|
126
|
+
continue
|
|
127
|
+
}
|
|
128
|
+
await moveFile(source, target)
|
|
129
|
+
counters.moved += 1
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Move every legacy book cache it can place unambiguously into its library.
|
|
135
|
+
*
|
|
136
|
+
* A book id held by exactly one registered library moves there. An id held by
|
|
137
|
+
* none or by several libraries is left untouched and reported: guessing could
|
|
138
|
+
* hand one library's translation of a book to another.
|
|
139
|
+
*
|
|
140
|
+
* @param {{ dataDir: string, libraries: Array<{ libraryDir: string, fragmentDir?: string, id?: string }> }} options - plugin data folder and registered libraries.
|
|
141
|
+
* @returns {Promise<{ moved: object[], skipped: object[], warnings: string[] }>} what happened.
|
|
142
|
+
*/
|
|
143
|
+
export async function migrateTranslationCache(options) {
|
|
144
|
+
const legacyRoot = legacyTranslationRoot(options.dataDir)
|
|
145
|
+
const legacyBooks = await readdir(legacyRoot).catch(() => [])
|
|
146
|
+
const report = { moved: [], skipped: [], warnings: [] }
|
|
147
|
+
if (legacyBooks.length === 0) return report
|
|
148
|
+
const libraries = (Array.isArray(options.libraries) ? options.libraries : [])
|
|
149
|
+
.filter(library => library !== null && typeof library === 'object' && typeof library.libraryDir === 'string' && library.libraryDir !== '')
|
|
150
|
+
if (libraries.length === 0) {
|
|
151
|
+
report.warnings.push(`旧译文缓存留在 ${legacyRoot}:还没有登记任何书库,无法判断归属`)
|
|
152
|
+
return report
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const owners = new Map()
|
|
156
|
+
for (const library of libraries) {
|
|
157
|
+
for (const id of await bookIdsOf(library)) {
|
|
158
|
+
if (!owners.has(id)) owners.set(id, [])
|
|
159
|
+
owners.get(id).push(library)
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
for (const bookId of legacyBooks) {
|
|
164
|
+
const sourceBook = join(legacyRoot, bookId)
|
|
165
|
+
const sourceInfo = await stat(sourceBook).catch(() => null)
|
|
166
|
+
if (sourceInfo === null || !sourceInfo.isDirectory()) continue
|
|
167
|
+
const candidates = owners.get(bookId) ?? []
|
|
168
|
+
if (candidates.length === 0) {
|
|
169
|
+
report.skipped.push({ book: bookId, reason: '没有书库包含这本书' })
|
|
170
|
+
continue
|
|
171
|
+
}
|
|
172
|
+
if (candidates.length > 1) {
|
|
173
|
+
report.skipped.push({ book: bookId, reason: '多个书库都有同名书,无法判断归属' })
|
|
174
|
+
continue
|
|
175
|
+
}
|
|
176
|
+
const library = candidates[0]
|
|
177
|
+
const targetBook = join(translationRoot(library), bookId)
|
|
178
|
+
const counters = { moved: 0, kept: 0, warnings: [] }
|
|
179
|
+
try {
|
|
180
|
+
await mkdir(targetBook, { recursive: true })
|
|
181
|
+
for (const chapter of await readdir(sourceBook).catch(() => [])) {
|
|
182
|
+
const sourceChapter = join(sourceBook, chapter)
|
|
183
|
+
const chapterInfo = await stat(sourceChapter).catch(() => null)
|
|
184
|
+
if (chapterInfo === null || !chapterInfo.isDirectory()) continue
|
|
185
|
+
await mergeChapter(sourceChapter, join(targetBook, chapter), counters)
|
|
186
|
+
const left = await readdir(sourceChapter).catch(() => [])
|
|
187
|
+
if (left.length === 0) await rm(sourceChapter, { recursive: true, force: true })
|
|
188
|
+
}
|
|
189
|
+
await writeFile(join(targetBook, MIGRATION_MARKER), `${JSON.stringify({
|
|
190
|
+
at: Date.now(),
|
|
191
|
+
from: legacyRoot,
|
|
192
|
+
moved: counters.moved,
|
|
193
|
+
duplicates: counters.kept,
|
|
194
|
+
warnings: counters.warnings.length,
|
|
195
|
+
}, null, 2)}\n`, 'utf8')
|
|
196
|
+
const remaining = await readdir(sourceBook).catch(() => [])
|
|
197
|
+
if (remaining.length === 0) await rm(sourceBook, { recursive: true, force: true })
|
|
198
|
+
report.moved.push({ book: bookId, libraryDir: library.libraryDir, files: counters.moved, duplicates: counters.kept })
|
|
199
|
+
report.warnings.push(...counters.warnings)
|
|
200
|
+
} catch (error) {
|
|
201
|
+
report.warnings.push(`迁移《${bookId}》失败,旧缓存保留:${String(error && error.message ? error.message : error)}`)
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const leftBooks = await readdir(legacyRoot).catch(() => [])
|
|
206
|
+
if (leftBooks.length === 0) await rm(legacyRoot, { recursive: true, force: true })
|
|
207
|
+
else report.warnings.push(`旧译文缓存目录仍有未迁移内容:${legacyRoot}`)
|
|
208
|
+
return report
|
|
209
|
+
}
|