transproof-dsh-plugin 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.
@@ -0,0 +1,652 @@
1
+ /* ═══════════ 4.23.0 P1:修订模式 —— 逐词/逐字 diff 生成 w:del / w:ins ═══════════
2
+ 原理:与「替换模式」共用解包回写引擎;差别在于改动段不再整段覆盖,而是
3
+ 拆成「删除的旧文字(w:del + w:delText,Word 显示删除线)」和「新增的新文字
4
+ (w:ins,显示下划线)」,Word/WPS 打开后可在「审阅」页逐条接受/拒绝。
5
+ 段落级格式(w:pPr:缩进/对齐/行距)与图片完全不碰,首个 run 的 rPr 作为
6
+ 新 run 的样式模板 → 字号/字体/加粗保留。 */
7
+ const TP_W_NS = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main';
8
+ function tpTokens(s){
9
+ // ASCII 连串(字母/数字)成词,空白成段,其余单字符成词 → 贴近 Word 的修订粒度
10
+ return String(s).match(/[A-Za-z0-9_]+|\s+|[^\s]/gu) || [];
11
+ }
12
+ function tpDiffOps(a, b, cap){
13
+ const n = a.length, m = b.length;
14
+ if(!n && !m) return [];
15
+ if(!n) return [{ t: '+', s: b.join('') }];
16
+ if(!m) return [{ t: '-', s: a.join('') }];
17
+ // DP 规模超限(长段落×长段落)→ 降级为整段删除+整段新增,保证不卡死
18
+ if(n * m > cap) return [{ t: '-', s: a.join('') }, { t: '+', s: b.join('') }];
19
+ const dp = [];
20
+ for(let i = 0; i <= n; i++) dp.push(new Uint32Array(m + 1));
21
+ for(let i = n - 1; i >= 0; i--)
22
+ for(let j = m - 1; j >= 0; j--)
23
+ dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
24
+ const ops = [];
25
+ const push = (t, ch) => { const last = ops[ops.length - 1]; if(last && last.t === t) last.s += ch; else ops.push({ t, s: ch }); };
26
+ let i = 0, j = 0;
27
+ while(i < n && j < m){
28
+ if(a[i] === b[j]){ push('=', a[i]); i++; j++; }
29
+ else if(dp[i + 1][j] >= dp[i][j + 1]){ push('-', a[i]); i++; }
30
+ else { push('+', b[j]); j++; }
31
+ }
32
+ while(i < n){ push('-', a[i]); i++; }
33
+ while(j < m){ push('+', b[j]); j++; }
34
+ return ops;
35
+ }
36
+ function tpRun(doc, rPr, text, tag){
37
+ const r = doc.createElementNS(TP_W_NS, 'w:r');
38
+ if(rPr) r.appendChild(rPr.cloneNode(true));
39
+ const t = doc.createElementNS(TP_W_NS, tag); // 普通文字 w:t / 删除文字 w:delText
40
+ t.setAttribute('xml:space', 'preserve');
41
+ t.textContent = text;
42
+ r.appendChild(t);
43
+ return r;
44
+ }
45
+ function writeTrackedDiff(doc, target, newText, revId, date){
46
+ const p = target.p;
47
+ const firstR = p.getElementsByTagName('w:r')[0];
48
+ const rPr = firstR ? firstR.getElementsByTagName('w:rPr')[0] : null; // 首 run 样式模板
49
+ const ops = tpDiffOps(tpTokens(target.text), tpTokens(newText), 250000);
50
+ // 清空段内子节点、仅留 w:pPr(段落级格式保留);rPr 已在清理前克隆
51
+ for(const ch of Array.from(p.childNodes)){
52
+ if(ch.nodeType === 1 && ch.localName === 'pPr') continue;
53
+ p.removeChild(ch);
54
+ }
55
+ for(const op of ops){
56
+ if(op.t === '='){ p.appendChild(tpRun(doc, rPr, op.s, 'w:t')); continue; }
57
+ const wrap = doc.createElementNS(TP_W_NS, op.t === '-' ? 'w:del' : 'w:ins');
58
+ wrap.setAttributeNS(TP_W_NS, 'w:id', String(++revId.v));
59
+ wrap.setAttributeNS(TP_W_NS, 'w:author', 'TransProof');
60
+ wrap.setAttributeNS(TP_W_NS, 'w:date', date);
61
+ wrap.appendChild(tpRun(doc, rPr, op.s, op.t === '-' ? 'w:delText' : 'w:t'));
62
+ p.appendChild(wrap);
63
+ }
64
+ }
65
+ async function exportProofreadDocx(track){
66
+ const f = __TP_FILES.dst;
67
+ if(!f || !f._zipBytes){ toast('请先在译文侧上传 Word 文档并勾选「文档模式」', 'e'); return; }
68
+ const proofText = extractProofText(LAST_OUT);
69
+ if(!proofText){ toast('校对结果里没有找到「修订后译文」段,无法回写', 'e'); return; }
70
+ const btn = track ? $('#btn-trackdoc') : $('#btn-docout');
71
+ btn.disabled = true; const old = btn.textContent; btn.textContent = '⏳ 生成中…';
72
+ try{
73
+ await loadLib('JSZip', ['https://registry.npmmirror.com/jszip/3.10.1/files/dist/jszip.min.js', 'https://cdn.bootcdn.net/ajax/libs/jszip/3.10.1/jszip.min.js', 'https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js', 'https://unpkg.com/jszip@3.10.1/dist/jszip.min.js']);
74
+ const zip = await window.JSZip.loadAsync(f._zipBytes);
75
+ const xml = await zip.file('word/document.xml').async('string');
76
+ const doc = new DOMParser().parseFromString(xml, 'application/xml');
77
+ if(doc.getElementsByTagName('parsererror').length) throw new Error('document.xml 解析失败');
78
+
79
+ // 1) 收集 body 直系段落(跳过表格内段落,避免误伤复杂结构)
80
+ const body = doc.getElementsByTagName('w:body')[0];
81
+ const paras = [];
82
+ for(const p of Array.from(body.children)){
83
+ if(p.tagName === 'w:p'){
84
+ const ts = Array.from(p.getElementsByTagName('w:t'));
85
+ const text = ts.map(t => t.textContent).join('').trim();
86
+ if(text) paras.push({ p, ts, text });
87
+ }
88
+ }
89
+ if(!paras.length) throw new Error('文档中没有可替换的文字段落');
90
+
91
+ // 2) 切分校对后的译文段
92
+ const segs = proofText.split(/\n\s*\n/).map(s => s.trim()).filter(Boolean);
93
+ // 去掉每段开头可能的列表/标题 markdown 记号(文档模式下不该有,防御性清理)
94
+ const clean = segs.map(s => s.replace(/^#{1,4}\s*/m, '').replace(/^\s*[-*]\s+/m, '').trim());
95
+
96
+ // 3) 对齐策略:一一对应;数量不匹配时按顺序对应到 min,多余忽略、缺失保留原文
97
+ const n = Math.min(paras.length, clean.length);
98
+ let replaced = 0, unchanged = 0;
99
+ if(track){
100
+ /* 修订模式:逐词/逐字 diff → w:del + w:ins,Word 审阅页可接受/拒绝 */
101
+ const revId = { v: 0 };
102
+ const date = new Date().toISOString().replace(/\.\d+Z$/, 'Z');
103
+ for(let i = 0; i < n; i++){
104
+ const target = paras[i];
105
+ const newText = clean[i];
106
+ if(newText === target.text){ unchanged++; continue; }
107
+ writeTrackedDiff(doc, target, newText, revId, date);
108
+ replaced++;
109
+ }
110
+ } else {
111
+ for(let i = 0; i < n; i++){
112
+ const target = paras[i];
113
+ const newText = clean[i];
114
+ if(newText === target.text){ unchanged++; continue; }
115
+ // 写入第一个 w:t,清空其余(保留首个 run 的样式属性 → 字体/字号/加粗全保留)
116
+ let first = true;
117
+ for(const t of target.ts){
118
+ if(first){ t.textContent = newText; t.setAttribute('xml:space', 'preserve'); first = false; }
119
+ else t.textContent = '';
120
+ }
121
+ replaced++;
122
+ }
123
+ }
124
+ const mismatchNote = paras.length !== clean.length
125
+ ? ';⚠ 段落数不匹配(原文档 ' + paras.length + ' 段 / 校对输出 ' + clean.length + ' 段),已按顺序对应前 ' + n + ' 段,其余保留原文'
126
+ : '';
127
+
128
+ // 4) 序列化回写(补回 XML 声明)
129
+ let serialized = new XMLSerializer().serializeToString(doc);
130
+ // Chromium 的 XMLSerializer 会自带一个 <?xml?> 声明——先剥掉再统一补回,
131
+ // 否则 document.xml 出现两条声明,Word/WPS 会判定文件损坏无法打开
132
+ serialized = serialized.replace(/^\s*<\?xml[^>]*\?>\s*/i, '');
133
+ const newXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n' + serialized;
134
+ zip.file('word/document.xml', newXml);
135
+ // 修订模式:settings.xml 加 w:trackChanges,让 Word 默认处于「记录修订」状态
136
+ if(track){
137
+ try{
138
+ const stf = zip.file('word/settings.xml');
139
+ if(stf){
140
+ let st = await stf.async('string');
141
+ if(!/<w:trackChanges[\s/>]/.test(st)) st = st.replace(/(<w:settings\b[^>]*>)/, '$1<w:trackChanges/>');
142
+ zip.file('word/settings.xml', st);
143
+ }
144
+ }catch(_){} // settings 缺失/异常不阻断主流程
145
+ }
146
+
147
+ // 5) 打包下载
148
+ const blob = await zip.generateAsync({
149
+ type: 'blob',
150
+ mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
151
+ });
152
+ const baseName = (f.fileName || '文档.docx').replace(/\.docx$/i, '');
153
+ if(track){
154
+ dlBlob('校对修订_' + baseName + '.docx', blob);
155
+ toast('已生成修订模式文档:' + replaced + ' 段带修订痕迹、' + unchanged + ' 段未动。用 Word 打开 →「审阅」→ 逐条接受/拒绝' + mismatchNote, replaced ? 'ok' : '');
156
+ }else{
157
+ dlBlob('校对后_' + baseName + '.docx', blob);
158
+ toast('已生成:替换 ' + replaced + ' 段,未变 ' + unchanged + ' 段' + mismatchNote, replaced ? 'ok' : '');
159
+ }
160
+ glossLog(track ? 'exportDocxTrack' : 'exportDocx', 'dst:' + f.fileName, null, { track: !!track, replaced, unchanged, paras: paras.length, segs: clean.length });
161
+ }catch(err){
162
+ toast('文档生成失败:' + err.message, 'e');
163
+ }finally{
164
+ btn.disabled = false; btn.textContent = old;
165
+ }
166
+ }
167
+ $('#btn-docout').onclick = () => exportProofreadDocx(false);
168
+ $('#btn-trackdoc').onclick = () => exportProofreadDocx(true);
169
+ // 勾/取消文档模式即时显隐两个导出按钮(恢复任务后无需重跑一次也能用)
170
+ $('#c-docmode').addEventListener('change', () => {
171
+ const v = docModeActive() ? '' : 'none';
172
+ $('#btn-docout').style.display = v;
173
+ $('#btn-trackdoc').style.display = v;
174
+ });
175
+
176
+ /* ═══════════════════════════════════════════════════════════════
177
+ 专有译词库(3.0)
178
+ 数据流:导入文件 → 解析候选词条 → 归一化合并 → 审核 → 入库 → 导出/同步
179
+ ═══════════════════════════════════════════════════════════════ */
180
+ /* GLOSS / PROMPTS 数据声明已提升到 01-core.js(避免 02/03 加载即引用时 ReferenceError) */
181
+ function savePrompts(){ save(LS_PROMPTS, PROMPTS); }
182
+ function newPromptId(){ return 'p_' + Date.now() + '_' + Math.floor(Math.random()*1000); }
183
+ function saveGloss(){ save(LS_GLOSS, GLOSS); }
184
+ function glossLog(action, target, before, after){
185
+ GLOSS.log.unshift({ t: Date.now(), action, target, before: before||null, after: after||null });
186
+ if(GLOSS.log.length > 500) GLOSS.log.length = 500;
187
+ }
188
+ let GID = GLOSS.terms.reduce((m,t)=>Math.max(m, Number(t.id)||0), 0) + 1;
189
+
190
+ // ── 繁简转换(懒加载 OpenCC)──
191
+ let __t2s = null;
192
+ async function t2s(text){
193
+ if(!text) return text;
194
+ try{
195
+ if(!__t2s){
196
+ await loadLib('OpenCC', ['https://cdn.jsdelivr.net/npm/opencc-js@1.0.5/dist/umd/full.js', 'https://unpkg.com/opencc-js@1.0.5/dist/umd/full.js']);
197
+ __t2s = window.OpenCC.Converter({ from:'t', to:'cn' });
198
+ }
199
+ return await __t2s(text);
200
+ }catch(_){ return text; }
201
+ }
202
+ // 全半角 + 空白归一
203
+ function normText(s){
204
+ return String(s||'')
205
+ .replace(/[\uFF01-\uFF5E]/g, ch => String.fromCharCode(ch.charCodeAt(0) - 0xFEE0))
206
+ .replace(/\u3000/g, ' ')
207
+ .replace(/\s+/g, ' ')
208
+ .trim();
209
+ }
210
+
211
+ // ── 索引行解析启发式 ──
212
+ // 支持形态:
213
+ // 中文词目……12, 45 中文,外文……12 外文(中文)……12
214
+ // 中文(外文),12 外文 中文 12 中文,外文, 12
215
+ function parseIndexLine(line){
216
+ let s = normText(line);
217
+ if(!s || s.length < 2) return null;
218
+ // 1) 剥离行尾页码:数字序列(逗号/空格分隔),前面容许 …… 或 , 或 。 或 —
219
+ let pages = [];
220
+ const pm = s.match(/(?:…+|\.+|-{1,2}|,|,|:|:|\s)\s*(\d+(?:\s*[,,,]\s*\d+)*)\s*$/);
221
+ if(pm){ pages = pm[1].split(/[,,,]/).map(x=>x.trim()).filter(Boolean); s = s.slice(0, pm.index).trim(); }
222
+ s = s.replace(/[…·,,;;::]+$/, '').trim();
223
+ if(!s) return null;
224
+
225
+ // 2) 括号模式:中文(外文) 或 外文(中文)
226
+ const br = s.match(/^(.+?)[((](.+?)[))]$/);
227
+ if(br){
228
+ const a = br[1].trim(), b = br[2].trim();
229
+ const aIsZh = isZh(a), bIsZh = isZh(b);
230
+ if(aIsZh && !bIsZh) return mkEntry(a, b, pages, s);
231
+ if(!aIsZh && bIsZh) return mkEntry(b, a, pages, s);
232
+ if(aIsZh && bIsZh) return mkEntry(a, b, pages, s); // 都是中文:b 作别名处理由归一层做
233
+ }
234
+ // 3) 分隔符模式:中文,外文 / 外文,中文 / 中文 外文
235
+ const parts = s.split(/[,,,]|\s{2,}/).map(x=>x.trim()).filter(Boolean);
236
+ if(parts.length >= 2){
237
+ let zh = '', foreign = '';
238
+ for(const p of parts){
239
+ if(isZh(p) && !zh) zh = p;
240
+ else if(!isZh(p) && !foreign) foreign = p;
241
+ else if(isZh(p) && zh) { /* 第二个中文片段并入 zh(少见)*/ }
242
+ else if(!isZh(p) && foreign){ foreign += ' ' + p; }
243
+ }
244
+ if(zh && foreign) return mkEntry(zh, foreign, pages, s);
245
+ if(zh) return mkEntry(zh, '', pages, s);
246
+ }
247
+ // 4) "外文 中文"(空格分隔,如 "Aufhebung 扬弃")
248
+ const sp = s.split(/\s+/);
249
+ if(sp.length >= 2 && !isZh(sp[0]) && isZh(sp[sp.length-1])){
250
+ return mkEntry(sp[sp.length-1], sp.slice(0,-1).join(' '), pages, s);
251
+ }
252
+ // 5) 纯中文词目 / 纯外文词条
253
+ if(isZh(s)) return mkEntry(s, '', pages, s);
254
+ if(/[A-Za-zÀ-ÿā-žÁ-ý]/.test(s)) return mkEntry('', s, pages, s);
255
+ return null;
256
+ }
257
+ function isZh(s){ return /[\u4e00-\u9fff]/.test(s); }
258
+ function zhRatio(s){ const c = String(s||''); const zh = (c.match(/[\u4e00-\u9fff]/g)||[]).length; return c.length ? zh/c.length : 0; }
259
+ function mkEntry(zh, foreign, pages, raw){
260
+ return { zh: zh||'', foreign: foreign||'', pages, raw };
261
+ }
262
+
263
+ // ── 文件导入分发 ──
264
+ async function parseGlossFile(file){
265
+ const ext = (file.name||'').split('.').pop().toLowerCase();
266
+ const text = async () => new TextDecoder('utf-8').decode(await file.arrayBuffer());
267
+ if(ext === 'txt') return parseIndexText(await text(), file.name);
268
+ if(ext === 'csv') return parseCsvText(await text(), file.name);
269
+ if(ext === 'json') return parseJsonText(await text(), file.name);
270
+ if(ext === 'tbx' || ext === 'xml') return parseTbxText(await text(), file.name);
271
+ if(ext === 'xlsx' || ext === 'xls') return await parseXlsxFile(file);
272
+ if(ext === 'docx') return await parseGlossDocx(file);
273
+ if(ext === 'pdf') return await parseGlossPdf(file);
274
+ throw new Error('不支持的格式 .' + ext + '(支持 txt / csv / json / tbx / xml / xlsx / docx / pdf)');
275
+ }
276
+
277
+ // TXT:逐行索引解析
278
+ async function parseIndexText(text, name){
279
+ const entries = [];
280
+ const NOISE = /^(索引|目錄|目录|Index|INDEX|Contents|CONTENTS|附錄|附录|参考文献|人名索引|术语索引|名词索引|主題索引|主题索引|词条|詞條)$/i;
281
+ for(const line of text.split(/\r?\n/)){
282
+ const raw = line.trim();
283
+ if(NOISE.test(raw)) continue; // 标题/分组行
284
+ if(/^[A-Z]?$/.test(raw)) continue; // 字母分组行(A/B/C…)
285
+ const e = parseIndexLine(line);
286
+ if(e && (e.zh || e.foreign)){
287
+ // 无页码且无外文的超短纯中文行大概率是分组标题(如"德国观念论"),跳过
288
+ if(!(e.pages||[]).length && !e.foreign && e.zh.length <= 6 && zhRatio(e.zh) === 1 && !/[,,、]/.test(e.zh)) continue;
289
+ entries.push(e);
290
+ }
291
+ }
292
+ if(!entries.length) throw new Error('未识别出任何词条,请检查索引格式(每行一条:词目……页码)');
293
+ return { kind:'index', name, entries };
294
+ }
295
+
296
+ // CSV:列映射(src,dst,cat,note 或 外文,中文,类别,备注)
297
+ async function parseCsvText(text, name){
298
+ const rows = csvParse(text);
299
+ if(rows.length < 2) throw new Error('CSV 内容为空');
300
+ const head = rows[0].map(h => String(h||'').trim().toLowerCase());
301
+ // 自动猜列
302
+ const c = {
303
+ foreign: idxOf(head, ['src','外文','foreign','原文','term','en','english','德文','法文']),
304
+ zh: idxOf(head, ['dst','中文','zh','译名','中文译名','chinese','译文']),
305
+ cat: idxOf(head, ['cat','category','类别','分类','类型']),
306
+ note: idxOf(head, ['note','备注','说明','注释','note']),
307
+ pages: idxOf(head, ['pages','页码','页','page'])
308
+ };
309
+ const entries = [];
310
+ if(c.zh >= 0 || c.foreign >= 0){
311
+ for(const r of rows.slice(1)){
312
+ const zh = c.zh >= 0 ? (r[c.zh]||'').trim() : '';
313
+ const foreign = c.foreign >= 0 ? (r[c.foreign]||'').trim() : '';
314
+ if(!zh && !foreign) continue;
315
+ entries.push({ zh, foreign, cat: c.cat>=0 ? (r[c.cat]||'').trim() : '', note: c.note>=0 ? (r[c.note]||'').trim() : '', pages: c.pages>=0 ? String(r[c.pages]||'').split(/[,,,\s]+/).filter(x=>/^\d+$/.test(x)) : [], raw: r.join('|') });
316
+ }
317
+ } else {
318
+ // 无表头:按"每行一个词条(词目……页码)"解析
319
+ return parseIndexText(text, name);
320
+ }
321
+ if(!entries.length) throw new Error('CSV 未识别出数据行');
322
+ return { kind:'csv', name, entries, header: head };
323
+ }
324
+ function idxOf(arr, keys){ for(const k of keys){ const i = arr.indexOf(k); if(i >= 0) return i; } return -1; }
325
+ function csvParse(text){
326
+ const out = []; let row = [], cur = '', q = false;
327
+ for(let i=0;i<text.length;i++){
328
+ const ch = text[i];
329
+ if(q){
330
+ if(ch === '"'){ if(text[i+1] === '"'){ cur += '"'; i++; } else q = false; }
331
+ else cur += ch;
332
+ } else {
333
+ if(ch === '"') q = true;
334
+ else if(ch === ','){ row.push(cur); cur = ''; }
335
+ else if(ch === '\n'){ row.push(cur); out.push(row); row = []; cur = ''; }
336
+ else if(ch !== '\r') cur += ch;
337
+ }
338
+ }
339
+ if(cur || row.length){ row.push(cur); out.push(row); }
340
+ return out.filter(r => r.some(c => String(c).trim()));
341
+ }
342
+
343
+ // JSON:数组 [{src,dst,...}] 或 [{zh,foreign,...}]
344
+ async function parseJsonText(text, name){
345
+ let data;
346
+ try{ data = JSON.parse(text); }catch(e){ throw new Error('JSON 解析失败:' + e.message); }
347
+ if(!Array.isArray(data)) throw new Error('JSON 顶层必须是数组');
348
+ const entries = data.map(o => ({
349
+ zh: String(o.zh || o.dst || o['中文'] || o['译名'] || '').trim(),
350
+ foreign: String(o.foreign || o.src || o['外文'] || o['原文'] || '').trim(),
351
+ cat: String(o.cat || o['类别'] || o['类型'] || '').trim(),
352
+ note: String(o.note || o['备注'] || '').trim(),
353
+ pages: Array.isArray(o.pages) ? o.pages.map(String) : [],
354
+ raw: JSON.stringify(o).slice(0, 120)
355
+ })).filter(e => e.zh || e.foreign);
356
+ if(!entries.length) throw new Error('JSON 无有效词条');
357
+ return { kind:'json', name, entries };
358
+ }
359
+
360
+ // TBX:XML 解析 termEntry
361
+ async function parseTbxText(text, name){
362
+ const doc = new DOMParser().parseFromString(text, 'application/xml');
363
+ const tes = Array.from(doc.getElementsByTagName('termEntry'));
364
+ if(!tes.length) throw new Error('未找到 termEntry 节点(不是合法 TBX?)');
365
+ const entries = [];
366
+ for(const te of tes){
367
+ let zh = '', foreign = '';
368
+ const langSets = Array.from(te.children).filter(n => n.tagName === 'langSet');
369
+ for(const ls of langSets){
370
+ const lang = ls.getAttribute('xml:lang') || ls.getAttribute('lang') || '';
371
+ const terms = Array.from(ls.getElementsByTagName('term'));
372
+ const val = terms.length ? terms[0].textContent.trim() : '';
373
+ if(!val) continue;
374
+ if(/^zh/i.test(lang) || isZh(val)) zh = zh || val;
375
+ else foreign = foreign || val;
376
+ }
377
+ if(zh || foreign) entries.push({ zh, foreign, pages: [], raw: te.getAttribute('id') || '' });
378
+ }
379
+ if(!entries.length) throw new Error('TBX 内无有效词条');
380
+ return { kind:'tbx', name, entries };
381
+ }
382
+
383
+ // XLSX:SheetJS
384
+ async function parseXlsxFile(file){
385
+ await loadLib('XLSX', ['https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js', 'https://unpkg.com/xlsx@0.18.5/dist/xlsx.full.min.js']);
386
+ const wb = window.XLSX.read(await file.arrayBuffer(), { type:'array' });
387
+ const ws = wb.Sheets[wb.SheetNames[0]];
388
+ const rows = window.XLSX.utils.sheet_to_json(ws, { header:1, raw:false }).map(r => r.map(c => String(c==null?'':c).trim()));
389
+ if(rows.length < 2) throw new Error('Excel 数据为空');
390
+ const head = rows[0].map(h => h.toLowerCase());
391
+ const c = {
392
+ foreign: idxOf(head, ['外文','src','foreign','原文','term']),
393
+ zh: idxOf(head, ['中文','dst','zh','译名','中文译名']),
394
+ cat: idxOf(head, ['类别','cat','category','类型']),
395
+ note: idxOf(head, ['备注','note','说明'])
396
+ };
397
+ if(c.zh < 0 && c.foreign < 0) throw new Error('Excel 表头找不到「中文/外文」列,请用第一行为表头');
398
+ const entries = [];
399
+ for(const r of rows.slice(1)){
400
+ const zh = c.zh>=0 ? (r[c.zh]||'') : '';
401
+ const foreign = c.foreign>=0 ? (r[c.foreign]||'') : '';
402
+ if(!zh && !foreign) continue;
403
+ entries.push({ zh, foreign, cat: c.cat>=0?(r[c.cat]||''):'' , note: c.note>=0?(r[c.note]||''):'', pages: [], raw: r.join('|') });
404
+ }
405
+ if(!entries.length) throw new Error('Excel 未识别出数据行');
406
+ return { kind:'xlsx', name: file.name, entries, header: head };
407
+ }
408
+
409
+ // DOCX 索引:mammoth 转文本后逐行
410
+ async function parseGlossDocx(file){
411
+ const mammoth = await loadLib('mammoth', ['https://cdn.jsdelivr.net/npm/mammoth@1.8.0/mammoth.browser.min.js', 'https://unpkg.com/mammoth@1.8.0/mammoth.browser.min.js']);
412
+ const res = await mammoth.extractRawText({ arrayBuffer: await file.arrayBuffer() });
413
+ return parseIndexText(res.value || '', file.name);
414
+ }
415
+
416
+ // PDF 索引:pdf.js 抽文字后逐行
417
+ async function parseGlossPdf(file){
418
+ await loadLib('pdfjs', ['https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.min.js', 'https://unpkg.com/pdfjs-dist@3.11.174/build/pdf.min.js', 'https://cdn.bootcdn.net/ajax/libs/pdf.js/3.11.174/pdf.min.js', 'https://cdn.staticfile.org/pdf.js/3.11.174/pdf.min.js']);
419
+ if(!window.pdfjsLib.GlobalWorkerOptions.workerSrc){
420
+ window.pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdn.bootcdn.net/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
421
+ }
422
+ const pdf = await window.pdfjsLib.getDocument({ data: await file.arrayBuffer() }).promise;
423
+ let all = '';
424
+ for(let p=1;p<=pdf.numPages;p++){
425
+ const tc = await (await pdf.getPage(p)).getTextContent();
426
+ // 按 y 坐标分组成行
427
+ const lines = {};
428
+ for(const it of tc.items){
429
+ const y = Math.round(it.transform[5] / 4) * 4;
430
+ (lines[y] = lines[y] || []).push({ x: it.transform[4], s: it.str });
431
+ }
432
+ Object.keys(lines).sort((a,b)=>b-a).forEach(y => {
433
+ const line = lines[y].sort((a,b)=>a.x-b.x).map(o=>o.s).join(' ').trim();
434
+ if(line) all += line + '\n';
435
+ });
436
+ all += '\n';
437
+ }
438
+ return parseIndexText(all, file.name);
439
+ }
440
+
441
+ /* ═══════════ 智能扫描抽词(v4.17)═══════════
442
+ 用 LLM 从普通文章 / PDF / DOC / TXT 语义抽取术语,规避「把标题目录当术语」的低级错误 */
443
+ const SCAN_SYS = `你是专业的学术翻译术语整理助手。你的任务是从「待翻译的学术/专业文本」中提取需要统一译法的【专有术语】。
444
+
445
+ 【必须提取】人名、地名、机构名、著作/文章名、学派/主义/思潮名、专业概念术语、专有缩写与代号。
446
+ 【严格排除】章节标题、小标题、目录、页眉页脚、脚注/尾注编号、参考文献条目;普通名词与日常表达(如 "the"、"analysis"、"重要"、"因此");无术语价值的泛化词组。
447
+ 【输出格式】只输出一个 JSON 数组,不要任何解释、不要 Markdown 代码块围栏。每项形如:
448
+ {"foreign":"原文术语","zh":"标准译名(不确定则空字符串)","type":"人物/概念/著作/学派/机构/事件/其他","note":"简注或使用约束(可空)","conf":"high/mid/low"}
449
+ conf 表示把握度:high=确为术语且译名确定;mid=是术语但译名存疑;low=可能只是普通词、拿不准。`;
450
+
451
+ // 清洗 LLM 返回:剥离 markdown 围栏、定位首个 JSON 数组;解析失败则按对象逐个兜底
452
+ function extractJsonArray(text){
453
+ if(!text) return [];
454
+ let s = String(text).trim();
455
+ s = s.replace(/```(?:json|JSON)?/g, '').replace(/```/g, '');
456
+ const a = s.indexOf('['), b = s.lastIndexOf(']');
457
+ if(a < 0 || b <= a) return [];
458
+ try{ const j = JSON.parse(s.slice(a, b + 1)); return Array.isArray(j) ? j : []; }
459
+ catch(e){
460
+ const out = [], re = /\{[^{}]*\}/g; let m;
461
+ while((m = re.exec(s.slice(a, b + 1)))){ try{ out.push(JSON.parse(m[0])); }catch(_){} }
462
+ return out;
463
+ }
464
+ }
465
+
466
+ // 解析 LLM 返回的单个 JSON 对象(剥围栏、定位首 { 尾 })
467
+ function extractJsonObject(text){
468
+ if(!text) return null;
469
+ let s = String(text).trim();
470
+ s = s.replace(/```(?:json|JSON)?/g, '').replace(/```/g, '').trim();
471
+ const a = s.indexOf('{'), b = s.lastIndexOf('}');
472
+ if(a < 0 || b <= a) return null;
473
+ try{ const j = JSON.parse(s.slice(a, b + 1)); return (j && typeof j === 'object' && !Array.isArray(j)) ? j : null; }
474
+ catch(e){ return null; }
475
+ }
476
+
477
+ // 文本分块:按约 size 字切分,尽量在换行/句末断,避免截断术语
478
+ function splitChunks(text, size){
479
+ const chunks = []; let s = String(text || '').trim();
480
+ while(s.length > size){
481
+ let cut = s.lastIndexOf('\n', size);
482
+ if(cut < size * 0.5) cut = s.lastIndexOf('。', size);
483
+ if(cut < size * 0.5) cut = s.lastIndexOf('.', size);
484
+ if(cut < size * 0.5) cut = size;
485
+ chunks.push(s.slice(0, cut + 1));
486
+ s = s.slice(cut + 1).trim();
487
+ }
488
+ if(s) chunks.push(s);
489
+ return chunks;
490
+ }
491
+
492
+ // ── 集合(collection)辅助 ──
493
+ function newCollectionId(){ return 'c' + Date.now() + '_' + Math.floor(Math.random() * 1000); }
494
+ function getCollection(cid){ return GLOSS.collections.find(c => c.id === cid); }
495
+ // 术语是否命中「当前启用的集合」:未分组术语始终视为命中(向后兼容)
496
+ function termActive(t){
497
+ const cols = Array.isArray(t.collections) ? t.collections : [];
498
+ if(!cols.length) return true;
499
+ return cols.some(cid => { const c = getCollection(cid); return !c || c.enabled !== false; });
500
+ }
501
+
502
+ // 智能扫描主流程:解析文件 → 分块 → LLM 抽词 → 建集合 → 归一入库
503
+ async function smartScanFile(file, onProgress){
504
+ if(!CFG.apiKey){ toast('请先在「设置」页配置 API Key,再使用智能扫描', 'e'); throw new Error('no key'); }
505
+ if(onProgress) onProgress('解析文件…', 0.05);
506
+ const parsed = await parseFile(file, 'src', onProgress);
507
+ const text = (parsed.fullText || '').trim();
508
+ if(!text){ toast('未能从文件中提取到文字', 'e'); throw new Error('empty'); }
509
+ const chunks = splitChunks(text, 2500);
510
+ const all = []; const seen = new Set();
511
+ for(let i = 0; i < chunks.length; i++){
512
+ if(onProgress) onProgress('智能抽词 ' + (i + 1) + '/' + chunks.length + ' …', 0.1 + 0.85 * (i / chunks.length));
513
+ const r = await callModel(SCAN_SYS, '待翻译文本(片段):\n---\n' + chunks[i] + '\n---', null, 'gloss');
514
+ for(const e of extractJsonArray(r.text)){
515
+ if(!e || typeof e !== 'object') continue;
516
+ const foreign = String(e.foreign || '').trim();
517
+ const zh = String(e.zh || '').trim();
518
+ if(!foreign && !zh) continue;
519
+ const fk = foreign ? fKey(foreign) : ('zh:' + zh);
520
+ if(seen.has(fk)) continue;
521
+ seen.add(fk);
522
+ all.push({ foreign, zh, cat: e.type || '其他',
523
+ note: (e.note ? String(e.note).trim() : '') + (e.conf === 'low' ? '(低置信度,请人工确认)' : ''),
524
+ conf: e.conf || 'mid', pages: [] });
525
+ }
526
+ }
527
+ if(!all.length){ toast('未抽取出术语(文本可能不含专有术语)', 'e'); return { added: 0 }; }
528
+ const cid = newCollectionId();
529
+ const cname = (file.name || '扫描').replace(/\.[^.]+$/, '') || '扫描';
530
+ GLOSS.collections.push({ id: cid, name: cname, source: file.name, kind: 'scan', enabled: true, createdAt: Date.now(), note: '' });
531
+ const res = await glossIngest({ name: file.name, kind: 'scan', entries: all.map(e => ({ ...e, collections: [cid] })) });
532
+ // 高置信度且有译名 → 自动确认并推荐;其余留待人工审核
533
+ for(const e of all){
534
+ if(e.conf === 'high' && e.zh){
535
+ const hit = e.foreign
536
+ ? GLOSS.terms.find(t => t.foreign && fKey(t.foreign) === fKey(e.foreign))
537
+ : GLOSS.terms.find(t => t.zh === e.zh);
538
+ if(hit && hit.status === 'pending'){ hit.status = 'confirmed'; if(!hit.recommend) hit.recommend = 'rec'; }
539
+ }
540
+ }
541
+ const col = getCollection(cid); if(col) col.count = all.length;
542
+ saveGloss(); renderGloss();
543
+ return { added: res.added, merged: res.merged, cid, total: all.length };
544
+ }
545
+
546
+ // ── 归一化合并引擎:候选 entries → 入库 ──
547
+ // 外文比较键:忽略逗号/句点/空格/引号等标点差异(Hegel, G. W. F. == Hegel G. W. F.)
548
+ function fKey(s){ return String(s||'').toLowerCase().replace(/[,.\s'"()\[\]·-]+/g, ''); }
549
+ async function glossIngest(parsed){
550
+ const sid = 's' + Date.now();
551
+ GLOSS.sources.push({ id: sid, name: parsed.name, kind: parsed.kind, date: new Date().toISOString(), count: parsed.entries.length });
552
+ let added = 0, merged = 0, conflicts = 0, aliasAdded = 0;
553
+
554
+ for(const e of parsed.entries){
555
+ // 归一:繁→简、全半角
556
+ let zh = normText(await t2s(e.zh || ''));
557
+ let foreign = normText(e.foreign || '');
558
+ const pages = (e.pages || []).map(String);
559
+ if(!zh && !foreign) continue;
560
+
561
+ // 查找已有词条:外文比较键相同 → 合并(含大小写/标点差异)
562
+ let hit = null;
563
+ const fk = fKey(foreign);
564
+ if(fk){
565
+ hit = GLOSS.terms.find(t => t.foreign && fKey(t.foreign) === fk);
566
+ }
567
+ if(!hit && zh){
568
+ // 中文主词相同 且(对方无外文 或 外文一致)
569
+ hit = GLOSS.terms.find(t => t.zh === zh && (!t.foreign || !foreign || fKey(t.foreign) === fk));
570
+ }
571
+ if(hit){
572
+ // 合并:别名 / 来源 / 页码 / 备注
573
+ if(Array.isArray(e.collections)){ hit.collections = hit.collections || []; e.collections.forEach(c => { if(!hit.collections.includes(c)) hit.collections.push(c); }); }
574
+ if(zh && zh !== hit.zh && !(hit.aliases||[]).includes(zh)){ hit.aliases = hit.aliases || []; hit.aliases.push(zh); aliasAdded++; }
575
+ if(foreign && !hit.foreign) hit.foreign = foreign;
576
+ if(hit.sources.indexOf(sid) < 0) hit.sources.push(sid);
577
+ hit.occurrences = hit.occurrences || [];
578
+ if(pages.length) hit.occurrences.push({ sid, pages });
579
+ if(e.cat && !hit.type) hit.type = e.cat;
580
+ if(e.note && (hit.note||'').indexOf(e.note) < 0) hit.note = (hit.note ? hit.note + ';' : '') + e.note;
581
+ if(hit.status === 'confirmed' && foreign && hit.foreign && fKey(hit.foreign) !== fk){
582
+ hit.status = 'pending'; hit.note = (hit.note ? hit.note+';' : '') + '⚠ 外文冲突:' + hit.foreign + ' vs ' + foreign;
583
+ conflicts++;
584
+ }
585
+ hit.updated = Date.now();
586
+ merged++;
587
+ } else {
588
+ // 冲突检测:同中文主词、不同外文 → 仍新建但标记
589
+ const clash = zh ? GLOSS.terms.find(t => t.zh === zh && t.foreign && foreign && fKey(t.foreign) !== fk) : null;
590
+ const t = {
591
+ id: GID++, zh, foreign, aliases: [], type: e.cat || guessType(zh, foreign),
592
+ tags: [], note: e.note || (clash ? '⚠ 同名异源(外文不同):' + clash.foreign : ''),
593
+ sources: [sid], occurrences: pages.length ? [{ sid, pages }] : [],
594
+ collections: Array.isArray(e.collections) ? e.collections : [],
595
+ status: 'pending', recommend: '', created: Date.now(), updated: Date.now()
596
+ };
597
+ GLOSS.terms.push(t);
598
+ if(clash){ t.note = (t.note ? t.note + ';' : '') + '⚠ 同名异源:另一条外文为 ' + clash.foreign; conflicts++; }
599
+ added++;
600
+ }
601
+ }
602
+ saveGloss();
603
+ glossLog('import', 'source:' + sid, null, { name: parsed.name, added, merged, conflicts });
604
+ renderGloss();
605
+ return { added, merged, conflicts, aliasAdded };
606
+ }
607
+
608
+ // 类型自动猜测
609
+ function guessType(zh, foreign){
610
+ if(/《.+》/.test(zh || '')) return '著作';
611
+ const name = foreign || '';
612
+ // 人名模式:Xxx, Xxx. / Xxx Xxx(首字母大写两词以上、无小写概念词)
613
+ if(/^[A-ZÀ-Ý][a-zà-ÿ]+,\s*[A-ZÀ-Ý.]/.test(name)) return '人物';
614
+ if(/^[A-ZÀ-Ý][a-zà-ÿ]+(\s+[A-ZÀ-Ý][a-zà-ÿ]+)+$/.test(name) && !/^(the|being|not|with|and)\b/i.test(name)) return '人物';
615
+ return '概念';
616
+ }
617
+
618
+ // ── 自动标签规则引擎 ──
619
+ const DEF_RULES = [
620
+ { id:'r1', pattern:'Hegel|黑格尔', tag:'德国观念论', on:true },
621
+ { id:'r2', pattern:'Kant|康德', tag:'德国观念论', on:true },
622
+ { id:'r3', pattern:'Althusser|阿尔都塞', tag:'结构马克思主义', on:true },
623
+ { id:'r4', pattern:'Heidegger|海德格尔|Dasein|此在', tag:'现象学', on:true },
624
+ { id:'r5', pattern:'Husserl|胡塞尔|现象学', tag:'现象学', on:true },
625
+ { id:'r6', pattern:'Marx|马克思|资本|剩余价值|阶级|无产阶级', tag:'马克思主义', on:true },
626
+ { id:'r7', pattern:'Gramsci|葛兰西|霸权', tag:'西方马克思主义', on:true },
627
+ { id:'r8', pattern:'Lukács|卢卡奇|物化|总体性', tag:'西方马克思主义', on:true },
628
+ { id:'r9', pattern:'Derrida|德里达|解构', tag:'解构主义', on:true },
629
+ { id:'r10', pattern:'Foucault|福柯|谱系|规训', tag:'后结构主义', on:true }
630
+ ];
631
+ function ensureRules(){
632
+ if(!GLOSS.rules || !GLOSS.rules.length) GLOSS.rules = DEF_RULES.slice();
633
+ }
634
+ function applyAutoTags(term){
635
+ ensureRules();
636
+ let hit = 0;
637
+ const text = (term.zh + ' ' + term.foreign + ' ' + (term.aliases||[]).join(' '));
638
+ for(const r of GLOSS.rules){
639
+ if(r.on === false) continue;
640
+ try{
641
+ const re = new RegExp(r.pattern, 'i');
642
+ if(re.test(text) && (term.tags||[]).indexOf(r.tag) < 0){ term.tags = term.tags || []; term.tags.push(r.tag); hit++; }
643
+ }catch(_){}
644
+ }
645
+ return hit;
646
+ }
647
+ function applyAutoTagsAll(){
648
+ let n = 0;
649
+ GLOSS.terms.forEach(t => { n += applyAutoTags(t); });
650
+ if(n){ saveGloss(); renderGloss(); }
651
+ return n;
652
+ }