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,842 @@
1
+ /* ═══════════ P1:文档输入解析(docx / pdf / 图片)═══════════ */
2
+ // 模块级缓存:每个 side 一份解析结果
3
+ const __TP_FILES = { src:null, dst:null };
4
+
5
+ // CDN 加载器:首次访问某能力时按需懒加载
6
+ const __TP_LIBS = { mammoth:null, pdfjs:null, tesseract:null, loadPromise:{} };
7
+ async function loadLib(name, urls){
8
+ if(__TP_LIBS[name]) return __TP_LIBS[name];
9
+ if(__TP_LIBS.loadPromise[name]) return __TP_LIBS.loadPromise[name];
10
+ for(const url of urls){
11
+ try{
12
+ __TP_LIBS.loadPromise[name] = new Promise((res, rej)=>{
13
+ const s = document.createElement('script');
14
+ // 超时保护:证书错误等场景下 onerror 可能不触发,超时兜底避免卡死
15
+ const timer = setTimeout(() => { s.remove(); rej(new Error('加载超时:' + url)); }, 10000);
16
+ s.src = url;
17
+ s.onload = () => { clearTimeout(timer); res(window[name]); };
18
+ s.onerror = () => { clearTimeout(timer); rej(new Error('加载失败:' + url)); };
19
+ document.head.appendChild(s);
20
+ });
21
+ __TP_LIBS[name] = await __TP_LIBS.loadPromise[name];
22
+ return __TP_LIBS[name];
23
+ }catch(e){
24
+ __TP_LIBS.loadPromise[name] = null; // 失败后清除缓存,允许下次重试
25
+ }
26
+ }
27
+ throw new Error('无法加载库 ' + name);
28
+ }
29
+
30
+ // ── Tesseract 路径多源解析:worker/core/lang 默认全指 jsdelivr,被墙时
31
+ // worker 加载失败会以 undefined 拒绝(→「解析失败undefined」),lang 下载失败会永久挂起 ──
32
+ const TESS_CANDIDATES = {
33
+ workerPath: [
34
+ 'https://unpkg.com/tesseract.js@5.1.0/dist/worker.min.js',
35
+ 'https://registry.npmmirror.com/tesseract.js/5.1.0/files/dist/worker.min.js',
36
+ 'https://cdn.jsdelivr.net/npm/tesseract.js@v5.1.0/dist/worker.min.js'
37
+ ],
38
+ corePath: [
39
+ 'https://unpkg.com/tesseract.js-core@5.1.0',
40
+ 'https://registry.npmmirror.com/tesseract.js-core/5.1.0/files',
41
+ 'https://cdn.jsdelivr.net/npm/tesseract.js-core@v5.1.0'
42
+ ]
43
+ };
44
+ const TESS_STATUS_ZH = {
45
+ 'loading tesseract core':'下载OCR内核',
46
+ 'loading language data':'下载OCR语言包',
47
+ 'initializing tesseract':'初始化OCR',
48
+ 'recognizing text':'OCR识别中'
49
+ };
50
+ async function tpReachable(url){
51
+ // Range/cors 都不加:普通 GET 拿到响应头即 cancel,避开预检且只拉几 KB
52
+ const ctl = (typeof AbortController !== 'undefined') ? new AbortController() : null;
53
+ const timer = setTimeout(() => { try{ ctl && ctl.abort(); }catch(_){} }, 8000);
54
+ try{
55
+ const r = await fetch(url, { cache:'no-store', signal: ctl ? ctl.signal : undefined });
56
+ if(r.body){ try{ await r.body.cancel(); }catch(_){} }
57
+ return r.ok || r.status === 206;
58
+ }catch(_){ return false; }
59
+ finally{ clearTimeout(timer); }
60
+ }
61
+ async function tpTessPaths(){
62
+ if(__TP_LIBS.tessPaths) return __TP_LIBS.tessPaths;
63
+ const probeOne = async (list, suffix) => {
64
+ for(const base of list){
65
+ if(await tpReachable(base + suffix)) return base;
66
+ }
67
+ return list[0]; // 全挂也别挡路:真实下载还有一线机会,超时看门狗兜底
68
+ };
69
+ // langPath 语义 = 含平铺 <lang>.traineddata.gz 的目录(单值服务所有语言,
70
+ // npm 的每语言分包布局拼不出来)→ 语言包随应用同源自带,探不到则不传、
71
+ // 回落厂商默认的 jsdelivr 每语言布局
72
+ const originDir = new URL('.', location.href).href.replace(/\/$/, '');
73
+ const [workerPath, corePath, langOk] = await Promise.all([
74
+ probeOne(TESS_CANDIDATES.workerPath, ''),
75
+ probeOne(TESS_CANDIDATES.corePath, '/tesseract-core-simd-lstm.wasm.js'),
76
+ Promise.all([
77
+ tpReachable(originDir + '/chi_sim.traineddata.gz'),
78
+ tpReachable(originDir + '/eng.traineddata.gz')
79
+ ]).then(r => r.every(Boolean))
80
+ ]);
81
+ __TP_LIBS.tessPaths = { workerPath, corePath, langPath: langOk ? originDir : undefined };
82
+ return __TP_LIBS.tessPaths;
83
+ }
84
+ // 统一 OCR 入口:多源主脚本 + 镜像路径探测 + 240s 看门狗(语言包下载失败会静默挂起)
85
+ async function tpRecognize(image, onOcrProgress){
86
+ await loadLib('Tesseract', [
87
+ 'https://unpkg.com/tesseract.js@5.1.0/dist/tesseract.min.js',
88
+ 'https://registry.npmmirror.com/tesseract.js/5.1.0/files/dist/tesseract.min.js',
89
+ 'https://cdn.jsdelivr.net/npm/tesseract.js@5.1.0/dist/tesseract.min.js'
90
+ ]);
91
+ const p = await tpTessPaths();
92
+ let timer;
93
+ const watchdog = new Promise((_, rej) => {
94
+ timer = setTimeout(() => rej(new Error('OCR 数据下载超时(语言包/内核),请检查网络后重试')), 240000);
95
+ });
96
+ try{
97
+ return await Promise.race([
98
+ window.Tesseract.recognize(image, 'chi_sim+eng', {
99
+ logger: m => {
100
+ if(onOcrProgress && m && typeof m.progress === 'number' && TESS_STATUS_ZH[m.status || '']){
101
+ onOcrProgress(m);
102
+ }
103
+ },
104
+ errorHandler: e => console.warn('tesseract:', e), // 否则 job 失败会在 onmessage 里 throw Error(event)
105
+ workerPath: p.workerPath,
106
+ corePath: p.corePath,
107
+ langPath: p.langPath
108
+ }),
109
+ watchdog
110
+ ]);
111
+ } finally{ clearTimeout(timer); }
112
+ }
113
+ // 错误文案兜底:worker onerror 抛的 event.message 是 undefined,直接展示会是「解析失败undefined」
114
+ function errMsg(e){
115
+ if(e == null) return '未知错误';
116
+ if(typeof e === 'string') return e || '未知错误';
117
+ if(e.message) return e.message;
118
+ if(e.type) return 'OCR/解析内部错误(' + e.type + ')';
119
+ try{ return JSON.stringify(e); }catch(_){ return String(e); }
120
+ }
121
+
122
+ // config.js 钩子:TP_FILE_HOOKS 允许朋友重写某个解析器
123
+ const TP_FILE_HOOKS = (window.TP_CONFIG && window.TP_CONFIG.fileHooks) || {};
124
+
125
+ // 主入口:file → 统一结构
126
+ async function parseFile(file, side, onProgress){
127
+ const ext = (file.name||'').split('.').pop().toLowerCase();
128
+ const hook = TP_FILE_HOOKS[side === 'src' ? 'parseSrc' : 'parseDst'];
129
+ if(hook){ return await hook(file, ext, onProgress); }
130
+ if(ext === 'docx') return await parseDocx(file, onProgress);
131
+ if(ext === 'pdf') return await parsePdf(file, onProgress);
132
+ if(/^(png|jpe?g|webp|gif|bmp|tiff?)$/.test(ext)) return await parseImage(file, onProgress);
133
+ if(/^(txt|md|markdown)$/.test(ext)) {
134
+ // 纯文本:直接读,转成 docx 兼容结构供下游统一处理
135
+ const text = await file.text();
136
+ return {
137
+ kind: 'txt',
138
+ fileName: file.name,
139
+ chapters: [{ title: '全文', text }],
140
+ fullText: text,
141
+ hasImages: false
142
+ };
143
+ }
144
+ throw new Error('暂不支持的文件格式:' + ext + '(仅支持 .docx / .pdf / 图片 / .txt / .md)');
145
+ }
146
+
147
+ // ── Docx 解析 ──
148
+ async function parseDocx(file, onProgress){
149
+ if(onProgress) onProgress('加载 mammoth…', 0.1);
150
+ // 用 loadLib 返回值(缓存命中时 window.mammoth 可能不存在)
151
+ const mammoth = await loadLib('mammoth', [
152
+ 'https://registry.npmmirror.com/mammoth/1.8.0/files/mammoth.browser.min.js',
153
+ 'https://cdn.jsdelivr.net/npm/mammoth@1.8.0/mammoth.browser.min.js',
154
+ 'https://unpkg.com/mammoth@1.8.0/mammoth.browser.min.js'
155
+ ]);
156
+ if(onProgress) onProgress('读取 docx…', 0.4);
157
+ // 纯文本:mammoth 直接搞定
158
+ const txtRes = await mammoth.extractRawText({ arrayBuffer: await file.arrayBuffer() });
159
+ const allText = txtRes.value || '';
160
+ // 章节切分:解析 HTML 版(保留段落结构与 pStyle),按 H1/H2 切
161
+ if(onProgress) onProgress('分析章节…', 0.7);
162
+ const htmlRes = await mammoth.convertToHtml({ arrayBuffer: await file.arrayBuffer() });
163
+ const chapters = splitDocxChapters(htmlRes.value);
164
+ if(onProgress) onProgress('完成', 1);
165
+ return {
166
+ kind:'docx',
167
+ fileName:file.name,
168
+ chapters: chapters.length ? chapters : [{ title:'全文', text:allText }],
169
+ fullText: allText,
170
+ hasImages: /<img\b/i.test(htmlRes.value)
171
+ };
172
+ }
173
+
174
+ // 用 DOMParser 解析 mammoth 输出的 HTML,按 <h1> 切章节,<h2> 作为标题前缀
175
+ function splitDocxChapters(html){
176
+ const doc = new DOMParser().parseFromString(html, 'text/html');
177
+ const chapters = []; let cur = { title:'引言', text:'', sub:'' };
178
+ function flush(){
179
+ const combined = (cur.title + (cur.sub ? ' · '+cur.sub : '')).trim() || '(未命名章节)';
180
+ if(cur.text.trim()){ chapters.push({ title: combined, text: cur.text.trim() }); }
181
+ cur = { title:'', text:'', sub:'' };
182
+ }
183
+ doc.body.childNodes.forEach(n => {
184
+ if(n.nodeType !== 1) return;
185
+ const tag = n.tagName.toLowerCase();
186
+ if(tag === 'h1'){ flush(); cur.title = (n.textContent||'').trim(); }
187
+ else if(tag === 'h2'){ cur.sub = (n.textContent||'').trim(); }
188
+ else { cur.text += (n.textContent||'').trim() + '\n\n'; }
189
+ });
190
+ flush();
191
+ return chapters.length ? chapters : [{ title:'全文', text:(doc.body.textContent||'').trim() }];
192
+ }
193
+
194
+ // v4.21.3:pdf.js 文本项按 Y 坐标分组成行,行内按 X 排序、ASCII 单词边界补空格。
195
+ // 原实现 join(' ') 把整页拍成一行 → 源文件换行全丢(AI 无结构可保留,粘贴进 Word 不断行)。
196
+ // v4.22.0 版面分析:逐项保留高度与坐标(注释标号/脚注区检测要用)。
197
+ // 行聚合按 y 聚簇(容忍 5pt 内基线差):上标通常比正文基线高 3-5pt,
198
+ // 旧的 /4*4 取整会把上标数字拆成独立一行,标号与正文就断开了。
199
+ function pdfLineObjs(tc){
200
+ const items = [];
201
+ for(const it of ((tc && tc.items) || [])){
202
+ if(!(it.str || '')) continue;
203
+ const tr = it.transform || [1,0,0,1,0,0];
204
+ items.push({ x: tr[4], y: tr[5], s: it.str, h: Math.abs(it.height || 0) || Math.hypot(tr[2], tr[3]) || 0 });
205
+ }
206
+ items.sort((a,b) => b.y - a.y); // y 大 = 页面上方
207
+ const lines = [];
208
+ for(const it of items){
209
+ const cur = lines[lines.length - 1];
210
+ if(cur && (cur.anchorY - it.y) <= 5 && (cur.anchorY - it.y) >= 0) cur.items.push(it);
211
+ else lines.push({ anchorY: it.y, items: [it] });
212
+ }
213
+ return lines.map(L => {
214
+ L.items.sort((a,b) => a.x - b.x);
215
+ L.y = L.anchorY;
216
+ L.h = L.items.reduce((m,o) => Math.max(m, o.h || 0), 0);
217
+ return L;
218
+ });
219
+ }
220
+ function lineJoin(L){
221
+ return (L.items || []).reduce((acc, o) => {
222
+ const s = o.s || '';
223
+ if(!s) return acc;
224
+ if(acc && !/\s$/.test(acc) && !/^\s/.test(s) && /[A-Za-z0-9]$/.test(acc) && /^[A-Za-z0-9]/.test(s)) return acc + ' ' + s;
225
+ return acc + s;
226
+ }, '').trim();
227
+ }
228
+ function pdfTextLines(tc){
229
+ return pdfLineObjs(tc).map(lineJoin).filter(s => s.length);
230
+ }
231
+ /* 正文字号:取最长文本行的高度(正文行长 > 脚注行;标题虽大但短) */
232
+ function calcBodyH(lines){
233
+ let best = 0, bestLen = 0;
234
+ for(const L of lines){
235
+ if(!(L.h > 0)) continue;
236
+ const len = lineJoin(L).length;
237
+ if(len > bestLen){ bestLen = len; best = L.h; }
238
+ }
239
+ if(best) return best;
240
+ return lines.reduce((m,L) => Math.max(m, L.h || 0), 0) || 12;
241
+ }
242
+ /* 标号包胶:小字号纯数字(上标标号)→ [n],让 AI 与贴注都能对上号。
243
+ 顺手吃掉标号前的独立空格项(pdf.js 会在 run 间吐 ' ' 项,标号按惯例贴附前词)。 */
244
+ function wrapMarkers(L, bodyH){
245
+ const items = L.items || [];
246
+ const out = [];
247
+ for(let i = 0; i < items.length; i++){
248
+ const o = items[i];
249
+ const t = (o.s || '').trim();
250
+ if(t && /^\d{1,3}$/.test(t) && o.h > 0 && bodyH > 0 && o.h < bodyH * 0.85){
251
+ while(out.length && !String(out[out.length - 1].s || '').trim()) out.pop();
252
+ out.push({ s: '[' + t + ']' });
253
+ } else out.push(o);
254
+ }
255
+ return lineJoin({ items: out });
256
+ }
257
+ const H_END = /^\s*(注释|注解|尾注|脚注|注脚|译注|校注|Notes|Footnotes|Endnotes|Annotations)\s*[::]?\s*$/i;
258
+ const H_STOP = /^(参考文献|文献目录|Bibliography|References|索引|Index|附录|Appendix|致谢|Acknowledg)/;
259
+ const RE_ENTRY = /^\s*[\[[((]?([0-9]{1,3}|[*†‡§])[\]]))]?[..、)]?\s*(\S.*)$/;
260
+ const RE_ENTRY_START = /^\s*(\[\d{1,3}\]|\(\d{1,3}\)|\d{1,3}[.)\s]|[*†‡])/;
261
+ /* 从 start 起解析注释条目:编号须递增才算新条目(正文数字行不误收),其余行并入当前条目。
262
+ 遇到停止标题(参考文献等)返回 stopIdx,让调用方把之后的行还给正文。 */
263
+ function parseNoteEntries(lines, start, join){
264
+ const out = [];
265
+ let cur = null, expected = null, stopIdx = -1;
266
+ for(let i = start; i < lines.length; i++){
267
+ const s = join(lines[i]);
268
+ if(!s) continue;
269
+ if(H_STOP.test(s)){ stopIdx = i; break; }
270
+ if(H_END.test(s)){ if(cur){ out.push(cur); cur = null; } continue; }
271
+ const m = s.match(RE_ENTRY);
272
+ if(m){
273
+ const raw = m[1];
274
+ const num = /^[0-9]+$/.test(raw) ? parseInt(raw, 10) : null;
275
+ const ok = num === null ? out.length < 400 : (expected === null ? num <= 400 : num === expected);
276
+ if(ok){
277
+ if(cur) out.push(cur);
278
+ cur = { n: raw, text: m[2] };
279
+ if(num !== null) expected = num + 1;
280
+ continue;
281
+ }
282
+ }
283
+ if(cur) cur.text += ' ' + s; // 条目续行
284
+ }
285
+ if(cur) out.push(cur);
286
+ return { entries: out, stopIdx };
287
+ }
288
+ /* 页底脚注区起点:优先找分隔线(页面下 60% 的纯横线/点线行),否则找页底小字号条目行。
289
+ 返回首个脚注行下标,没找到返回 -1。bodyH=0 表示无版面信息(OCR 行),只走分隔线支路。 */
290
+ function detectFootBlock(lines, bodyH, pageH){
291
+ if(!lines || lines.length < 2) return -1;
292
+ let start = -1;
293
+ for(let i = lines.length - 1; i >= Math.floor(lines.length * 0.4); i--){
294
+ const s = lineJoin(lines[i]);
295
+ if(s && s.length <= 40 && /^[\s\-–—_·.=*•]+$/.test(s) && /[-–—_·.]/.test(s)){ start = i; break; }
296
+ }
297
+ if(start < 0 && bodyH > 0){
298
+ for(let i = 0; i < lines.length; i++){
299
+ const L = lines[i];
300
+ if(L.y < pageH * 0.45 && L.h > 0 && L.h < bodyH * 0.78 && RE_ENTRY_START.test(lineJoin(L))){ start = i; break; }
301
+ }
302
+ }
303
+ if(start >= 0 && bodyH > 0){
304
+ let hit = 0;
305
+ for(let i = start; i < lines.length; i++){
306
+ const L = lines[i];
307
+ if((L.h > 0 && L.h < bodyH * 0.85) || RE_ENTRY_START.test(lineJoin(L))) hit++;
308
+ }
309
+ if(!hit) return -1;
310
+ }
311
+ return start;
312
+ }
313
+ /* 从输出/译文中抽出注释标号集合:[1]、(1)、(1)、上标 ¹²³⁴… */
314
+ function markersIn(text){
315
+ const SUP = { '⁰':'0','¹':'1','²':'2','³':'3','⁴':'4','⁵':'5','⁶':'6','⁷':'7','⁸':'8','⁹':'9' };
316
+ const set = new Set();
317
+ const re = /[\[[((]\s*(\d{1,3}|[a-hA-H])\s*[\]]))]|[⁰¹²³⁴⁵⁶⁷⁸⁹]/g;
318
+ let m;
319
+ while((m = re.exec(text || '')) !== null) set.add(m[1] || SUP[m[0]] || m[0]);
320
+ return set;
321
+ }
322
+
323
+ // ── PDF 解析(自动判别文字型 vs 扫描件)──
324
+ async function parsePdf(file, onProgress){
325
+ if(onProgress) onProgress('加载 pdf.js…', 0.05);
326
+ await loadLib('pdfjs', [
327
+ 'https://registry.npmmirror.com/pdfjs-dist/3.11.174/files/build/pdf.min.js',
328
+ 'https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.min.js',
329
+ 'https://unpkg.com/pdfjs-dist@3.11.174/build/pdf.min.js',
330
+ 'https://cdn.bootcdn.net/ajax/libs/pdf.js/3.11.174/pdf.min.js',
331
+ 'https://cdn.staticfile.org/pdf.js/3.11.174/pdf.min.js'
332
+ ]);
333
+ // 配置 worker(pdfjs 3.x 用 pdfjsLib 全局)
334
+ if(!window.pdfjsLib.GlobalWorkerOptions.workerSrc){
335
+ window.pdfjsLib.GlobalWorkerOptions.workerSrc =
336
+ 'https://registry.npmmirror.com/pdfjs-dist/3.11.174/files/build/pdf.worker.min.js';
337
+ }
338
+ if(onProgress) onProgress('读取 PDF…', 0.2);
339
+ const buf = await file.arrayBuffer();
340
+ const pdf = await window.pdfjsLib.getDocument({ data:buf }).promise;
341
+ const total = pdf.numPages;
342
+ let allText = '';
343
+ const chapterMap = []; let curChap = { title:'全部页面', text:'', pageStart:1, pageEnd:total };
344
+
345
+ // outline 章节
346
+ let outline = null;
347
+ try { outline = await pdf.getOutline(); } catch(_){}
348
+ if(outline && outline.length){
349
+ // 把每个 outline 项解析成 [startPage]
350
+ const pageChap = [];
351
+ for(const o of outline){
352
+ if(o.items && o.items.length) continue; // 仅顶层
353
+ let p = 1;
354
+ try{
355
+ if(typeof o.dest === 'string'){
356
+ const pageIdx = await pdf.getPageIndex(o.dest);
357
+ p = pageIdx + 1;
358
+ } else if(Array.isArray(o.dest) && o.dest[0]){
359
+ const ref = pdf.doc?.catalog?.get(o.dest[0]) || o.dest[0];
360
+ // 直接用 PDF.js 解析
361
+ const pageIdx = await pdf.getPageIndex(ref);
362
+ p = pageIdx + 1;
363
+ }
364
+ }catch(_){}
365
+ pageChap.push({ title:o.title, page:p });
366
+ }
367
+ pageChap.sort((a,b)=>a.page-b.page).forEach((c,i,arr) => {
368
+ c.pageEnd = (arr[i+1] && arr[i+1].page>1) ? arr[i+1].page-1 : total;
369
+ });
370
+ pageChap.forEach(c => chapterMap.push({ title:c.title.replace(/[^\x20-\x7E\u00A0-\u024F\u3000-\u303F\uFF00-\uFFEF一-鿿㐀-䶿가-힯]/g,'').trim() || '第'+c.page+'页', text:'', pageStart:c.page, pageEnd:c.pageEnd }));
371
+ }
372
+
373
+ // 逐页解析:先抽文字层;文字层几乎为空 → 该页单独 OCR(堵住混合型 PDF 漏页)
374
+ let ocrPages = 0;
375
+ const scanReport = [];
376
+ const notes = []; // v4.22.0 提取的注释条目(页底脚注 foot + 文末尾注 end)
377
+ let inEndnotes = false; // 已进入文末尾注区(跨页状态)
378
+ for(let p=1; p<=total; p++){
379
+ if(onProgress) onProgress('解析第 '+p+' / '+total+' 页…', 0.2 + 0.75*p/total);
380
+ const page = await pdf.getPage(p);
381
+ const tc = await page.getTextContent();
382
+ const notesBefore = notes.length;
383
+ const lineObjs = pdfLineObjs(tc);
384
+ const bodyH = calcBodyH(lineObjs);
385
+ let pageH = 792; try{ pageH = page.getViewport({ scale:1 }).height; }catch(_){}
386
+ // v4.22.0:脚注区/尾注区检测——注释条目进 notes,正文只留标号不留注释文本
387
+ const footStart = detectFootBlock(lineObjs, bodyH, pageH);
388
+ let bodyEnd = footStart >= 0 ? footStart : lineObjs.length;
389
+ let endStart = -1;
390
+ if(inEndnotes){ endStart = 0; bodyEnd = 0; }
391
+ else {
392
+ const hi = lineObjs.findIndex(L => H_END.test(lineJoin(L)));
393
+ if(hi >= 0 && p > 1){ inEndnotes = true; endStart = hi + 1; bodyEnd = Math.min(bodyEnd, hi); }
394
+ }
395
+ let endRest = [];
396
+ if(footStart >= 0){
397
+ parseNoteEntries(lineObjs, footStart, lineJoin).entries.forEach(e => notes.push({ n:e.n, text:e.text, page:p, kind:'foot' }));
398
+ }
399
+ if(endStart >= 0){
400
+ const r = parseNoteEntries(lineObjs, endStart, lineJoin);
401
+ r.entries.forEach(e => notes.push({ n:e.n, text:e.text, page:p, kind:'end' }));
402
+ if(r.stopIdx >= 0){ inEndnotes = false; endRest = lineObjs.slice(r.stopIdx); } // 停止标题(参考文献等)之后归还正文
403
+ }
404
+ // v4.21.3:按行保留源文换行(原 join 全页拍平成一行);v4.22.0:上标标号包胶成 [n]
405
+ let pageText = lineObjs.slice(0, bodyEnd).map(L => wrapMarkers(L, bodyH)).filter(s => s.length).join('\n')
406
+ .replace(/[^\n\x20-\x7E\u00A0-\u024F\u3000-\u303F\uFF00-\uFFEF一-鿿㐀-䶿가-힯]/g, '')
407
+ .replace(/ {3,}/g, ' ')
408
+ .trim();
409
+ if(endRest.length){
410
+ const rt = endRest.map(L => wrapMarkers(L, bodyH)).filter(s => s.length).join('\n');
411
+ if(rt) pageText = (pageText ? pageText + '\n' : '') + rt;
412
+ }
413
+ const gotNewNotes = notes.length > notesBefore;
414
+ let method = '文本层', conf = null;
415
+ if(pageText.replace(/\s/g, '').length < 8 && !gotNewNotes){
416
+ // 文字层缺失/极少 → 该页按扫描页单独 OCR
417
+ method = 'OCR'; ocrPages++;
418
+ if(onProgress) onProgress('第 '+p+' 页无文字层,OCR 识别…', 0.2 + 0.75*p/total);
419
+ const ocr = await ocrPdfPage(page, m => {
420
+ if(onProgress) onProgress('第 '+p+' 页无文字层 · ' + (TESS_STATUS_ZH[m.status] || m.status) + ' ' + Math.round(m.progress*100) + '%', 0.2 + 0.75*p/total);
421
+ });
422
+ pageText = ocr.text; conf = ocr.conf;
423
+ // v4.22.0 OCR 页没有字号信息:只做分隔线/尾注标题级检测,正文切掉注释区
424
+ const oLines = (pageText || '').split('\n').map(s => ({ y:0, h:0, items:[{ x:0, s, h:0 }] }));
425
+ const oFoot = detectFootBlock(oLines, 0, pageH);
426
+ let oStart = -1, oCut = -1;
427
+ if(inEndnotes){ oStart = 0; oCut = 0; }
428
+ else {
429
+ const hi = oLines.findIndex(L => H_END.test(lineJoin(L)));
430
+ if(hi >= 0 && p > 1){ inEndnotes = true; oStart = hi + 1; oCut = hi; }
431
+ }
432
+ let cut = oLines.length;
433
+ if(oFoot >= 0) cut = Math.min(cut, oFoot);
434
+ if(oCut >= 0) cut = Math.min(cut, oCut);
435
+ if(oFoot >= 0){
436
+ parseNoteEntries(oLines, oFoot, lineJoin).entries.forEach(e => notes.push({ n:e.n, text:e.text, page:p, kind:'foot' }));
437
+ }
438
+ if(oStart >= 0){
439
+ const r = parseNoteEntries(oLines, oStart, lineJoin);
440
+ r.entries.forEach(e => notes.push({ n:e.n, text:e.text, page:p, kind:'end' }));
441
+ if(r.stopIdx >= 0){ inEndnotes = false; oLines._rest = oLines.slice(r.stopIdx).map(L => lineJoin(L)).filter(s => s.length).join('\n'); }
442
+ }
443
+ if(cut < oLines.length || cut === 0){
444
+ pageText = oLines.slice(0, cut).map(L => lineJoin(L)).filter(s => s.length).join('\n');
445
+ }
446
+ if(oLines._rest) pageText = (pageText ? pageText + '\n' : '') + oLines._rest;
447
+ if(!pageText.replace(/\s/g, '') && notes.length > notesBefore) method = '注释页';
448
+ }
449
+ else if(gotNewNotes && pageText.replace(/\s/g, '').length < 8){ method = '注释页'; }
450
+ scanReport.push({ page:p, method, chars:(pageText||'').length, conf });
451
+ allText += '\n\n[第 '+p+' 页]\n' + (pageText || '(空白)') + '\n';
452
+ // 按页范围归到章节
453
+ const ch = chapterMap.find(c => p >= c.pageStart && p <= c.pageEnd);
454
+ if(ch) ch.text += (pageText || '') + '\n\n';
455
+ }
456
+
457
+ if(!chapterMap.length){
458
+ // 无 outline:用"第N章"正则硬切
459
+ const hard = splitTextByChapterKeywords(allText);
460
+ chapterMap.push(...hard);
461
+ }
462
+ if(onProgress) onProgress('完成', 1);
463
+ return {
464
+ kind: ocrPages === total ? 'pdf-scan' : (ocrPages > 0 ? 'pdf-mixed' : 'pdf-text'),
465
+ fileName:file.name,
466
+ chapters: chapterMap.map(c => ({ title:c.title, text:c.text.trim(), pageStart:c.pageStart, pageEnd:c.pageEnd })).filter(c => c.text),
467
+ fullText: allText.trim(),
468
+ hasImages: ocrPages > 0,
469
+ scanReport,
470
+ notes // v4.22.0 注释条目(贴注功能数据源)
471
+ };
472
+ }
473
+
474
+ function splitTextByChapterKeywords(text){
475
+ // 兜底:用"第 N 章"或大写罗马数字切
476
+ const out = [{ title:'前言', text:'' }];
477
+ const re = /\n\s*(第\s*[一二三四五六七八九十百千零0-9]+\s*章[^\n]*|Chapter\s+\d+[^\n]*|CHAPTER\s+[IVXLCDM]+[^\n]*)\n/g;
478
+ let last = 0, m;
479
+ while((m = re.exec(text))){
480
+ out[out.length-1].text = text.slice(last, m.index).trim();
481
+ out.push({ title:m[1].trim(), text:'' });
482
+ last = m.index + m[0].length;
483
+ }
484
+ out[out.length-1].text = text.slice(last).trim();
485
+ return out.filter(c => c.text);
486
+ }
487
+
488
+ // 单页 OCR(混合型 PDF 用):渲染一页成图 → tesseract 识别,返回文字与置信度
489
+ async function ocrPdfPage(page, onOcrProgress){
490
+ const viewport = page.getViewport({ scale: 2.0 });
491
+ const canvas = document.createElement('canvas');
492
+ canvas.width = viewport.width; canvas.height = viewport.height;
493
+ const ctx = canvas.getContext('2d');
494
+ await page.render({ canvasContext: ctx, viewport }).promise;
495
+ const blob = await new Promise(r => canvas.toBlob(r, 'image/png'));
496
+ const { data } = await tpRecognize(blob, onOcrProgress);
497
+ return { text: (data.text || '').trim(), conf: typeof data.confidence === 'number' ? Math.round(data.confidence) : null };
498
+ }
499
+
500
+ // PDF 扫描件:把每页渲染成图片 → tesseract.js OCR
501
+ async function parsePdfAsScan(file, pdf, total, onProgress){
502
+ if(onProgress) onProgress('加载 OCR…', 0.1);
503
+ const ocrAll = [];
504
+ for(let p=1; p<=total; p++){
505
+ if(onProgress) onProgress('OCR 第 '+p+' / '+total+' 页…', 0.1 + 0.85*p/total);
506
+ const page = await pdf.getPage(p);
507
+ const viewport = page.getViewport({ scale:2.0 });
508
+ const canvas = document.createElement('canvas');
509
+ canvas.width = viewport.width; canvas.height = viewport.height;
510
+ const ctx = canvas.getContext('2d');
511
+ await page.render({ canvasContext:ctx, viewport }).promise;
512
+ const blob = await new Promise(r => canvas.toBlob(r, 'image/png'));
513
+ const { data:{ text } } = await tpRecognize(blob, m => {
514
+ if(onProgress) onProgress('OCR 第 '+p+' / '+total+' 页 · ' + (TESS_STATUS_ZH[m.status] || m.status) + ' ' + Math.round(m.progress*100) + '%', 0.1 + 0.85*p/total);
515
+ });
516
+ ocrAll.push({ page:p, text: (text||'').trim() });
517
+ }
518
+ if(onProgress) onProgress('完成', 1);
519
+ return {
520
+ kind:'pdf-scan',
521
+ fileName:file.name,
522
+ chapters: ocrAll.map(o => ({ title:'第 '+o.page+' 页', text:o.text })),
523
+ fullText: ocrAll.map(o => '【第 '+o.page+' 页】\n'+o.text).join('\n\n'),
524
+ hasImages: true
525
+ };
526
+ }
527
+
528
+ // ── 图片输入解析(直接 OCR)──
529
+ async function parseImage(file, onProgress){
530
+ if(onProgress) onProgress('加载 OCR…', 0.1);
531
+ const { data:{ text } } = await tpRecognize(file, m => {
532
+ if(onProgress) onProgress((TESS_STATUS_ZH[m.status] || m.status) + ' ' + Math.round(m.progress*100) + '%', 0.4 + 0.55*(m.progress || 0));
533
+ });
534
+ if(onProgress) onProgress('完成', 1);
535
+ return {
536
+ kind:'image',
537
+ fileName:file.name,
538
+ chapters:[{ title:file.name, text:(text||'').trim() }],
539
+ fullText:(text||'').trim(),
540
+ hasImages:true
541
+ };
542
+ }
543
+
544
+ // ── UI 渲染 ──
545
+ function renderFileBar(side){
546
+ const bar = $('#'+side+'FileBar'); if(!bar) return;
547
+ const data = __TP_FILES[side];
548
+ bar.innerHTML = '';
549
+ if(!data){
550
+ bar.classList.remove('has-file');
551
+ const btn = document.createElement('button');
552
+ btn.className = 'btn gray'; btn.id = 'btn-'+side+'-file'; btn.textContent = '📂 上传' + (side==='src'?'原文':'译文') + '文档';
553
+ btn.onclick = () => $('#'+side+'File').click();
554
+ bar.appendChild(btn);
555
+ const tid = document.createElement('button');
556
+ tid.className = 'btn gray sm'; tid.id = 'btn-tidy-' + side;
557
+ tid.textContent = side === 'src' ? '🧽 原文整理' : '🧽 译文整理';
558
+ tid.title = '对噪声文本(语音转写/OCR/段落乱序)排序整理、重分段、去噪:只修明显的乱,不删内容、不改风格、不臆改专名与数字(v4.24.0)';
559
+ tid.onclick = () => tidyText(side);
560
+ bar.appendChild(tid);
561
+ const tip = document.createElement('span');
562
+ tip.style.cssText = 'font-size:11px;color:var(--tx3)';
563
+ tip.textContent = '支持 .docx / .pdf / 图片(扫描件自动 OCR)';
564
+ bar.appendChild(tip);
565
+ const inp = document.createElement('input');
566
+ inp.type='file'; inp.id = side+'File'; inp.accept='.docx,.pdf,image/*'; inp.hidden = true;
567
+ inp.onchange = e => onFileChosen(side, e.target.files[0]);
568
+ bar.appendChild(inp);
569
+ return;
570
+ }
571
+ bar.classList.add('has-file');
572
+ const name = document.createElement('span');
573
+ name.className = 'fb-name';
574
+ name.innerHTML = '📄 ' + esc(data.fileName) + '<span class="fb-meta">'
575
+ + esc(kindLabel(data.kind)) + (data.chapters.length ? ' · '+data.chapters.length+' 章节' : '')
576
+ + (data.hasImages ? ' · 含图' : '') + ((data.notes && data.notes.length) ? ' · 注释 ' + data.notes.length + ' 条' : '') + '</span>';
577
+ bar.appendChild(name);
578
+
579
+ // v4.24:整理按钮(bar 每次重建,需回填)
580
+ const tid2 = document.createElement('button');
581
+ tid2.className = 'btn gray sm'; tid2.id = 'btn-tidy-' + side;
582
+ tid2.textContent = side === 'src' ? '🧽 原文整理' : '🧽 译文整理';
583
+ tid2.title = '对噪声文本(语音转写/OCR/段落乱序)排序整理、重分段、去噪:只修明显的乱,不删内容、不改风格、不臆改专名与数字(v4.24.0)';
584
+ tid2.onclick = () => tidyText(side);
585
+ bar.appendChild(tid2);
586
+
587
+ // v4.3:扫描质检报告入口(PDF 逐页解析后生成)
588
+ if(data.scanReport && data.scanReport.length){
589
+ const ocrN = data.scanReport.filter(r => r.method === 'OCR').length;
590
+ const emptyN = data.scanReport.filter(r => r.chars === 0).length;
591
+ const lowConf = data.scanReport.filter(r => r.method === 'OCR' && r.conf !== null && r.conf < 70).length;
592
+ const rpt = document.createElement('button');
593
+ rpt.className = 'btn sm gray';
594
+ rpt.style.cssText = 'font-size:11px;margin-left:4px';
595
+ rpt.textContent = '📋 扫描报告 ' + data.scanReport.length + ' 页' + (ocrN ? ' · ' + ocrN + ' 页 OCR' : '') + ((emptyN || lowConf) ? ' ⚠' : '');
596
+ rpt.onclick = () => showScanReport(data);
597
+ bar.appendChild(rpt);
598
+ }
599
+
600
+ // v4.3:原文侧导出 docx(PDF/图片/文本 → docx;docx 本身即 docx 无需转)
601
+ if(side === 'src' && data.kind !== 'docx'){
602
+ const ex = document.createElement('button');
603
+ ex.className = 'btn sm';
604
+ ex.style.cssText = 'font-size:11px;margin-left:4px';
605
+ ex.textContent = '📥 导出原文 docx';
606
+ ex.onclick = () => exportOriginalDocx();
607
+ bar.appendChild(ex);
608
+ }
609
+
610
+ if(data.chapters.length > 1){
611
+ const sel = document.createElement('select');
612
+ const allOpt = document.createElement('option');
613
+ allOpt.value = ''; allOpt.textContent = '全部('+data.chapters.length+' 章)';
614
+ sel.appendChild(allOpt);
615
+ data.chapters.forEach((c,i) => {
616
+ const o = document.createElement('option');
617
+ o.value = i; o.textContent = (i+1) + '. ' + c.title.slice(0,28);
618
+ sel.appendChild(o);
619
+ });
620
+ const cur = data._chapterIdx;
621
+ sel.value = cur === undefined ? '' : cur;
622
+ sel.onchange = () => fillFromChapter(side, sel.value === '' ? -1 : +sel.value);
623
+ bar.appendChild(sel);
624
+ }
625
+
626
+ const x = document.createElement('button');
627
+ x.className = 'btn x'; x.textContent = '✕ 清除';
628
+ x.onclick = () => { __TP_FILES[side] = null; renderFileBar(side); $('#'+side).value = ''; saveTask(); };
629
+ bar.appendChild(x);
630
+
631
+ // 3.1 文档模式勾选框联动:仅 dst 侧 docx 可用
632
+ const dm = $('#c-docmode');
633
+ if(dm){
634
+ const usable = (side === 'dst' && data.kind === 'docx' && !!data._zipBytes);
635
+ if(usable){
636
+ dm.disabled = false;
637
+ $('#docModeWrap').style.color = '';
638
+ $('#docModeHint').textContent = '('+data.fileName+')';
639
+ } else if(side === 'dst'){
640
+ dm.disabled = true; dm.checked = false;
641
+ $('#docModeWrap').style.color = 'var(--tx3)';
642
+ $('#docModeHint').textContent = '(需上传 .docx 译文)';
643
+ }
644
+ }
645
+ }
646
+
647
+ function kindLabel(k){ return ({'docx':'Word 文档','pdf-text':'PDF(文字型)','pdf-scan':'PDF(扫描件)','pdf-mixed':'PDF(混合·含扫描页)','image':'图片'})[k] || k; }
648
+
649
+ // 扫描质检报告弹窗(PDF 逐页解析后的质量一览)
650
+ function showScanReport(data){
651
+ const report = data.scanReport || [];
652
+ const ocrN = report.filter(r => r.method === 'OCR').length;
653
+ const emptyN = report.filter(r => r.chars === 0).length;
654
+ const rows = report.map(r => {
655
+ let status = '✅ 正常';
656
+ if(r.chars === 0) status = '⚠️ 空白页';
657
+ else if(r.method === 'OCR' && r.conf !== null && r.conf < 70) status = '⚠️ 低置信度';
658
+ return '<tr><td>' + r.page + '</td><td>' + (r.method === 'OCR' ? 'OCR 识别' : '文字层') + '</td><td>' + r.chars + '</td><td>' + (r.conf === null ? '—' : r.conf + '%') + '</td><td>' + status + '</td></tr>';
659
+ }).join('');
660
+ modal('扫描质检报告', [
661
+ '<div style="font-size:13px;color:var(--tx2);line-height:1.8;margin-bottom:12px">共 <b>' + report.length + '</b> 页' + (ocrN ? ',其中 <b>' + ocrN + '</b> 页为 OCR 识别' : '') + (emptyN ? ',<b style="color:var(--err)">' + emptyN + '</b> 页空白' : '') + '。<br>空白页或低置信度 OCR 页建议人工核对,避免内容遗漏。</div>',
662
+ '<div style="max-height:52vh;overflow:auto"><table class="g-table"><thead><tr><th>页码</th><th>识别方式</th><th>字数</th><th>OCR 置信度</th><th>状态</th></tr></thead><tbody>' + rows + '</tbody></table></div>'
663
+ ].join(''));
664
+ }
665
+
666
+ /* ═══════════ v4.3:原文 PDF/图片/文本 → docx 导出 ═══════════
667
+ 最小 OOXML 重建:文字按章节/段落写入 docx(保文字,丢版式) */
668
+ function escXml(s){ return String(s == null ? '' : s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&apos;'); }
669
+
670
+ async function buildDocxFromChapters(chapters){
671
+ 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']);
672
+ const zip = new window.JSZip();
673
+ const paras = [];
674
+ const list = chapters && chapters.length ? chapters : [{ title:'', text:'' }];
675
+ list.forEach(c => {
676
+ if(c.title && list.length > 1){
677
+ paras.push('<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>' + escXml(c.title) + '</w:t></w:r></w:p>');
678
+ }
679
+ String(c.text || '').split(/\n+/).map(s => s.trim()).filter(Boolean).forEach(line => {
680
+ paras.push('<w:p><w:r><w:t xml:space="preserve">' + escXml(line) + '</w:t></w:r></w:p>');
681
+ });
682
+ });
683
+ const body = paras.length ? paras.join('') : '<w:p/>';
684
+ const documentXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
685
+ '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
686
+ '<w:body>' + body + '</w:body></w:document>';
687
+ const contentTypes = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
688
+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' +
689
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
690
+ '<Default Extension="xml" ContentType="application/xml"/>' +
691
+ '<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>' +
692
+ '<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>' +
693
+ '</Types>';
694
+ const rels = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
695
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
696
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>' +
697
+ '</Relationships>';
698
+ const docRels = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
699
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' +
700
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>' +
701
+ '</Relationships>';
702
+ const styles = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' +
703
+ '<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">' +
704
+ '<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>' +
705
+ '<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:rPr><w:b/><w:sz w:val="32"/></w:rPr></w:style>' +
706
+ '</w:styles>';
707
+ zip.file('[Content_Types].xml', contentTypes);
708
+ zip.file('_rels/.rels', rels);
709
+ zip.file('word/document.xml', documentXml);
710
+ zip.file('word/_rels/document.xml.rels', docRels);
711
+ zip.file('word/styles.xml', styles);
712
+ return await zip.generateAsync({ type:'blob', mimeType:'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
713
+ }
714
+
715
+ async function exportOriginalDocx(){
716
+ const f = __TP_FILES.src;
717
+ if(!f){ toast('请先在原文侧上传文件', 'e'); return; }
718
+ if(!f.fullText || !f.fullText.trim()){ toast('未解析到任何文字,无法导出', 'e'); return; }
719
+ try{
720
+ const blob = await buildDocxFromChapters(f.chapters);
721
+ const base = (f.fileName || '原文').replace(/\.[^.]+$/, '');
722
+ const a = document.createElement('a');
723
+ a.href = URL.createObjectURL(blob); a.download = base + '.docx'; a.click();
724
+ setTimeout(() => URL.revokeObjectURL(a.href), 3000);
725
+ toast('已导出:' + base + '.docx(文字版,图片与复杂版式未保留)');
726
+ }catch(e){ toast('导出失败:' + e.message, 'e'); }
727
+ }
728
+
729
+ // 用户选章节后回填 textarea
730
+ function fillFromChapter(side, idx){
731
+ const data = __TP_FILES[side]; if(!data) return;
732
+ if(idx < 0){ data._chapterIdx = undefined; $('#'+side).value = data.fullText; return; }
733
+ data._chapterIdx = idx;
734
+ $('#'+side).value = data.chapters[idx].text;
735
+ }
736
+
737
+ // 用户选择文件后的总入口
738
+ async function onFileChosen(side, file){
739
+ if(!file) return;
740
+ const bar = $('#'+side+'FileBar');
741
+ // 渲染进度态
742
+ bar.innerHTML = '<span class="fb-spin"></span><span>正在解析 '+esc(file.name)+'…</span>';
743
+ bar.classList.add('has-file');
744
+ try{
745
+ const data = await parseFile(file, side, (msg, p) => {
746
+ bar.innerHTML = '<span class="fb-spin"></span><span>'+esc(msg)+'</span><span class="fb-progress">' + Math.round(p*100) + '%</span>';
747
+ });
748
+ // 3.1 文档模式:译文侧 docx 保留原始 zip 字节,供校对后回写
749
+ if(side === 'dst' && data.kind === 'docx'){
750
+ try{ data._zipBytes = await file.arrayBuffer(); }catch(_){}
751
+ }
752
+ __TP_FILES[side] = data;
753
+ renderFileBar(side);
754
+ // 默认回填"全部"
755
+ fillFromChapter(side, -1);
756
+ toast('已解析:'+data.chapters.length+' 章节,'+data.fullText.length+' 字'+((data.notes && data.notes.length) ? ' · 注释 '+data.notes.length+' 条' : ''));
757
+ saveTask();
758
+ }catch(err){
759
+ renderFileBar(side);
760
+ toast('解析失败:' + errMsg(err), 'e');
761
+ }
762
+ }
763
+
764
+ /* ═══════════ 任务断点续传(本地快照,避免重新上传扫描)═══════════ */
765
+ const LS_TASK = 'tp.task';
766
+ function fileSnap(f){
767
+ if(!f) return null;
768
+ return { kind:f.kind, fileName:f.fileName, chapters:f.chapters, fullText:f.fullText, hasImages:f.hasImages, _chapterIdx:f._chapterIdx, scanReport:f.scanReport || null, notes:f.notes || [] };
769
+ }
770
+ function saveTask(){
771
+ try{
772
+ const snap = {
773
+ page: ((document.querySelector('nav button.on')||{}).dataset||{}).page || 'p-work',
774
+ work: { src:$('#src').value, dst:$('#dst').value, extra:$('#extra').value, out:LAST_OUT, auditFix: (typeof AUDIT_FIX === 'object' && AUDIT_FIX && Object.keys(AUDIT_FIX).length) ? AUDIT_FIX : null },
775
+ trans: { src:$('#ts-src').value, out:TS_LAST_OUT },
776
+ files: { src:fileSnap(__TP_FILES.src), dst:fileSnap(__TP_FILES.dst), tsSrc:fileSnap(TS_FILES.src) },
777
+ t: Date.now()
778
+ };
779
+ const has = snap.work.src || snap.work.dst || snap.work.extra || snap.trans.src || snap.work.out || snap.files.src || snap.files.dst || snap.files.tsSrc;
780
+ if(has) localStorage.setItem(LS_TASK, JSON.stringify(snap));
781
+ else localStorage.removeItem(LS_TASK);
782
+ }catch(e){ /* localStorage 满或隐私模式:静默失败 */ }
783
+ }
784
+ function restoreTask(s){
785
+ if(!s) return;
786
+ if(s.files && s.files.src) __TP_FILES.src = s.files.src;
787
+ if(s.files && s.files.dst) __TP_FILES.dst = s.files.dst;
788
+ if(s.files && s.files.tsSrc) TS_FILES.src = s.files.tsSrc;
789
+ if(s.work){
790
+ if(s.work.src) $('#src').value = s.work.src;
791
+ if(s.work.dst) $('#dst').value = s.work.dst;
792
+ if(s.work.extra) $('#extra').value = s.work.extra;
793
+ if(s.work.out){
794
+ LAST_OUT = s.work.out; $('#out').innerHTML = md(s.work.out); $('#outHint').textContent = '已恢复上次结果';
795
+ AUDIT_FIX = (s.work.auditFix && typeof s.work.auditFix === 'object') ? s.work.auditFix : {};
796
+ markErrorLines(); renderAuditControls(); renderErrorFilter(LAST_OUT); dedupAuditLines(); paintErrFixSpans();
797
+ }
798
+ }
799
+ if(s.trans){
800
+ if(s.trans.src) $('#ts-src').value = s.trans.src;
801
+ if(s.trans.out){ TS_LAST_OUT = s.trans.out; $('#ts-out').innerHTML = md(s.trans.out); $('#ts-outHint').textContent = '已恢复上次译文'; }
802
+ }
803
+ renderFileBar('src'); renderFileBar('dst');
804
+ tsRenderSrcBar();
805
+ if(s.files && s.files.tsSrc) $('#ts-srcStat').textContent = '已恢复:' + s.files.tsSrc.chapters.length + ' 章节';
806
+ if(s.page){ const b = document.querySelector('nav button[data-page="'+s.page+'"]'); if(b) b.click(); }
807
+ saveTask();
808
+ if(typeof syncOutView === 'function') syncOutView(); // v4.30.0:恢复结果后同步刷新视图切换条
809
+ }
810
+ function promptResumeTask(){
811
+ try{
812
+ const raw = localStorage.getItem(LS_TASK);
813
+ if(!raw) return;
814
+ const s = JSON.parse(raw);
815
+ const has = (s.work && (s.work.src||s.work.dst||s.work.out)) || (s.trans && (s.trans.src||s.trans.out)) || (s.files && (s.files.src||s.files.dst||s.files.tsSrc));
816
+ if(!has) return;
817
+ const fname = ((s.files && (s.files.src||s.files.tsSrc||s.files.dst)) || {}).fileName || '';
818
+ modal('继续上次任务?', [
819
+ '<div style="font-size:13px;color:var(--tx2);line-height:1.9">检测到上次未完成的任务(' + new Date(s.t).toLocaleString('zh-CN') + ')。<br>· 文件:' + (fname ? '<b>' + esc(fname) + '</b>' : '无') + '<br>· 文本与输出已自动保存,可直接继续,无需重新上传扫描。</div>',
820
+ '<div style="display:flex;gap:8px;margin-top:14px"><button class="btn pri" id="resume-yes">✅ 恢复上次任务</button><button class="btn gray" id="resume-no">忽略,重新开始</button></div>'
821
+ ].join(''));
822
+ $('#resume-yes').onclick = () => { restoreTask(s); closeModal(); toast('已恢复上次任务'); };
823
+ $('#resume-no').onclick = () => { localStorage.removeItem(LS_TASK); closeModal(); };
824
+ }catch(e){}
825
+ }
826
+
827
+ /* ═══════════ 3.1 文档模式:从校对输出中提取"修订后译文"段 ═══════════ */
828
+ function extractProofText(mdText){
829
+ const t = String(mdText || '');
830
+ // 匹配 "## 一、修订后译文"(兼容:## 修订后译文 / ## 一. 修订后译文 / ### 修订后译文)
831
+ const m = t.match(/(?:^|\n)#{2,3}\s*[一二三四五六1-9]?[、..]?\s*修订后译文[^\n]*\n([\s\S]*?)(?=\n#{2,3}\s|\n*$)/);
832
+ if(m) return m[1].trim();
833
+ // 兜底:精修模式可能输出"## 终稿"/"## 定稿"
834
+ const m2 = t.match(/(?:^|\n)#{2,3}\s*[^\n]*(终稿|定稿|修订稿)[^\n]*\n([\s\S]*?)(?=\n#{2,3}\s|\n*$)/);
835
+ if(m2) return m2[2].trim();
836
+ return null;
837
+ }
838
+
839
+ /* ═══════════ 3.1 文档模式:docx 解包回写引擎(图片零接触) ═══════════
840
+ 原理:docx = zip 包;word/document.xml 是内容,word/media/ 是图片。
841
+ 只把"修订后译文"写回各段落的文字节点(w:t),图片节点(w:drawing)
842
+ 与样式属性完全不碰 → 图片原位保留、字号/加粗/字体等格式不变。 */