dsh-bilingual-reader 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.en.md +146 -0
- package/README.md +145 -2
- package/client/client.js +88 -0
- package/cordis.patch.yml +7 -0
- package/docs/architecture.md +66 -0
- package/docs/demo.jpg +0 -0
- package/docs/release-v0.1.0.md +47 -0
- package/docs/release-v0.1.1.md +31 -0
- package/index.js +82 -0
- package/package.json +76 -4
- package/src/cache.js +76 -0
- package/src/client.js +59 -0
- package/src/config.js +74 -0
- package/src/extract.js +259 -0
- package/src/fetch.js +183 -0
- package/src/glossary.js +74 -0
- package/src/prompt.js +125 -0
- package/src/protect.js +71 -0
- package/src/routes.js +317 -0
- package/src/security.js +169 -0
- package/src/segment.js +116 -0
- package/src/store.js +325 -0
- package/src/tools.js +220 -0
- package/src/translator.js +357 -0
- package/src/util.js +62 -0
- package/web/app.js +477 -0
- package/web/favicon.svg +5 -0
- package/web/index.html +99 -0
- package/web/style.css +488 -0
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import { buildBatchPrompt, chunkBlocks, parseBatchResponse, selectGlossary } from './prompt.js'
|
|
2
|
+
import { protectInline } from './protect.js'
|
|
3
|
+
import { segmentMarkdown } from './segment.js'
|
|
4
|
+
|
|
5
|
+
function failureText(failure) {
|
|
6
|
+
if (failure === undefined || failure === null) return 'unknown'
|
|
7
|
+
if (typeof failure === 'string') return failure
|
|
8
|
+
if (typeof failure.code === 'string') return failure.code
|
|
9
|
+
if (typeof failure.kind === 'string') return failure.kind
|
|
10
|
+
if (typeof failure.message === 'string') return failure.message
|
|
11
|
+
return 'unknown'
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function optionalService(ctx, name) {
|
|
15
|
+
try {
|
|
16
|
+
if (typeof ctx.get === 'function') return ctx.get(name)
|
|
17
|
+
return ctx[name]
|
|
18
|
+
} catch {
|
|
19
|
+
return undefined
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Build a one-shot completion function from the DSH services. Returns null when
|
|
25
|
+
* the profile has no LLM or default-model service, so the plugin still mounts
|
|
26
|
+
* without AI and the UI can explain what is missing.
|
|
27
|
+
*/
|
|
28
|
+
export function createCompletion(ctx) {
|
|
29
|
+
const llm = optionalService(ctx, 'llm')
|
|
30
|
+
const defaultModel = optionalService(ctx, 'agentDefaultModel')
|
|
31
|
+
if (llm === undefined || llm === null || typeof llm.stream !== 'function') return null
|
|
32
|
+
if (defaultModel === undefined || defaultModel === null || typeof defaultModel.currentSelection !== 'function') {
|
|
33
|
+
return null
|
|
34
|
+
}
|
|
35
|
+
try {
|
|
36
|
+
const selection = defaultModel.currentSelection()
|
|
37
|
+
if (selection === null || selection === undefined || !selection.provider || !selection.model) return null
|
|
38
|
+
} catch {
|
|
39
|
+
return null
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return async (prompt, options = {}) => {
|
|
43
|
+
let selection
|
|
44
|
+
try {
|
|
45
|
+
selection = defaultModel.currentSelection()
|
|
46
|
+
} catch (error) {
|
|
47
|
+
throw new Error(`没有可用的默认模型:${error instanceof Error ? error.message : String(error)}`)
|
|
48
|
+
}
|
|
49
|
+
if (selection === null || selection === undefined || !selection.provider || !selection.model) {
|
|
50
|
+
throw new Error('没有可用的默认模型')
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
let text = ''
|
|
54
|
+
let failure = null
|
|
55
|
+
let stream
|
|
56
|
+
try {
|
|
57
|
+
stream = llm.stream({
|
|
58
|
+
provider: selection.provider,
|
|
59
|
+
model: selection.model,
|
|
60
|
+
...(options.system === undefined ? {} : { system: options.system }),
|
|
61
|
+
messages: [{
|
|
62
|
+
role: 'user',
|
|
63
|
+
content: [{ type: 'text', text: String(prompt) }],
|
|
64
|
+
}],
|
|
65
|
+
maxTokens: options.maxTokens ?? 2_000,
|
|
66
|
+
temperature: options.temperature ?? 0.1,
|
|
67
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
68
|
+
})
|
|
69
|
+
for await (const chunk of stream) {
|
|
70
|
+
if (chunk.type === 'text-delta') text += chunk.text
|
|
71
|
+
if (chunk.type === 'finish') {
|
|
72
|
+
if (chunk.reason?.kind === 'error' || chunk.reason?.kind === 'aborted') {
|
|
73
|
+
failure = chunk.reason.failure ?? chunk.reason
|
|
74
|
+
}
|
|
75
|
+
break
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
} catch (error) {
|
|
79
|
+
if (error?.name === 'AbortError') throw new Error('模型调用已取消')
|
|
80
|
+
throw new Error(`模型调用失败:${failureText(error)}`)
|
|
81
|
+
}
|
|
82
|
+
if (failure !== null) throw new Error(`模型调用失败:${failureText(failure)}`)
|
|
83
|
+
if (text.trim() === '') throw new Error('模型没有返回内容')
|
|
84
|
+
return { text: text.trim(), provider: selection.provider, model: selection.model }
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function headingPrefix(text) {
|
|
89
|
+
const match = /^(#{1,6})\s+/.exec(String(text ?? ''))
|
|
90
|
+
return match === null ? '' : `${match[1]} `
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function ensureHeadingPrefix(original, translation) {
|
|
94
|
+
const prefix = headingPrefix(original)
|
|
95
|
+
if (prefix === '') return translation
|
|
96
|
+
const trimmed = String(translation ?? '').trim()
|
|
97
|
+
if (trimmed.startsWith(prefix)) return trimmed
|
|
98
|
+
return `${prefix}${trimmed.replace(/^#{1,6}\s+/, '')}`
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function estimateMaxTokens(chars) {
|
|
102
|
+
return Math.min(8_000, Math.max(1_024, Math.ceil(chars * 1.6)))
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function snippet(text, max = 180) {
|
|
106
|
+
const value = String(text ?? '').replace(/\s+/g, ' ').trim()
|
|
107
|
+
return value.length > max ? value.slice(0, max) : value
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export class Translator {
|
|
111
|
+
constructor({ config, cache, glossary, complete = null }) {
|
|
112
|
+
this.config = config
|
|
113
|
+
this.cache = cache
|
|
114
|
+
this.glossary = glossary
|
|
115
|
+
this.complete = complete
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
get enabled() {
|
|
119
|
+
return typeof this.complete === 'function'
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
contextFor(doc, blocks) {
|
|
123
|
+
const first = blocks[0]
|
|
124
|
+
const last = blocks[blocks.length - 1]
|
|
125
|
+
const firstIndex = first === undefined ? -1 : doc.blocks.findIndex(block => block.id === first.id)
|
|
126
|
+
const lastIndex = last === undefined ? -1 : doc.blocks.findIndex(block => block.id === last.id)
|
|
127
|
+
const before = firstIndex > 0 ? doc.blocks[firstIndex - 1]?.original : ''
|
|
128
|
+
const after = lastIndex >= 0 && lastIndex < doc.blocks.length - 1 ? doc.blocks[lastIndex + 1]?.original : ''
|
|
129
|
+
return {
|
|
130
|
+
title: doc.title ?? '',
|
|
131
|
+
before: snippet(before),
|
|
132
|
+
after: snippet(after),
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
refreshStats(doc) {
|
|
137
|
+
const translatable = doc.blocks.filter(block => block.translatable)
|
|
138
|
+
const done = translatable.filter(block => block.status === 'done' || block.status === 'cached').length
|
|
139
|
+
const cached = translatable.filter(block => block.status === 'cached').length
|
|
140
|
+
const failed = translatable.filter(block => block.status === 'failed').length
|
|
141
|
+
const pending = translatable.filter(block => block.status === 'pending').length
|
|
142
|
+
doc.stats = {
|
|
143
|
+
...(doc.stats ?? {}),
|
|
144
|
+
blocks: doc.blocks.length,
|
|
145
|
+
translatable: translatable.length,
|
|
146
|
+
done,
|
|
147
|
+
cached,
|
|
148
|
+
failed,
|
|
149
|
+
pending,
|
|
150
|
+
chars: translatable.reduce((sum, block) => sum + block.original.length, 0),
|
|
151
|
+
translatedChars: translatable.reduce((sum, block) => sum + (block.translation?.length ?? 0), 0),
|
|
152
|
+
}
|
|
153
|
+
doc.progress = translatable.length === 0 ? 1 : done / translatable.length
|
|
154
|
+
return doc
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async translateDoc(doc, options = {}) {
|
|
158
|
+
if (!this.enabled) {
|
|
159
|
+
doc.status = 'failed'
|
|
160
|
+
doc.error = '没有可用的默认模型;请先在 DSH 里配置模型或登录'
|
|
161
|
+
return doc
|
|
162
|
+
}
|
|
163
|
+
doc.status = 'running'
|
|
164
|
+
doc.error = ''
|
|
165
|
+
doc.stats = { requests: 0, cacheHits: 0, ...(doc.stats ?? {}) }
|
|
166
|
+
|
|
167
|
+
const translatable = doc.blocks.filter(block => block.translatable)
|
|
168
|
+
const misses = []
|
|
169
|
+
const glossaryTerms = this.glossary.list()
|
|
170
|
+
const glossaryHash = this.glossary.hash()
|
|
171
|
+
|
|
172
|
+
for (const block of translatable) {
|
|
173
|
+
if (block.status === 'done' || block.status === 'cached') continue
|
|
174
|
+
const key = this.cache.key(block.original, doc.targetLang, glossaryHash)
|
|
175
|
+
const hit = this.cache.get(key)
|
|
176
|
+
if (hit !== null) {
|
|
177
|
+
block.translation = hit
|
|
178
|
+
block.status = 'cached'
|
|
179
|
+
block.error = ''
|
|
180
|
+
doc.stats.cacheHits += 1
|
|
181
|
+
continue
|
|
182
|
+
}
|
|
183
|
+
block.status = 'pending'
|
|
184
|
+
block.error = ''
|
|
185
|
+
misses.push(block)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
this.refreshStats(doc)
|
|
189
|
+
await options.onProgress?.(doc)
|
|
190
|
+
|
|
191
|
+
const batches = chunkBlocks(misses, {
|
|
192
|
+
maxBlocks: this.config.batchBlocks,
|
|
193
|
+
maxChars: this.config.batchChars,
|
|
194
|
+
})
|
|
195
|
+
const concurrency = Math.min(4, Math.max(1, Number(this.config.concurrency) || 1))
|
|
196
|
+
let nextBatch = 0
|
|
197
|
+
const worker = async () => {
|
|
198
|
+
while (true) {
|
|
199
|
+
if (options.signal?.aborted) throw new Error('翻译已取消')
|
|
200
|
+
const index = nextBatch
|
|
201
|
+
nextBatch += 1
|
|
202
|
+
if (index >= batches.length) return
|
|
203
|
+
await this.translateBatch(doc, batches[index], { glossaryTerms, glossaryHash, signal: options.signal })
|
|
204
|
+
this.refreshStats(doc)
|
|
205
|
+
await options.onProgress?.(doc)
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const settled = await Promise.allSettled(
|
|
209
|
+
Array.from({ length: Math.min(concurrency, batches.length) }, () => worker()),
|
|
210
|
+
)
|
|
211
|
+
const failure = settled.find(result => result.status === 'rejected')
|
|
212
|
+
if (failure !== undefined) throw failure.reason
|
|
213
|
+
|
|
214
|
+
this.refreshStats(doc)
|
|
215
|
+
if (doc.stats.translatable === 0) doc.status = 'done'
|
|
216
|
+
else if (doc.stats.failed > 0) doc.status = doc.stats.done > 0 ? 'partial' : 'failed'
|
|
217
|
+
else doc.status = 'done'
|
|
218
|
+
if (doc.stats.failed > 0) {
|
|
219
|
+
doc.error = `${doc.stats.failed} 个段落翻译失败,可在界面里重试`
|
|
220
|
+
}
|
|
221
|
+
await this.cache.flush()
|
|
222
|
+
return doc
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
async translateBatch(doc, blocks, context = {}) {
|
|
226
|
+
const protectedBlocks = blocks.map(block => ({ block, protection: protectInline(block.original) }))
|
|
227
|
+
const batchText = protectedBlocks.map(item => item.protection.text).join('\n')
|
|
228
|
+
const terms = selectGlossary(context.glossaryTerms ?? [], batchText)
|
|
229
|
+
const prompt = buildBatchPrompt({
|
|
230
|
+
blocks: protectedBlocks.map(item => ({ text: item.protection.text })),
|
|
231
|
+
targetLang: doc.targetLang,
|
|
232
|
+
glossary: terms,
|
|
233
|
+
context: this.contextFor(doc, blocks),
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
let translations = null
|
|
237
|
+
try {
|
|
238
|
+
doc.stats.requests += 1
|
|
239
|
+
const result = await this.complete(prompt.user, {
|
|
240
|
+
system: prompt.system,
|
|
241
|
+
maxTokens: estimateMaxTokens(batchText.length),
|
|
242
|
+
signal: context.signal,
|
|
243
|
+
})
|
|
244
|
+
translations = parseBatchResponse(result.text, protectedBlocks.length)
|
|
245
|
+
} catch (error) {
|
|
246
|
+
if (context.signal?.aborted) throw error
|
|
247
|
+
translations = null
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
if (translations === null) {
|
|
251
|
+
for (const item of protectedBlocks) {
|
|
252
|
+
await this.translateSingle(doc, item, context)
|
|
253
|
+
}
|
|
254
|
+
return
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
for (let index = 0; index < protectedBlocks.length; index += 1) {
|
|
258
|
+
const item = protectedBlocks[index]
|
|
259
|
+
const value = translations[index]
|
|
260
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
261
|
+
await this.translateSingle(doc, item, context)
|
|
262
|
+
continue
|
|
263
|
+
}
|
|
264
|
+
let restored = item.protection.restore(value)
|
|
265
|
+
if (restored.missing.length > 0) {
|
|
266
|
+
const retried = await this.translateSingle(doc, item, context, { retryOnly: true })
|
|
267
|
+
if (retried) continue
|
|
268
|
+
restored = item.protection.restore(value)
|
|
269
|
+
this.finishBlock(
|
|
270
|
+
doc,
|
|
271
|
+
item.block,
|
|
272
|
+
restored.text,
|
|
273
|
+
context.glossaryHash,
|
|
274
|
+
`模型丢失了保护片段:${restored.missing.length}`,
|
|
275
|
+
)
|
|
276
|
+
continue
|
|
277
|
+
}
|
|
278
|
+
this.finishBlock(doc, item.block, restored.text, context.glossaryHash)
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async translateSingle(doc, item, context = {}, options = {}) {
|
|
283
|
+
const prompt = buildBatchPrompt({
|
|
284
|
+
blocks: [{ text: item.protection.text }],
|
|
285
|
+
targetLang: doc.targetLang,
|
|
286
|
+
glossary: selectGlossary(context.glossaryTerms ?? [], item.protection.text),
|
|
287
|
+
context: this.contextFor(doc, [item.block]),
|
|
288
|
+
})
|
|
289
|
+
try {
|
|
290
|
+
doc.stats.requests += 1
|
|
291
|
+
const result = await this.complete(prompt.user, {
|
|
292
|
+
system: prompt.system,
|
|
293
|
+
maxTokens: estimateMaxTokens(item.protection.text.length),
|
|
294
|
+
signal: context.signal,
|
|
295
|
+
})
|
|
296
|
+
const values = parseBatchResponse(result.text, 1)
|
|
297
|
+
const restored = item.protection.restore(values[0] ?? '')
|
|
298
|
+
if (restored.text.trim() === '') throw new Error('译文为空')
|
|
299
|
+
this.finishBlock(
|
|
300
|
+
doc,
|
|
301
|
+
item.block,
|
|
302
|
+
restored.text,
|
|
303
|
+
context.glossaryHash,
|
|
304
|
+
restored.missing.length > 0 ? `模型丢失了保护片段:${restored.missing.length}` : '',
|
|
305
|
+
)
|
|
306
|
+
return true
|
|
307
|
+
} catch (error) {
|
|
308
|
+
if (options.retryOnly) return false
|
|
309
|
+
item.block.status = 'failed'
|
|
310
|
+
item.block.error = error instanceof Error ? error.message : String(error)
|
|
311
|
+
return false
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
finishBlock(doc, block, translation, glossaryHash = this.glossary.hash(), warning = '') {
|
|
316
|
+
const text = ensureHeadingPrefix(block.original, translation).trim()
|
|
317
|
+
if (text === '') {
|
|
318
|
+
block.status = 'failed'
|
|
319
|
+
block.error = '译文为空'
|
|
320
|
+
return
|
|
321
|
+
}
|
|
322
|
+
block.translation = text
|
|
323
|
+
block.status = 'done'
|
|
324
|
+
block.error = ''
|
|
325
|
+
block.warning = warning
|
|
326
|
+
const key = this.cache.key(block.original, doc.targetLang, glossaryHash)
|
|
327
|
+
this.cache.set(key, text)
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
async translateText(text, options = {}) {
|
|
331
|
+
const targetLang = options.targetLang ?? this.config.targetLang
|
|
332
|
+
const { blocks } = segmentMarkdown(String(text ?? ''), { maxBlocks: this.config.maxBlocks })
|
|
333
|
+
const doc = {
|
|
334
|
+
id: 'adhoc',
|
|
335
|
+
title: options.title ?? '',
|
|
336
|
+
url: '',
|
|
337
|
+
targetLang,
|
|
338
|
+
createdAt: new Date().toISOString(),
|
|
339
|
+
status: 'pending',
|
|
340
|
+
error: '',
|
|
341
|
+
blocks: blocks.map((block, index) => ({
|
|
342
|
+
id: index,
|
|
343
|
+
type: block.type,
|
|
344
|
+
original: block.original,
|
|
345
|
+
translatable: block.translatable,
|
|
346
|
+
translation: '',
|
|
347
|
+
status: block.translatable ? 'pending' : 'skipped',
|
|
348
|
+
warning: '',
|
|
349
|
+
error: '',
|
|
350
|
+
})),
|
|
351
|
+
stats: { requests: 0, cacheHits: 0 },
|
|
352
|
+
progress: 0,
|
|
353
|
+
}
|
|
354
|
+
await this.translateDoc(doc, { signal: options.signal })
|
|
355
|
+
return doc
|
|
356
|
+
}
|
|
357
|
+
}
|
package/src/util.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import fs from 'node:fs/promises'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
|
|
5
|
+
export function sha256(text) {
|
|
6
|
+
return createHash('sha256').update(String(text), 'utf8').digest('hex')
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function clampText(value, maxLength) {
|
|
10
|
+
const text = String(value ?? '').replace(/\s+/g, ' ').trim()
|
|
11
|
+
return text.length > maxLength ? text.slice(0, maxLength) : text
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export async function readJson(file, fallback) {
|
|
15
|
+
try {
|
|
16
|
+
return JSON.parse(await fs.readFile(file, 'utf8'))
|
|
17
|
+
} catch {
|
|
18
|
+
return fallback
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Replace a file with a temp file. On Windows, renaming over a file that a
|
|
24
|
+
* reader currently has open can fail with EPERM/EBUSY; retry briefly and fall
|
|
25
|
+
* back to an in-place write so a UI poll cannot make the translation job fail.
|
|
26
|
+
*/
|
|
27
|
+
async function replaceFile(temp, file, content) {
|
|
28
|
+
for (let attempt = 0; attempt < 6; attempt += 1) {
|
|
29
|
+
try {
|
|
30
|
+
await fs.rename(temp, file)
|
|
31
|
+
return
|
|
32
|
+
} catch (error) {
|
|
33
|
+
if (!['EPERM', 'EBUSY', 'EACCES'].includes(error.code)) throw error
|
|
34
|
+
if (attempt === 5) {
|
|
35
|
+
await fs.writeFile(file, content, 'utf8')
|
|
36
|
+
await fs.rm(temp, { force: true })
|
|
37
|
+
return
|
|
38
|
+
}
|
|
39
|
+
await new Promise(resolve => setTimeout(resolve, 25 * (attempt + 1)))
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function writeJsonAtomic(file, value) {
|
|
45
|
+
await fs.mkdir(path.dirname(file), { recursive: true })
|
|
46
|
+
const content = `${JSON.stringify(value, null, 2)}\n`
|
|
47
|
+
const temp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
|
|
48
|
+
await fs.writeFile(temp, content, 'utf8')
|
|
49
|
+
await replaceFile(temp, file, content)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function writeTextAtomic(file, text) {
|
|
53
|
+
await fs.mkdir(path.dirname(file), { recursive: true })
|
|
54
|
+
const content = String(text ?? '')
|
|
55
|
+
const temp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
|
|
56
|
+
await fs.writeFile(temp, content, 'utf8')
|
|
57
|
+
await replaceFile(temp, file, content)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function nowIso() {
|
|
61
|
+
return new Date().toISOString()
|
|
62
|
+
}
|