dsh-bilingual-reader 0.1.0 → 0.2.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/src/routes.js CHANGED
@@ -2,6 +2,7 @@ import { readFile } from 'node:fs/promises'
2
2
  import { join } from 'node:path'
3
3
  import { TARGET_LANGUAGES } from './config.js'
4
4
  import { renderMarkdown } from './extract.js'
5
+ import { sha256 } from './util.js'
5
6
 
6
7
  export const PREFIX = '/dsh-bilingual-reader'
7
8
  const API_PREFIX = `${PREFIX}/api`
@@ -108,11 +109,30 @@ function summarizeDoc(doc) {
108
109
  }
109
110
  }
110
111
 
112
+ const HTML_CACHE_LIMIT = 2000
113
+ const htmlCache = new Map()
114
+
115
+ /**
116
+ * Polling asks for the whole document every tick while translation runs. The
117
+ * same source and translation blocks are rendered again and again; cache the
118
+ * sanitized HTML by content hash so only changed blocks pay for marked +
119
+ * sanitize-html.
120
+ */
121
+ function renderCached(markdown, kind) {
122
+ const key = `${kind}:${sha256(markdown)}`
123
+ const cached = htmlCache.get(key)
124
+ if (cached !== undefined) return cached
125
+ const html = renderMarkdown(markdown)
126
+ if (htmlCache.size >= HTML_CACHE_LIMIT) htmlCache.clear()
127
+ htmlCache.set(key, html)
128
+ return html
129
+ }
130
+
111
131
  function decorateBlocks(blocks) {
112
132
  return blocks.map(block => ({
113
133
  ...block,
114
- originalHtml: renderMarkdown(block.original),
115
- translationHtml: block.translation ? renderMarkdown(block.translation) : '',
134
+ originalHtml: renderCached(block.original, 'original'),
135
+ translationHtml: block.translation ? renderCached(block.translation, 'translation') : '',
116
136
  }))
117
137
  }
118
138
 
@@ -182,6 +202,31 @@ async function handleApi(req, res, url, store) {
182
202
  }
183
203
  }
184
204
 
205
+ if (segments[0] === 'read-text' && segments.length === 1) {
206
+ if (method !== 'POST') return writeError(res, 405, 'method not allowed')
207
+ const body = await readJsonBody(req)
208
+ if (typeof body.text !== 'string' || body.text.trim() === '') {
209
+ return writeError(res, 400, '缺少 text')
210
+ }
211
+ const text = body.text.trim()
212
+ if (text.length > store.config.maxTranslateChars) {
213
+ return writeError(res, 400, `文本超过 ${store.config.maxTranslateChars} 字符上限`)
214
+ }
215
+ const firstLine = text.split(/\r?\n/).map(line => line.replace(/^#{1,6}\s+/, '').trim()).find(Boolean) ?? ''
216
+ try {
217
+ const doc = await store.createDoc({
218
+ markdown: text,
219
+ title: firstLine.slice(0, 120) || '粘贴的文本',
220
+ url: '',
221
+ meta: { siteName: '粘贴文本', charCount: text.length, source: 'paste' },
222
+ }, { targetLang: body.targetLang })
223
+ await store.startJob(doc)
224
+ return writeJson(res, 200, { ok: true, doc: summarizeDoc(doc) })
225
+ } catch (error) {
226
+ return writeError(res, 400, error instanceof Error ? error.message : String(error))
227
+ }
228
+ }
229
+
185
230
  if (segments[0] === 'translate' && segments.length === 1) {
186
231
  if (method !== 'POST') return writeError(res, 405, 'method not allowed')
187
232
  const body = await readJsonBody(req)
@@ -241,6 +286,16 @@ async function handleApi(req, res, url, store) {
241
286
  return writeError(res, 400, error instanceof Error ? error.message : String(error))
242
287
  }
243
288
  }
289
+ if (segments.length === 5 && method === 'POST' && segments[2] === 'blocks' && segments[4] === 'retry') {
290
+ const id = decodeSegment(segments[1])
291
+ const blockId = decodeSegment(segments[3])
292
+ try {
293
+ const doc = await store.retryBlock(id, blockId)
294
+ return writeJson(res, 200, { ok: true, doc: summarizeDoc(doc) })
295
+ } catch (error) {
296
+ return writeError(res, 400, error instanceof Error ? error.message : String(error))
297
+ }
298
+ }
244
299
  if (segments.length === 3 && method === 'GET' && segments[2] === 'export') {
245
300
  const id = decodeSegment(segments[1])
246
301
  try {
@@ -257,22 +312,49 @@ async function handleApi(req, res, url, store) {
257
312
  }
258
313
  }
259
314
 
260
- if (segments[0] === 'glossary' && segments.length === 1) {
261
- if (method === 'GET') {
262
- return writeJson(res, 200, { ok: true, terms: store.glossary.list() })
315
+ if (segments[0] === 'glossary') {
316
+ if (segments.length === 1) {
317
+ if (method === 'GET') {
318
+ return writeJson(res, 200, { ok: true, terms: store.glossary.list() })
319
+ }
320
+ if (method === 'POST') {
321
+ const body = await readJsonBody(req)
322
+ try {
323
+ if (body.action === 'add') {
324
+ store.glossary.add(body.source, body.target, body.note)
325
+ } else if (body.action === 'remove') {
326
+ store.glossary.remove(body.source)
327
+ } else {
328
+ return writeError(res, 400, 'action 只支持 add / remove')
329
+ }
330
+ await store.glossary.flush()
331
+ return writeJson(res, 200, { ok: true, terms: store.glossary.list() })
332
+ } catch (error) {
333
+ return writeError(res, 400, error instanceof Error ? error.message : String(error))
334
+ }
335
+ }
336
+ return writeError(res, 405, 'method not allowed')
263
337
  }
264
- if (method === 'POST') {
338
+ if (segments.length === 2 && segments[1] === 'export' && method === 'GET') {
339
+ res.writeHead(200, {
340
+ ...commonHeaders('application/json; charset=utf-8'),
341
+ 'content-disposition': 'attachment; filename="dsh-bilingual-glossary.json"',
342
+ })
343
+ res.end(`${JSON.stringify({
344
+ version: 1,
345
+ exportedAt: new Date().toISOString(),
346
+ terms: store.glossary.list(),
347
+ }, null, 2)}\n`)
348
+ return
349
+ }
350
+ if (segments.length === 2 && segments[1] === 'import' && method === 'POST') {
265
351
  const body = await readJsonBody(req)
352
+ const terms = Array.isArray(body) ? body : body.terms
353
+ if (!Array.isArray(terms)) return writeError(res, 400, '缺少 terms 数组')
266
354
  try {
267
- if (body.action === 'add') {
268
- store.glossary.add(body.source, body.target, body.note)
269
- } else if (body.action === 'remove') {
270
- store.glossary.remove(body.source)
271
- } else {
272
- return writeError(res, 400, 'action 只支持 add / remove')
273
- }
355
+ const result = store.glossary.importTerms(terms)
274
356
  await store.glossary.flush()
275
- return writeJson(res, 200, { ok: true, terms: store.glossary.list() })
357
+ return writeJson(res, 200, { ok: true, ...result })
276
358
  } catch (error) {
277
359
  return writeError(res, 400, error instanceof Error ? error.message : String(error))
278
360
  }
package/src/store.js CHANGED
@@ -30,6 +30,7 @@ export class BilingualStore {
30
30
  complete,
31
31
  })
32
32
  this.jobs = new Map()
33
+ this.saveQueue = Promise.resolve()
33
34
  this.loaded = false
34
35
  this.readyPromise = null
35
36
  }
@@ -161,9 +162,17 @@ export class BilingualStore {
161
162
  return doc
162
163
  }
163
164
 
164
- async saveDoc(doc) {
165
+ /**
166
+ * Serialize writes for the same store. Parallel translation batches finish at
167
+ * different times; without a queue an older snapshot could rename over a
168
+ * newer one and briefly hide finished blocks from the UI.
169
+ */
170
+ saveDoc(doc) {
165
171
  doc.updatedAt = nowIso()
166
- await writeJsonAtomic(this.docFile(doc.id), doc)
172
+ const file = this.docFile(doc.id)
173
+ const write = this.saveQueue.then(() => writeJsonAtomic(file, doc))
174
+ this.saveQueue = write.catch(() => {})
175
+ return write
167
176
  }
168
177
 
169
178
  async getDoc(id) {
@@ -275,6 +284,25 @@ export class BilingualStore {
275
284
  return doc
276
285
  }
277
286
 
287
+ async retryBlock(id, blockId) {
288
+ const doc = await this.getDoc(id)
289
+ if (doc === null) throw new Error('找不到文档')
290
+ const block = doc.blocks.find(item => String(item.id) === String(blockId))
291
+ if (block === undefined) throw new Error('找不到段落')
292
+ if (!block.translatable) throw new Error('该段落不需要翻译')
293
+ block.status = 'pending'
294
+ block.translation = ''
295
+ block.error = ''
296
+ block.warning = ''
297
+ block.force = true
298
+ doc.status = 'pending'
299
+ doc.error = ''
300
+ this.translator.refreshStats(doc)
301
+ await this.saveDoc(doc)
302
+ await this.startJob(doc)
303
+ return doc
304
+ }
305
+
278
306
  async exportMarkdown(id) {
279
307
  const doc = await this.getDoc(id)
280
308
  if (doc === null) throw new Error('找不到文档')
package/src/translator.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { buildBatchPrompt, chunkBlocks, parseBatchResponse, selectGlossary } from './prompt.js'
2
2
  import { protectInline } from './protect.js'
3
+ import { translationWarnings } from './quality.js'
3
4
  import { segmentMarkdown } from './segment.js'
4
5
 
5
6
  function failureText(failure) {
@@ -172,14 +173,22 @@ export class Translator {
172
173
  for (const block of translatable) {
173
174
  if (block.status === 'done' || block.status === 'cached') continue
174
175
  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
176
+ if (block.force !== true) {
177
+ const hit = this.cache.get(key)
178
+ if (hit !== null) {
179
+ block.translation = hit
180
+ block.status = 'cached'
181
+ block.error = ''
182
+ block.warning = translationWarnings({
183
+ original: block.original,
184
+ translation: hit,
185
+ glossary: selectGlossary(glossaryTerms, block.original),
186
+ }).join(';')
187
+ doc.stats.cacheHits += 1
188
+ continue
189
+ }
182
190
  }
191
+ block.force = false
183
192
  block.status = 'pending'
184
193
  block.error = ''
185
194
  misses.push(block)
@@ -192,13 +201,24 @@ export class Translator {
192
201
  maxBlocks: this.config.batchBlocks,
193
202
  maxChars: this.config.batchChars,
194
203
  })
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)
204
+ const concurrency = Math.min(4, Math.max(1, Number(this.config.concurrency) || 1))
205
+ let nextBatch = 0
206
+ const worker = async () => {
207
+ while (true) {
208
+ if (options.signal?.aborted) throw new Error('翻译已取消')
209
+ const index = nextBatch
210
+ nextBatch += 1
211
+ if (index >= batches.length) return
212
+ await this.translateBatch(doc, batches[index], { glossaryTerms, glossaryHash, signal: options.signal })
213
+ this.refreshStats(doc)
214
+ await options.onProgress?.(doc)
215
+ }
201
216
  }
217
+ const settled = await Promise.allSettled(
218
+ Array.from({ length: Math.min(concurrency, batches.length) }, () => worker()),
219
+ )
220
+ const failure = settled.find(result => result.status === 'rejected')
221
+ if (failure !== undefined) throw failure.reason
202
222
 
203
223
  this.refreshStats(doc)
204
224
  if (doc.stats.translatable === 0) doc.status = 'done'
@@ -255,17 +275,26 @@ export class Translator {
255
275
  const retried = await this.translateSingle(doc, item, context, { retryOnly: true })
256
276
  if (retried) continue
257
277
  restored = item.protection.restore(value)
258
- item.block.warning = `模型丢失了保护片段:${restored.missing.length}`
278
+ this.finishBlock(
279
+ doc,
280
+ item.block,
281
+ restored.text,
282
+ context.glossaryHash,
283
+ `模型丢失了保护片段:${restored.missing.length}`,
284
+ terms,
285
+ )
286
+ continue
259
287
  }
260
- this.finishBlock(doc, item.block, restored.text)
288
+ this.finishBlock(doc, item.block, restored.text, context.glossaryHash, '', terms)
261
289
  }
262
290
  }
263
291
 
264
292
  async translateSingle(doc, item, context = {}, options = {}) {
293
+ const terms = selectGlossary(context.glossaryTerms ?? [], item.protection.text)
265
294
  const prompt = buildBatchPrompt({
266
295
  blocks: [{ text: item.protection.text }],
267
296
  targetLang: doc.targetLang,
268
- glossary: selectGlossary(context.glossaryTerms ?? [], item.protection.text),
297
+ glossary: terms,
269
298
  context: this.contextFor(doc, [item.block]),
270
299
  })
271
300
  try {
@@ -278,10 +307,14 @@ export class Translator {
278
307
  const values = parseBatchResponse(result.text, 1)
279
308
  const restored = item.protection.restore(values[0] ?? '')
280
309
  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)
310
+ this.finishBlock(
311
+ doc,
312
+ item.block,
313
+ restored.text,
314
+ context.glossaryHash,
315
+ restored.missing.length > 0 ? `模型丢失了保护片段:${restored.missing.length}` : '',
316
+ terms,
317
+ )
285
318
  return true
286
319
  } catch (error) {
287
320
  if (options.retryOnly) return false
@@ -291,7 +324,7 @@ export class Translator {
291
324
  }
292
325
  }
293
326
 
294
- finishBlock(doc, block, translation) {
327
+ finishBlock(doc, block, translation, glossaryHash = this.glossary.hash(), warning = '', glossary = []) {
295
328
  const text = ensureHeadingPrefix(block.original, translation).trim()
296
329
  if (text === '') {
297
330
  block.status = 'failed'
@@ -301,7 +334,9 @@ export class Translator {
301
334
  block.translation = text
302
335
  block.status = 'done'
303
336
  block.error = ''
304
- const key = this.cache.key(block.original, doc.targetLang, this.glossary.hash())
337
+ const quality = translationWarnings({ original: block.original, translation: text, glossary })
338
+ block.warning = [...new Set([warning, ...quality].filter(Boolean))].join(';')
339
+ const key = this.cache.key(block.original, doc.targetLang, glossaryHash)
305
340
  this.cache.set(key, text)
306
341
  }
307
342
 
package/src/util.js CHANGED
@@ -44,7 +44,7 @@ async function replaceFile(temp, file, content) {
44
44
  export async function writeJsonAtomic(file, value) {
45
45
  await fs.mkdir(path.dirname(file), { recursive: true })
46
46
  const content = `${JSON.stringify(value, null, 2)}\n`
47
- const temp = `${file}.tmp-${process.pid}-${Date.now()}`
47
+ const temp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
48
48
  await fs.writeFile(temp, content, 'utf8')
49
49
  await replaceFile(temp, file, content)
50
50
  }
@@ -52,7 +52,7 @@ export async function writeJsonAtomic(file, value) {
52
52
  export async function writeTextAtomic(file, text) {
53
53
  await fs.mkdir(path.dirname(file), { recursive: true })
54
54
  const content = String(text ?? '')
55
- const temp = `${file}.tmp-${process.pid}-${Date.now()}`
55
+ const temp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
56
56
  await fs.writeFile(temp, content, 'utf8')
57
57
  await replaceFile(temp, file, content)
58
58
  }