dsh-bilingual-reader 0.1.1 → 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/README.en.md +27 -5
- package/README.md +28 -5
- package/docs/architecture.md +1 -0
- package/docs/demo.jpg +0 -0
- package/docs/release-v0.2.0.md +41 -0
- package/package.json +1 -1
- package/src/glossary.js +33 -0
- package/src/quality.js +30 -0
- package/src/routes.js +96 -14
- package/src/store.js +19 -0
- package/src/translator.js +24 -11
- package/web/app.js +339 -13
- package/web/index.html +23 -5
- package/web/style.css +112 -4
package/README.en.md
CHANGED
|
@@ -17,10 +17,11 @@ DSH already has 297 translation-related plugins, but most cover a single entry p
|
|
|
17
17
|
This plugin replicates the core experience of Immersive Translate and Read Frog, but in a DSH-native way:
|
|
18
18
|
|
|
19
19
|
- **Bilingual next to the original** — every paragraph keeps its translation underneath; no separate translation window.
|
|
20
|
+
- **Web page or pasted text** — fetch a public article, or switch to **Paste text** when a login wall or SPA blocks extraction.
|
|
20
21
|
- **Read while it translates** — finished paragraphs appear in place, and progress updates replace only the blocks that changed, so your scroll position stays put.
|
|
21
22
|
- **Structure preserved** — code blocks, inline code, LaTeX, link URLs, tables and heading levels are protected; dropped tokens are detected and retried.
|
|
22
23
|
- **Token-efficient** — blocks are batched into one request; translations are cached by `original + target language + glossary hash`.
|
|
23
|
-
- **Reusable** — a glossary enforces consistent terms; bilingual Markdown exports; agents read and write the same data.
|
|
24
|
+
- **Reusable** — a glossary enforces consistent terms, and translations that miss a required term or look untranslated are flagged for review; bilingual Markdown exports; agents read and write the same data.
|
|
24
25
|
- **Local-first** — data lives in `~/.dsh-bilingual-reader/`; no telemetry, no separate API key.
|
|
25
26
|
|
|
26
27
|
## Install
|
|
@@ -51,13 +52,16 @@ Restart DSH and open **Bilingual Reader** in the sidebar. The plugin uses the **
|
|
|
51
52
|
|
|
52
53
|
### Sidebar
|
|
53
54
|
|
|
54
|
-
Paste a public article URL, choose the target language (Simplified Chinese, Traditional Chinese, English, Japanese, Korean) and click **Read and translate**.
|
|
55
|
+
Paste a public article URL, choose the target language (Simplified Chinese, Traditional Chinese, English, Japanese, Korean) and click **Read and translate**. If a page cannot be extracted, switch to **Paste text** and translate Markdown or plain text directly.
|
|
55
56
|
|
|
56
57
|
- **Inline** (default) — the translation sits directly under each paragraph, best for narrow windows and immersive reading.
|
|
57
58
|
- **Bilingual** — original on the left, translation on the right.
|
|
58
59
|
- **Original** / **Translation** — single-column reading; the view choice is remembered.
|
|
59
|
-
- **
|
|
60
|
+
- **Text size and position** — A− / A / A+ in the top bar; the setting is remembered, and each document reopens at your last scroll position. Opening the sidebar again resumes the last document; `?doc=<id>` opens a specific one, `?url=<link>` prefills a URL, and `start=1` begins translation.
|
|
61
|
+
- **Glossary** — add terms such as `token → 令牌`; translations must use them, **Retry this block** bypasses the cache for a fresh attempt, and JSON import/export makes the glossary easy to back up or move.
|
|
60
62
|
- **Export bilingual Markdown** — headings, lists, tables and code blocks are kept.
|
|
63
|
+
- **Print** — reader layout with navigation, sidebar and action buttons hidden.
|
|
64
|
+
- **Copy translations** — copy all translated blocks as Markdown for notes or chat.
|
|
61
65
|
- **Retry failed blocks** — completed blocks are not translated again.
|
|
62
66
|
|
|
63
67
|
### Command
|
|
@@ -98,6 +102,7 @@ The command returns a document id immediately; translation continues in the back
|
|
|
98
102
|
| `DSH_BILINGUAL_BATCH_CHARS` | `3500` | Max characters per request |
|
|
99
103
|
| `DSH_BILINGUAL_CONCURRENCY` | `2` | Concurrent translation batches (1–4) |
|
|
100
104
|
| `DSH_BILINGUAL_MAX_BLOCKS` | `400` | Max blocks per document |
|
|
105
|
+
| `DSH_BILINGUAL_MAX_TRANSLATE_CHARS` | `20000` | Pasted-text and ad-hoc translation limit |
|
|
101
106
|
| `DSH_BILINGUAL_MAX_BYTES` | `5242880` | Page size cap |
|
|
102
107
|
| `DSH_BILINGUAL_TIMEOUT_MS` | `20000` | Fetch timeout |
|
|
103
108
|
| `DSH_BILINGUAL_PROXY` | environment proxy | Fetch proxy |
|
|
@@ -113,17 +118,29 @@ The command returns a document id immediately; translation continues in the back
|
|
|
113
118
|
|
|
114
119
|
## Limitations
|
|
115
120
|
|
|
116
|
-
- Public pages only; login walls, SPAs and anti-bot pages may fail extraction
|
|
121
|
+
- Public pages only; login walls, SPAs and anti-bot pages may fail extraction. Switch to **Paste text** to translate the body directly.
|
|
117
122
|
- No PDF/EPUB/DOCX layout translation in v0.1; convert PDFs to Markdown first.
|
|
118
123
|
- Does not translate assistant replies (covered by `dsh-bilingual` / `dsh-think-translate`); it focuses on web and document reading.
|
|
119
124
|
- Translation quality depends on the DSH default model; malformed batch responses fall back to single blocks.
|
|
120
125
|
- Cache entries are shared across documents; changing the glossary produces new cache keys.
|
|
121
126
|
|
|
127
|
+
## FAQ
|
|
128
|
+
|
|
129
|
+
**Does this conflict with `dsh-reading-inbox`?** No. The inbox saves, organizes, searches and annotates; the bilingual reader fetches the article, translates it and shows the parallel text. With both installed, web documents get a **Save to reading inbox** action.
|
|
130
|
+
|
|
131
|
+
**What content is supported?** Public web pages, or Markdown/plain text pasted directly. PDF, EPUB and DOCX layout translation are out of scope; convert them to Markdown first.
|
|
132
|
+
|
|
133
|
+
**Which model does it use?** The DSH default model, with no separate API key. If the profile has no model, the UI explains it; translated documents remain readable.
|
|
134
|
+
|
|
135
|
+
**What does "glossary miss" mean?** The translation did not use the target term configured in the glossary. Edit the term and click **Retry this block** to bypass the cache for that block.
|
|
136
|
+
|
|
137
|
+
**Where is the data?** `~/.dsh-bilingual-reader/` by default, containing documents, cache and glossary; override it with `DSH_BILINGUAL_READER_DIR`.
|
|
138
|
+
|
|
122
139
|
## Development
|
|
123
140
|
|
|
124
141
|
```sh
|
|
125
142
|
npm install
|
|
126
|
-
npm test #
|
|
143
|
+
npm test # 47 tests: segmentation, protection, prompts, cache, glossary, quality checks, security, store/translator, HTTP routes
|
|
127
144
|
npm run verify # local HTTP fixture → fetch → translate → export → cache
|
|
128
145
|
npm run dev # local UI with a demo model: http://127.0.0.1:4183/dsh-bilingual-reader/
|
|
129
146
|
```
|
|
@@ -132,12 +149,17 @@ Demo article for `npm run dev`: `http://127.0.0.1:4183/demo-article.html`.
|
|
|
132
149
|
|
|
133
150
|
Architecture and data layout: [docs/architecture.md](docs/architecture.md).
|
|
134
151
|
|
|
152
|
+
## Related
|
|
153
|
+
|
|
154
|
+
- [dsh-reading-inbox](https://github.com/bit0620/dsh-reading-inbox) — a local read-later inbox. When both plugins are installed, web documents get a **Save to reading inbox** action that hands the original URL to the inbox for archiving and search.
|
|
155
|
+
|
|
135
156
|
## Inspiration
|
|
136
157
|
|
|
137
158
|
Product shape inspired by [Immersive Translate](https://github.com/immersive-translate/immersive-translate), [Read Frog](https://github.com/tomode1/read-frog), [NextAI Translator](https://github.com/nextai-translator/nextai-translator) and [Saladict](https://github.com/crimx/ext-saladict). The implementation is independent; no affiliation.
|
|
138
159
|
|
|
139
160
|
## Release notes
|
|
140
161
|
|
|
162
|
+
- [v0.2.0](docs/release-v0.2.0.md): paste-text mode, reading-inbox handoff, translation quality warnings, text-size controls and a render cache.
|
|
141
163
|
- [v0.1.1](docs/release-v0.1.1.md): inline bilingual view by default, incremental progress rendering, parallel batches, cache and write consistency fixes.
|
|
142
164
|
- [v0.1.0](docs/release-v0.1.0.md): first release — web/document bilingual reading, glossary, cache, export and agent tools.
|
|
143
165
|
|
package/README.md
CHANGED
|
@@ -17,10 +17,11 @@ DSH 里已经有 297 个和翻译相关的插件,但大多只覆盖一个入
|
|
|
17
17
|
这个插件复刻的是 Immersive Translate / 陪读蛙最核心的体验,但按 DSH 的方式做:
|
|
18
18
|
|
|
19
19
|
- **双语贴着原文**:每段原文下方就是译文,不跳转到另一个翻译窗口。
|
|
20
|
+
- **网页或粘贴文本**:公开文章直接抓正文;登录墙、SPA 可以切到“粘贴文本”,不离开阅读器。
|
|
20
21
|
- **边译边读**:完成的段落立即出现,进度更新只替换变化的段落,不会重置滚动位置。
|
|
21
22
|
- **保结构**:代码块、行内代码、公式、链接 URL、表格、标题层级不翻译;模型丢失保护片段会被检测并重试。
|
|
22
23
|
- **省 token**:多段合并成一次请求;按“原文 + 目标语言 + 术语表哈希”缓存,重复段落不再调用模型。
|
|
23
|
-
-
|
|
24
|
+
- **可沉淀**:术语表强制统一译法,译文没用上指定术语或疑似未翻译时会标记出来;双语 Markdown 可导出;Agent 可以读写同一份数据。
|
|
24
25
|
- **本地优先**:数据在 `~/.dsh-bilingual-reader/`,不发送遥测,不引入独立 API key。
|
|
25
26
|
|
|
26
27
|
## 安装
|
|
@@ -51,13 +52,17 @@ dsh plugin --profile web add file:C:/path/to/dsh-bilingual-reader
|
|
|
51
52
|
|
|
52
53
|
### 侧栏
|
|
53
54
|
|
|
54
|
-
粘贴公开网页链接,选择目标语言(简体中文 / 繁體中文 / English / 日本語 /
|
|
55
|
+
粘贴公开网页链接,选择目标语言(简体中文 / 繁體中文 / English / 日本語 / 한국어),点击“读取并翻译”;抓不到正文的页面可以切到“粘贴文本”,直接翻译 Markdown 或纯文本。
|
|
55
56
|
|
|
56
57
|
- **上下**(默认):原文在上,译文紧随其下,适合窄窗口和沉浸阅读。
|
|
57
58
|
- **对照**:左原文、右译文。
|
|
58
59
|
- **原文** / **译文**:单栏阅读;视图选择会记住。
|
|
59
|
-
-
|
|
60
|
+
- **字号与位置**:顶栏 A− / A / A+ 调整正文大小,选择会记住;每篇文档的阅读位置也会保存,重新打开回到上次处。
|
|
61
|
+
- **继续阅读**:再次打开侧栏会自动恢复上次文档;也支持 `?doc=<id>` 直接打开某一篇,`?url=<链接>` 预填链接,加 `start=1` 可直接开始翻译。
|
|
62
|
+
- **术语表**:添加 `token → 令牌` 这类术语,翻译时强制使用;质量提示旁的“重试此段”会绕过缓存重新翻译该段;支持 JSON 导入/导出,方便备份和换机器。
|
|
60
63
|
- **导出双语 Markdown**:保留标题、列表、表格和代码块。
|
|
64
|
+
- **打印**:按阅读版式输出,自动隐藏导航、侧栏和操作按钮。
|
|
65
|
+
- **复制译文**:一键复制全部译文 Markdown,方便贴进笔记或对话。
|
|
61
66
|
- 失败的段落可以“重试失败段”,不会重跑已完成的段落。
|
|
62
67
|
|
|
63
68
|
### 命令
|
|
@@ -98,6 +103,7 @@ dsh plugin --profile web add file:C:/path/to/dsh-bilingual-reader
|
|
|
98
103
|
| `DSH_BILINGUAL_BATCH_CHARS` | `3500` | 每次请求最多字符数 |
|
|
99
104
|
| `DSH_BILINGUAL_CONCURRENCY` | `2` | 同时翻译的批次数(1–4) |
|
|
100
105
|
| `DSH_BILINGUAL_MAX_BLOCKS` | `400` | 单篇最多段落数 |
|
|
106
|
+
| `DSH_BILINGUAL_MAX_TRANSLATE_CHARS` | `20000` | 粘贴文本 / 即时翻译字符上限 |
|
|
101
107
|
| `DSH_BILINGUAL_MAX_BYTES` | `5242880` | 页面大小上限 |
|
|
102
108
|
| `DSH_BILINGUAL_TIMEOUT_MS` | `20000` | 抓取超时 |
|
|
103
109
|
| `DSH_BILINGUAL_PROXY` | 环境代理 | 抓取代理 |
|
|
@@ -113,17 +119,29 @@ dsh plugin --profile web add file:C:/path/to/dsh-bilingual-reader
|
|
|
113
119
|
|
|
114
120
|
## 限制
|
|
115
121
|
|
|
116
|
-
- 只支持公开页面;登录墙、SPA
|
|
122
|
+
- 只支持公开页面;登录墙、SPA、反爬页可能提取失败,可以切到“粘贴文本”直接翻译正文。
|
|
117
123
|
- 第一版不做 PDF / EPUB / DOCX 版面翻译;PDF 可以先用其他工具转 Markdown。
|
|
118
124
|
- 不翻译助手回复(已有 `dsh-bilingual` / `dsh-think-translate` 覆盖),专注网页与文档阅读。
|
|
119
125
|
- 翻译质量取决于 DSH 默认模型;批量解析失败会自动降级到单段。
|
|
120
126
|
- 缓存按段落命中,跨文档共享;修改术语表会产生新的缓存键。
|
|
121
127
|
|
|
128
|
+
## 常见问题
|
|
129
|
+
|
|
130
|
+
**和 `dsh-reading-inbox` 冲突吗?** 不冲突:阅读箱负责收藏、归档、检索和批注,双语阅读负责抓正文、翻译和对照阅读。同时安装后,双语阅读的网页文档会出现“存入阅读箱”。
|
|
131
|
+
|
|
132
|
+
**支持哪些内容?** 公开网页,或直接粘贴 Markdown / 纯文本。PDF、EPUB、DOCX 版面翻译暂不支持,可以先把内容转成 Markdown。
|
|
133
|
+
|
|
134
|
+
**用的哪个模型?** DSH 默认模型,不需要单独的 API key;没有配置模型时界面会提示,已翻译文档仍可浏览。
|
|
135
|
+
|
|
136
|
+
**“术语未命中”是什么意思?** 译文没有使用术语表里为该词指定的译法。可以修改术语后点“重试此段”,会绕过缓存重新翻译该段。
|
|
137
|
+
|
|
138
|
+
**数据在哪里?** 默认 `~/.dsh-bilingual-reader/`,包括文档、缓存和术语表;可以用 `DSH_BILINGUAL_READER_DIR` 改位置。
|
|
139
|
+
|
|
122
140
|
## 开发
|
|
123
141
|
|
|
124
142
|
```sh
|
|
125
143
|
npm install
|
|
126
|
-
npm test #
|
|
144
|
+
npm test # 47 项单测:切分、保护、提示词、缓存、术语表、质量检查、安全、store/translator、HTTP 路由
|
|
127
145
|
npm run verify # 本地 HTTP fixture → 抓取 → 翻译 → 导出 → 缓存
|
|
128
146
|
npm run dev # 带示范模型的本地 UI:http://127.0.0.1:4183/dsh-bilingual-reader/
|
|
129
147
|
```
|
|
@@ -132,12 +150,17 @@ npm run dev # 带示范模型的本地 UI:http://127.0.0.1:4183/dsh-bili
|
|
|
132
150
|
|
|
133
151
|
架构与数据格式见 [docs/architecture.md](docs/architecture.md)。
|
|
134
152
|
|
|
153
|
+
## 相关项目
|
|
154
|
+
|
|
155
|
+
- [dsh-reading-inbox](https://github.com/bit0620/dsh-reading-inbox) — 本地阅读收件箱。同时安装后,双语阅读的网页文档会出现“存入阅读箱”,把原文链接交给阅读箱归档和后续检索。
|
|
156
|
+
|
|
135
157
|
## 灵感与致谢
|
|
136
158
|
|
|
137
159
|
产品形态参考 [Immersive Translate](https://github.com/immersive-translate/immersive-translate)、[陪读蛙 Read Frog](https://github.com/tomode1/read-frog)、[NextAI Translator](https://github.com/nextai-translator/nextai-translator) 和 [Saladict](https://github.com/crimx/ext-saladict);代码为独立实现,与这些项目没有隶属关系。
|
|
138
160
|
|
|
139
161
|
## 版本说明
|
|
140
162
|
|
|
163
|
+
- [v0.2.0](docs/release-v0.2.0.md):粘贴文本、阅读箱集成、翻译质量提示、阅读字号与渲染缓存。
|
|
141
164
|
- [v0.1.1](docs/release-v0.1.1.md):默认“上下对照”视图,逐段渐进更新,批量并行翻译,缓存与并发写入修正。
|
|
142
165
|
- [v0.1.0](docs/release-v0.1.0.md):首个版本,网页/文档双语阅读、术语表、缓存、导出与 Agent 工具。
|
|
143
166
|
|
package/docs/architecture.md
CHANGED
|
@@ -51,6 +51,7 @@ URL ──fetchHtml──> HTML ──Readability + Turndown──> Markdown
|
|
|
51
51
|
- 一个批次失败会拆成单段重试;单段仍失败只标记该段,不影响其他段落。
|
|
52
52
|
- 模型丢失保护 token 时先重试单段;仍丢失则保留译文并给该段加 `warning`,不会静默删掉链接或代码。
|
|
53
53
|
- 所有写文件使用唯一临时文件 + rename,避免半截 JSON;同一 store 的文档写入串行化,并行批次不会用旧快照覆盖新快照。
|
|
54
|
+
- HTTP 轮询返回的块 HTML 按内容哈希缓存,未变化段落不会重复执行 marked + sanitize-html;缓存有上限并在超限时清空。
|
|
54
55
|
|
|
55
56
|
## 安全边界
|
|
56
57
|
|
package/docs/demo.jpg
CHANGED
|
Binary file
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# dsh-bilingual-reader v0.2.0 / 粘贴文本、阅读箱与质量提示
|
|
2
|
+
|
|
3
|
+
v0.2.0 补齐了“抓不到网页时怎么办”:可以直接粘贴 Markdown 或纯文本翻译;网页文档可以把原文一键交给 `dsh-reading-inbox` 归档;译文漏用术语或疑似未翻译时会标记出来。
|
|
4
|
+
|
|
5
|
+
v0.2.0 adds a paste-text mode, a one-click handoff to `dsh-reading-inbox`, glossary/untranslated quality warnings, persisted text-size controls and a render cache for polling.
|
|
6
|
+
|
|
7
|
+
- GitHub: <https://github.com/bit0620/dsh-bilingual-reader>
|
|
8
|
+
- npm: <https://www.npmjs.com/package/dsh-bilingual-reader>
|
|
9
|
+
- 版本:`0.2.0`
|
|
10
|
+
- 升级:`dsh plugin --profile web add dsh-bilingual-reader@0.2.0`
|
|
11
|
+
|
|
12
|
+
## 变化 / Changes
|
|
13
|
+
|
|
14
|
+
- **粘贴文本**:侧栏可在“网页链接 / 粘贴文本”之间切换,直接翻译 Markdown 或纯文本;标题取第一行,文档照常保存、导出和重试。上限由 `DSH_BILINGUAL_MAX_TRANSLATE_CHARS` 控制(默认 20,000 字符),支持 Ctrl/Cmd+Enter 提交。
|
|
15
|
+
- **阅读箱集成**:检测到 `dsh-reading-inbox` 时,网页文档页显示“存入阅读箱”,通过阅读箱已有的 `?clip=<url>` 入口归档原文;粘贴文本文档不显示该按钮。
|
|
16
|
+
- **翻译质量提示**:译文与原文相同(长文本)、或术语表指定译法没有出现在译文中时,给该段加“可能未翻译 / 术语未命中”徽标;不改变通过状态,只提示复核。徽标旁的“重试此段”会绕过缓存重新翻译该段。
|
|
17
|
+
- **缓存也做质量检查**:命中的缓存译文同样会检查术语和未翻译情况,不会因为命中缓存而跳过提示。
|
|
18
|
+
- **术语表导入/导出**:术语表弹窗支持导出 JSON 和导入 JSON,导入按 source 合并(新增/更新/跳过计数),适合备份和换机器。
|
|
19
|
+
- **阅读字号与位置**:顶栏 A− / A / A+,90%–130% 五档,选择保存在 localStorage;每篇文档保存滚动位置,重新打开回到上次处。再次打开侧栏自动恢复上次文档,`?doc=<id>` 可深链到指定文档,`?url=<链接>&start=1` 可直接开始翻译。
|
|
20
|
+
- **打印**:文档页新增“打印”,打印样式隐藏导航、输入区、侧栏和操作按钮,按上下对照排版。
|
|
21
|
+
- **复制译文**:一键复制全部译文 Markdown,适合贴进笔记或对话。
|
|
22
|
+
- **无障碍**:进度条使用 `progressbar` 语义并同步进度值;输入方式按钮使用 `aria-pressed`;补充刷新按钮标签。
|
|
23
|
+
- **渲染性能**:轮询返回的块 HTML 按内容哈希缓存(上限 2000),未变化段落不再重复执行 marked + sanitize-html。
|
|
24
|
+
|
|
25
|
+
## 验证 / Verification
|
|
26
|
+
|
|
27
|
+
- 47 项单测:新增质量检查、粘贴文本路由、单段强制重试、术语表导入/导出、文档列表/导出/删除、跨站请求拒绝;全部通过。
|
|
28
|
+
- `npm run verify`:本地 HTTP fixture → 抓取 → 翻译 → 导出 → 缓存,端到端通过。
|
|
29
|
+
- 本地 UI 实测:粘贴文本标题/段落/代码块切分正确;字号 110% 刷新后保持;术语未命中徽标显示;无阅读箱时“存入阅读箱”保持隐藏。
|
|
30
|
+
- 本地 `npm pack --dry-run` 通过;提交后由 GitHub Actions Node 22/24 矩阵复核。
|
|
31
|
+
|
|
32
|
+
## 兼容性 / Compatibility
|
|
33
|
+
|
|
34
|
+
- 新增 HTTP 入口 `POST /dsh-bilingual-reader/api/read-text`,供界面使用;Agent 工具不变。
|
|
35
|
+
- 文档、缓存和术语表格式不变;0.1.x 的文档可以直接打开。
|
|
36
|
+
- 仍要求 DSH `>=0.2.0 <0.3.0`、Node.js `>=22.12`。
|
|
37
|
+
|
|
38
|
+
## 说明 / Notes
|
|
39
|
+
|
|
40
|
+
- “存入阅读箱”只传递原文 URL,不复制双语正文;阅读箱负责归档与检索,双语阅读负责翻译与对照。
|
|
41
|
+
- 质量提示是启发式检查,不会因为提示而阻断导出或缓存。
|
package/package.json
CHANGED
package/src/glossary.js
CHANGED
|
@@ -52,6 +52,39 @@ export class Glossary {
|
|
|
52
52
|
return this.list()
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
+
importTerms(terms) {
|
|
56
|
+
const incoming = Array.isArray(terms) ? terms : []
|
|
57
|
+
let added = 0
|
|
58
|
+
let updated = 0
|
|
59
|
+
let skipped = 0
|
|
60
|
+
for (const term of incoming) {
|
|
61
|
+
if (term === null || typeof term !== 'object') {
|
|
62
|
+
skipped += 1
|
|
63
|
+
continue
|
|
64
|
+
}
|
|
65
|
+
const source = cleanTerm(term.source)
|
|
66
|
+
const target = cleanTerm(term.target)
|
|
67
|
+
if (source === '' || target === '') {
|
|
68
|
+
skipped += 1
|
|
69
|
+
continue
|
|
70
|
+
}
|
|
71
|
+
const note = cleanTerm(term.note, 160)
|
|
72
|
+
const existing = this.terms.find(item => item.source.toLowerCase() === source.toLowerCase())
|
|
73
|
+
if (existing !== undefined) {
|
|
74
|
+
existing.target = target
|
|
75
|
+
existing.note = note
|
|
76
|
+
updated += 1
|
|
77
|
+
} else if (this.terms.length < this.limit) {
|
|
78
|
+
this.terms.push({ source, target, note })
|
|
79
|
+
added += 1
|
|
80
|
+
} else {
|
|
81
|
+
skipped += 1
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
this.terms.sort((a, b) => a.source.localeCompare(b.source))
|
|
85
|
+
return { terms: this.list(), added, updated, skipped }
|
|
86
|
+
}
|
|
87
|
+
|
|
55
88
|
remove(source) {
|
|
56
89
|
const cleanSource = cleanTerm(source)
|
|
57
90
|
if (cleanSource === '') throw new Error('术语 source 不能为空')
|
package/src/quality.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
function normalize(text) {
|
|
2
|
+
return String(text ?? '')
|
|
3
|
+
.replace(/^#{1,6}\s+/, '')
|
|
4
|
+
.replace(/\s+/g, ' ')
|
|
5
|
+
.trim()
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Non-blocking checks for a finished translation. These do not change the
|
|
10
|
+
* pass/fail state; they add a visible warning so a bad block is easy to review.
|
|
11
|
+
*/
|
|
12
|
+
export function translationWarnings({ original, translation, glossary = [] } = {}) {
|
|
13
|
+
const warnings = []
|
|
14
|
+
const source = normalize(original)
|
|
15
|
+
const target = normalize(translation)
|
|
16
|
+
if (source.length >= 20 && source.toLocaleLowerCase() === target.toLocaleLowerCase()) {
|
|
17
|
+
warnings.push('译文与原文相同')
|
|
18
|
+
}
|
|
19
|
+
const haystack = target.toLocaleLowerCase()
|
|
20
|
+
for (const term of glossary) {
|
|
21
|
+
const sourceTerm = normalize(term?.source)
|
|
22
|
+
const targetTerm = normalize(term?.target)
|
|
23
|
+
if (sourceTerm === '' || targetTerm === '') continue
|
|
24
|
+
if (!source.toLocaleLowerCase().includes(sourceTerm.toLocaleLowerCase())) continue
|
|
25
|
+
if (!haystack.includes(targetTerm.toLocaleLowerCase())) {
|
|
26
|
+
warnings.push(`术语未使用:${sourceTerm}`)
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return warnings
|
|
30
|
+
}
|
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:
|
|
115
|
-
translationHtml: 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'
|
|
261
|
-
if (
|
|
262
|
-
|
|
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 === '
|
|
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
|
-
|
|
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,
|
|
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
|
@@ -284,6 +284,25 @@ export class BilingualStore {
|
|
|
284
284
|
return doc
|
|
285
285
|
}
|
|
286
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
|
+
|
|
287
306
|
async exportMarkdown(id) {
|
|
288
307
|
const doc = await this.getDoc(id)
|
|
289
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
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
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)
|
|
@@ -272,18 +281,20 @@ export class Translator {
|
|
|
272
281
|
restored.text,
|
|
273
282
|
context.glossaryHash,
|
|
274
283
|
`模型丢失了保护片段:${restored.missing.length}`,
|
|
284
|
+
terms,
|
|
275
285
|
)
|
|
276
286
|
continue
|
|
277
287
|
}
|
|
278
|
-
this.finishBlock(doc, item.block, restored.text, context.glossaryHash)
|
|
288
|
+
this.finishBlock(doc, item.block, restored.text, context.glossaryHash, '', terms)
|
|
279
289
|
}
|
|
280
290
|
}
|
|
281
291
|
|
|
282
292
|
async translateSingle(doc, item, context = {}, options = {}) {
|
|
293
|
+
const terms = selectGlossary(context.glossaryTerms ?? [], item.protection.text)
|
|
283
294
|
const prompt = buildBatchPrompt({
|
|
284
295
|
blocks: [{ text: item.protection.text }],
|
|
285
296
|
targetLang: doc.targetLang,
|
|
286
|
-
glossary:
|
|
297
|
+
glossary: terms,
|
|
287
298
|
context: this.contextFor(doc, [item.block]),
|
|
288
299
|
})
|
|
289
300
|
try {
|
|
@@ -302,6 +313,7 @@ export class Translator {
|
|
|
302
313
|
restored.text,
|
|
303
314
|
context.glossaryHash,
|
|
304
315
|
restored.missing.length > 0 ? `模型丢失了保护片段:${restored.missing.length}` : '',
|
|
316
|
+
terms,
|
|
305
317
|
)
|
|
306
318
|
return true
|
|
307
319
|
} catch (error) {
|
|
@@ -312,7 +324,7 @@ export class Translator {
|
|
|
312
324
|
}
|
|
313
325
|
}
|
|
314
326
|
|
|
315
|
-
finishBlock(doc, block, translation, glossaryHash = this.glossary.hash(), warning = '') {
|
|
327
|
+
finishBlock(doc, block, translation, glossaryHash = this.glossary.hash(), warning = '', glossary = []) {
|
|
316
328
|
const text = ensureHeadingPrefix(block.original, translation).trim()
|
|
317
329
|
if (text === '') {
|
|
318
330
|
block.status = 'failed'
|
|
@@ -322,7 +334,8 @@ export class Translator {
|
|
|
322
334
|
block.translation = text
|
|
323
335
|
block.status = 'done'
|
|
324
336
|
block.error = ''
|
|
325
|
-
block.
|
|
337
|
+
const quality = translationWarnings({ original: block.original, translation: text, glossary })
|
|
338
|
+
block.warning = [...new Set([warning, ...quality].filter(Boolean))].join(';')
|
|
326
339
|
const key = this.cache.key(block.original, doc.targetLang, glossaryHash)
|
|
327
340
|
this.cache.set(key, text)
|
|
328
341
|
}
|