dsh-bilingual-reader 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.en.md +138 -0
- package/README.md +137 -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/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 +73 -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 +316 -0
- package/src/tools.js +220 -0
- package/src/translator.js +335 -0
- package/src/util.js +62 -0
- package/web/app.js +400 -0
- package/web/favicon.svg +5 -0
- package/web/index.html +98 -0
- package/web/style.css +475 -0
package/src/tools.js
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { TARGET_LANGUAGES, targetLanguageName } from './config.js'
|
|
2
|
+
import { bilingualMarkdown, translationMarkdown } from './segment.js'
|
|
3
|
+
|
|
4
|
+
const LANG_ENUM = TARGET_LANGUAGES.map(item => item.code)
|
|
5
|
+
|
|
6
|
+
const OUTPUT = {
|
|
7
|
+
schema: {
|
|
8
|
+
type: 'object',
|
|
9
|
+
additionalProperties: true,
|
|
10
|
+
properties: { text: { type: 'string' } },
|
|
11
|
+
required: ['text'],
|
|
12
|
+
},
|
|
13
|
+
render: (_args, value) => [{ type: 'text', text: String(value?.text ?? '') }],
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function statusLabel(status) {
|
|
17
|
+
return {
|
|
18
|
+
pending: '待翻译',
|
|
19
|
+
running: '翻译中',
|
|
20
|
+
done: '已完成',
|
|
21
|
+
partial: '部分完成',
|
|
22
|
+
failed: '失败',
|
|
23
|
+
interrupted: '已中断',
|
|
24
|
+
}[status] ?? status
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function docSummary(doc) {
|
|
28
|
+
const stats = doc.stats ?? {}
|
|
29
|
+
const lines = [
|
|
30
|
+
`《${doc.title}》`,
|
|
31
|
+
`id: ${doc.id}`,
|
|
32
|
+
doc.url ? `url: ${doc.url}` : '来源:本地文本',
|
|
33
|
+
`目标语言:${targetLanguageName(doc.targetLang)}`,
|
|
34
|
+
`状态:${statusLabel(doc.status)}(${Math.round((doc.progress ?? 0) * 100)}%)`,
|
|
35
|
+
`段落:${stats.done ?? 0}/${stats.translatable ?? 0},缓存命中 ${stats.cached ?? 0},失败 ${stats.failed ?? 0},请求 ${stats.requests ?? 0}`,
|
|
36
|
+
]
|
|
37
|
+
if (doc.error) lines.push(`错误:${doc.error}`)
|
|
38
|
+
if (doc.status === 'running') lines.push('翻译仍在后台进行,可稍后用 bilingual_status 查看。')
|
|
39
|
+
return lines.join('\n')
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function previewBlocks(doc, limit = 6) {
|
|
43
|
+
const blocks = doc.blocks
|
|
44
|
+
.filter(block => block.translatable && block.translation)
|
|
45
|
+
.slice(0, limit)
|
|
46
|
+
if (blocks.length === 0) return ''
|
|
47
|
+
return blocks
|
|
48
|
+
.map(block => `原文:${block.original}\n译文:${block.translation}`)
|
|
49
|
+
.join('\n\n')
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function registerTools(ctx, { store }) {
|
|
53
|
+
ctx.tools.register({
|
|
54
|
+
name: 'bilingual_read_url',
|
|
55
|
+
description:
|
|
56
|
+
'抓取一个公开网页,提取正文,按段落翻译成目标语言,并保存为双语阅读文档。' +
|
|
57
|
+
'当用户要求“翻译这篇文章 / 双语阅读这个链接 / 读懂这个页面”时使用。' +
|
|
58
|
+
'默认等待翻译完成(最多约 2 分钟);长文章可传 wait=false,再用 bilingual_status 查询。' +
|
|
59
|
+
'只能访问 http/https 公开页面,内网和本机地址会被拒绝。',
|
|
60
|
+
parameters: {
|
|
61
|
+
type: 'object',
|
|
62
|
+
additionalProperties: false,
|
|
63
|
+
properties: {
|
|
64
|
+
url: { type: 'string', description: '要阅读和翻译的 http/https URL。' },
|
|
65
|
+
targetLang: {
|
|
66
|
+
type: 'string',
|
|
67
|
+
enum: LANG_ENUM,
|
|
68
|
+
description: '目标语言,默认使用插件配置(通常是 zh-CN)。',
|
|
69
|
+
},
|
|
70
|
+
wait: {
|
|
71
|
+
type: 'boolean',
|
|
72
|
+
description: '是否等待翻译完成;默认 true。长文章可以设 false 后轮询。',
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
required: ['url'],
|
|
76
|
+
},
|
|
77
|
+
output: OUTPUT,
|
|
78
|
+
timeoutMs: 150_000,
|
|
79
|
+
isConcurrencySafe: () => false,
|
|
80
|
+
async execute(args, exec) {
|
|
81
|
+
if (args === null || typeof args !== 'object' || typeof args.url !== 'string' || args.url.trim() === '') {
|
|
82
|
+
throw new Error('bilingual_read_url 需要非空的 url')
|
|
83
|
+
}
|
|
84
|
+
const doc = await store.createDocFromUrl(args.url.trim(), {
|
|
85
|
+
targetLang: args.targetLang,
|
|
86
|
+
signal: exec.signal,
|
|
87
|
+
})
|
|
88
|
+
await store.startJob(doc)
|
|
89
|
+
const current = args.wait === false
|
|
90
|
+
? doc
|
|
91
|
+
: await store.waitForJob(doc.id, { timeoutMs: 115_000 })
|
|
92
|
+
const lines = [docSummary(current)]
|
|
93
|
+
const preview = previewBlocks(current)
|
|
94
|
+
if (preview !== '') lines.push('', preview)
|
|
95
|
+
if (current.status === 'done' || current.status === 'partial') {
|
|
96
|
+
lines.push('', `可在侧栏“双语阅读”里打开对照视图,或导出双语 Markdown。`)
|
|
97
|
+
}
|
|
98
|
+
return { text: lines.join('\n') }
|
|
99
|
+
},
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
ctx.tools.register({
|
|
103
|
+
name: 'bilingual_translate',
|
|
104
|
+
description:
|
|
105
|
+
'把一段 Markdown 或纯文本翻译成目标语言,保留代码、链接、公式、表格和标题结构。' +
|
|
106
|
+
'适合用户粘贴一段文字要求翻译;不需要保存为文档。结果会被缓存,重复内容不会再次调用模型。',
|
|
107
|
+
parameters: {
|
|
108
|
+
type: 'object',
|
|
109
|
+
additionalProperties: false,
|
|
110
|
+
properties: {
|
|
111
|
+
text: { type: 'string', description: '要翻译的文本,支持 Markdown。' },
|
|
112
|
+
targetLang: {
|
|
113
|
+
type: 'string',
|
|
114
|
+
enum: LANG_ENUM,
|
|
115
|
+
description: '目标语言,默认使用插件配置。',
|
|
116
|
+
},
|
|
117
|
+
bilingual: {
|
|
118
|
+
type: 'boolean',
|
|
119
|
+
description: '为 true 时返回原文 + 译文对照,否则只返回译文。',
|
|
120
|
+
},
|
|
121
|
+
},
|
|
122
|
+
required: ['text'],
|
|
123
|
+
},
|
|
124
|
+
output: OUTPUT,
|
|
125
|
+
timeoutMs: 120_000,
|
|
126
|
+
isConcurrencySafe: () => false,
|
|
127
|
+
async execute(args, exec) {
|
|
128
|
+
if (args === null || typeof args !== 'object' || typeof args.text !== 'string' || args.text.trim() === '') {
|
|
129
|
+
throw new Error('bilingual_translate 需要非空的 text')
|
|
130
|
+
}
|
|
131
|
+
const doc = await store.translateText(args.text, {
|
|
132
|
+
targetLang: args.targetLang,
|
|
133
|
+
signal: exec.signal,
|
|
134
|
+
})
|
|
135
|
+
const body = args.bilingual === true
|
|
136
|
+
? bilingualMarkdown(doc.blocks)
|
|
137
|
+
: translationMarkdown(doc.blocks)
|
|
138
|
+
return {
|
|
139
|
+
text: [
|
|
140
|
+
`目标语言:${targetLanguageName(doc.targetLang)}`,
|
|
141
|
+
`段落:${doc.stats?.done ?? 0}/${doc.stats?.translatable ?? 0},缓存命中 ${doc.stats?.cached ?? 0},失败 ${doc.stats?.failed ?? 0}`,
|
|
142
|
+
'',
|
|
143
|
+
body,
|
|
144
|
+
].join('\n'),
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
ctx.tools.register({
|
|
150
|
+
name: 'bilingual_status',
|
|
151
|
+
description:
|
|
152
|
+
'查看一个双语阅读文档的翻译进度、失败段落和部分译文。' +
|
|
153
|
+
'当 bilingual_read_url 返回“翻译仍在后台进行”或用户问“翻译好了吗”时使用。',
|
|
154
|
+
parameters: {
|
|
155
|
+
type: 'object',
|
|
156
|
+
additionalProperties: false,
|
|
157
|
+
properties: {
|
|
158
|
+
id: { type: 'string', description: 'bilingual_read_url 返回的文档 id。' },
|
|
159
|
+
includeTranslations: {
|
|
160
|
+
type: 'boolean',
|
|
161
|
+
description: '为 true 时附带前 20 个已完成段落的原文和译文。',
|
|
162
|
+
},
|
|
163
|
+
},
|
|
164
|
+
required: ['id'],
|
|
165
|
+
},
|
|
166
|
+
output: OUTPUT,
|
|
167
|
+
timeoutMs: 30_000,
|
|
168
|
+
isConcurrencySafe: () => true,
|
|
169
|
+
async execute(args) {
|
|
170
|
+
await store.ready()
|
|
171
|
+
const doc = await store.getDoc(args?.id)
|
|
172
|
+
if (doc === null) throw new Error(`找不到文档:${args?.id}`)
|
|
173
|
+
const lines = [docSummary(doc)]
|
|
174
|
+
if (args.includeTranslations === true) {
|
|
175
|
+
const preview = previewBlocks(doc, 20)
|
|
176
|
+
if (preview !== '') lines.push('', preview)
|
|
177
|
+
}
|
|
178
|
+
return { text: lines.join('\n') }
|
|
179
|
+
},
|
|
180
|
+
})
|
|
181
|
+
|
|
182
|
+
ctx.tools.register({
|
|
183
|
+
name: 'bilingual_glossary',
|
|
184
|
+
description:
|
|
185
|
+
'管理双语阅读的术语表。翻译时会强制使用术语表里的译法。' +
|
|
186
|
+
'action=list 查看;action=add 添加或更新(需要 source 和 target);action=remove 删除(需要 source)。',
|
|
187
|
+
parameters: {
|
|
188
|
+
type: 'object',
|
|
189
|
+
additionalProperties: false,
|
|
190
|
+
properties: {
|
|
191
|
+
action: { type: 'string', enum: ['list', 'add', 'remove'] },
|
|
192
|
+
source: { type: 'string', description: '原文术语,例如 token。' },
|
|
193
|
+
target: { type: 'string', description: '目标语言术语,例如 令牌。' },
|
|
194
|
+
note: { type: 'string', description: '可选备注。' },
|
|
195
|
+
},
|
|
196
|
+
required: ['action'],
|
|
197
|
+
},
|
|
198
|
+
output: OUTPUT,
|
|
199
|
+
timeoutMs: 30_000,
|
|
200
|
+
isConcurrencySafe: () => false,
|
|
201
|
+
async execute(args) {
|
|
202
|
+
await store.ready()
|
|
203
|
+
const action = args?.action
|
|
204
|
+
if (action === 'add') {
|
|
205
|
+
store.glossary.add(args.source, args.target, args.note)
|
|
206
|
+
await store.glossary.flush()
|
|
207
|
+
} else if (action === 'remove') {
|
|
208
|
+
store.glossary.remove(args.source)
|
|
209
|
+
await store.glossary.flush()
|
|
210
|
+
} else if (action !== 'list') {
|
|
211
|
+
throw new Error('action 只支持 list / add / remove')
|
|
212
|
+
}
|
|
213
|
+
const terms = store.glossary.list()
|
|
214
|
+
const lines = terms.length === 0
|
|
215
|
+
? ['术语表为空。']
|
|
216
|
+
: terms.map(term => `${term.source} => ${term.target}${term.note ? `(${term.note})` : ''}`)
|
|
217
|
+
return { text: lines.join('\n') }
|
|
218
|
+
},
|
|
219
|
+
})
|
|
220
|
+
}
|
|
@@ -0,0 +1,335 @@
|
|
|
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
|
+
|
|
196
|
+
for (const batch of batches) {
|
|
197
|
+
if (options.signal?.aborted) throw new Error('翻译已取消')
|
|
198
|
+
await this.translateBatch(doc, batch, { glossaryTerms, glossaryHash, signal: options.signal })
|
|
199
|
+
this.refreshStats(doc)
|
|
200
|
+
await options.onProgress?.(doc)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
this.refreshStats(doc)
|
|
204
|
+
if (doc.stats.translatable === 0) doc.status = 'done'
|
|
205
|
+
else if (doc.stats.failed > 0) doc.status = doc.stats.done > 0 ? 'partial' : 'failed'
|
|
206
|
+
else doc.status = 'done'
|
|
207
|
+
if (doc.stats.failed > 0) {
|
|
208
|
+
doc.error = `${doc.stats.failed} 个段落翻译失败,可在界面里重试`
|
|
209
|
+
}
|
|
210
|
+
await this.cache.flush()
|
|
211
|
+
return doc
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async translateBatch(doc, blocks, context = {}) {
|
|
215
|
+
const protectedBlocks = blocks.map(block => ({ block, protection: protectInline(block.original) }))
|
|
216
|
+
const batchText = protectedBlocks.map(item => item.protection.text).join('\n')
|
|
217
|
+
const terms = selectGlossary(context.glossaryTerms ?? [], batchText)
|
|
218
|
+
const prompt = buildBatchPrompt({
|
|
219
|
+
blocks: protectedBlocks.map(item => ({ text: item.protection.text })),
|
|
220
|
+
targetLang: doc.targetLang,
|
|
221
|
+
glossary: terms,
|
|
222
|
+
context: this.contextFor(doc, blocks),
|
|
223
|
+
})
|
|
224
|
+
|
|
225
|
+
let translations = null
|
|
226
|
+
try {
|
|
227
|
+
doc.stats.requests += 1
|
|
228
|
+
const result = await this.complete(prompt.user, {
|
|
229
|
+
system: prompt.system,
|
|
230
|
+
maxTokens: estimateMaxTokens(batchText.length),
|
|
231
|
+
signal: context.signal,
|
|
232
|
+
})
|
|
233
|
+
translations = parseBatchResponse(result.text, protectedBlocks.length)
|
|
234
|
+
} catch (error) {
|
|
235
|
+
if (context.signal?.aborted) throw error
|
|
236
|
+
translations = null
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
if (translations === null) {
|
|
240
|
+
for (const item of protectedBlocks) {
|
|
241
|
+
await this.translateSingle(doc, item, context)
|
|
242
|
+
}
|
|
243
|
+
return
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
for (let index = 0; index < protectedBlocks.length; index += 1) {
|
|
247
|
+
const item = protectedBlocks[index]
|
|
248
|
+
const value = translations[index]
|
|
249
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
250
|
+
await this.translateSingle(doc, item, context)
|
|
251
|
+
continue
|
|
252
|
+
}
|
|
253
|
+
let restored = item.protection.restore(value)
|
|
254
|
+
if (restored.missing.length > 0) {
|
|
255
|
+
const retried = await this.translateSingle(doc, item, context, { retryOnly: true })
|
|
256
|
+
if (retried) continue
|
|
257
|
+
restored = item.protection.restore(value)
|
|
258
|
+
item.block.warning = `模型丢失了保护片段:${restored.missing.length}`
|
|
259
|
+
}
|
|
260
|
+
this.finishBlock(doc, item.block, restored.text)
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async translateSingle(doc, item, context = {}, options = {}) {
|
|
265
|
+
const prompt = buildBatchPrompt({
|
|
266
|
+
blocks: [{ text: item.protection.text }],
|
|
267
|
+
targetLang: doc.targetLang,
|
|
268
|
+
glossary: selectGlossary(context.glossaryTerms ?? [], item.protection.text),
|
|
269
|
+
context: this.contextFor(doc, [item.block]),
|
|
270
|
+
})
|
|
271
|
+
try {
|
|
272
|
+
doc.stats.requests += 1
|
|
273
|
+
const result = await this.complete(prompt.user, {
|
|
274
|
+
system: prompt.system,
|
|
275
|
+
maxTokens: estimateMaxTokens(item.protection.text.length),
|
|
276
|
+
signal: context.signal,
|
|
277
|
+
})
|
|
278
|
+
const values = parseBatchResponse(result.text, 1)
|
|
279
|
+
const restored = item.protection.restore(values[0] ?? '')
|
|
280
|
+
if (restored.text.trim() === '') throw new Error('译文为空')
|
|
281
|
+
if (restored.missing.length > 0) {
|
|
282
|
+
item.block.warning = `模型丢失了保护片段:${restored.missing.length}`
|
|
283
|
+
}
|
|
284
|
+
this.finishBlock(doc, item.block, restored.text)
|
|
285
|
+
return true
|
|
286
|
+
} catch (error) {
|
|
287
|
+
if (options.retryOnly) return false
|
|
288
|
+
item.block.status = 'failed'
|
|
289
|
+
item.block.error = error instanceof Error ? error.message : String(error)
|
|
290
|
+
return false
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
finishBlock(doc, block, translation) {
|
|
295
|
+
const text = ensureHeadingPrefix(block.original, translation).trim()
|
|
296
|
+
if (text === '') {
|
|
297
|
+
block.status = 'failed'
|
|
298
|
+
block.error = '译文为空'
|
|
299
|
+
return
|
|
300
|
+
}
|
|
301
|
+
block.translation = text
|
|
302
|
+
block.status = 'done'
|
|
303
|
+
block.error = ''
|
|
304
|
+
const key = this.cache.key(block.original, doc.targetLang, this.glossary.hash())
|
|
305
|
+
this.cache.set(key, text)
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
async translateText(text, options = {}) {
|
|
309
|
+
const targetLang = options.targetLang ?? this.config.targetLang
|
|
310
|
+
const { blocks } = segmentMarkdown(String(text ?? ''), { maxBlocks: this.config.maxBlocks })
|
|
311
|
+
const doc = {
|
|
312
|
+
id: 'adhoc',
|
|
313
|
+
title: options.title ?? '',
|
|
314
|
+
url: '',
|
|
315
|
+
targetLang,
|
|
316
|
+
createdAt: new Date().toISOString(),
|
|
317
|
+
status: 'pending',
|
|
318
|
+
error: '',
|
|
319
|
+
blocks: blocks.map((block, index) => ({
|
|
320
|
+
id: index,
|
|
321
|
+
type: block.type,
|
|
322
|
+
original: block.original,
|
|
323
|
+
translatable: block.translatable,
|
|
324
|
+
translation: '',
|
|
325
|
+
status: block.translatable ? 'pending' : 'skipped',
|
|
326
|
+
warning: '',
|
|
327
|
+
error: '',
|
|
328
|
+
})),
|
|
329
|
+
stats: { requests: 0, cacheHits: 0 },
|
|
330
|
+
progress: 0,
|
|
331
|
+
}
|
|
332
|
+
await this.translateDoc(doc, { signal: options.signal })
|
|
333
|
+
return doc
|
|
334
|
+
}
|
|
335
|
+
}
|
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()}`
|
|
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()}`
|
|
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
|
+
}
|