dsh-paper-workbench 1.1.1 → 1.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/CHANGELOG.md +15 -0
- package/README.md +65 -449
- package/assets/app/app.js +311 -147
- package/assets/app/style.css +21 -10
- package/assets/pdf_tool.py +37 -8
- package/docs/guide.md +43 -0
- package/docs/v4-layout.md +9 -0
- package/docs/v6-zhpdf.md +13 -12
- package/docs/v7-quality.md +3 -1
- package/docs/v8-native-session.md +2 -0
- package/lib/arxiv.js +398 -34
- package/lib/doc.js +145 -48
- package/lib/history.js +76 -0
- package/lib/index.js +95 -74
- package/lib/layout-ir.js +96 -1
- package/lib/layout.js +1 -1
- package/lib/paper-context.js +3 -0
- package/lib/pdf.js +12 -1
- package/lib/server.js +17 -2
- package/lib/translate-jobs.js +3 -0
- package/lib/zhpdf-jobs.js +198 -0
- package/lib/zhpdf.js +248 -63
- package/package.json +7 -2
- package/scripts/audit-library.mjs +348 -0
- package/scripts/batch-layout.mjs +201 -0
- package/scripts/quality/rebuild-layout.mjs +7 -2
package/lib/doc.js
CHANGED
|
@@ -14,6 +14,7 @@ import { createReadStream, promises as fsp } from 'node:fs'
|
|
|
14
14
|
import * as store from './store.js'
|
|
15
15
|
import { extractText } from './pdf.js'
|
|
16
16
|
import { LAYOUT_BUILD, LAYOUT_VERSION, readPublishedLayout, tidyFormulaLatex } from './layout.js'
|
|
17
|
+
import { structureTocRows, tocEntryInfo } from './layout-ir.js'
|
|
17
18
|
|
|
18
19
|
export const DOC_VERSION = 1
|
|
19
20
|
|
|
@@ -225,6 +226,27 @@ function levelForSize(size, tiers, maxLevels) {
|
|
|
225
226
|
|
|
226
227
|
// ---------------------------------------------------------------- 块 / 页规范化
|
|
227
228
|
|
|
229
|
+
function tocMetadata(item) {
|
|
230
|
+
return item.role === 'toc-entry' ? { role: 'toc-entry', tocLevel: item.tocLevel || 1,
|
|
231
|
+
...(item.tocTargetPage !== undefined ? { tocTargetPage: item.tocTargetPage } : {}),
|
|
232
|
+
...(item.parentBlockId ? { parentBlockId: item.parentBlockId } : {}) } : {}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** 旧版 layout/文本缓存仍可投影目录;只借用已有换行,不猜测压平字符串的断点。 */
|
|
236
|
+
function expandTocBlocks(blocks) {
|
|
237
|
+
const context = blocks.some(b => /^(?:contents|table of contents|目\s*录)\s*$/i.test(collapseWs(b.text)))
|
|
238
|
+
const expanded = blocks.flatMap(block => {
|
|
239
|
+
if (block.role === 'toc-entry' || !['body', 'list', 'heading', undefined, ''].includes(block.kind)) return [{ ...block }]
|
|
240
|
+
const rows = structureTocRows(String(block.text || '').split(/\r?\n/).map(text => ({ text })), context || block.label === 'content')
|
|
241
|
+
return rows ? rows.map(row => ({ ...block, ...row, kind: 'list', role: 'toc-entry', ...(block.blockId ? { parentBlockId: block.blockId } : {}) })) : [{ ...block }]
|
|
242
|
+
})
|
|
243
|
+
const candidates = expanded.filter(b => b.role !== 'toc-entry' && ['body', 'list', 'heading', undefined, ''].includes(b.kind) && tocEntryInfo(b.text))
|
|
244
|
+
if (structureTocRows(candidates, context)) {
|
|
245
|
+
for (const block of candidates) Object.assign(block, { kind: 'list', role: 'toc-entry' }, tocMetadata({ role: 'toc-entry', ...tocEntryInfo(block.text) }))
|
|
246
|
+
}
|
|
247
|
+
return expanded
|
|
248
|
+
}
|
|
249
|
+
|
|
228
250
|
function normalizeBlock(raw) {
|
|
229
251
|
if (!raw || typeof raw !== 'object') return null
|
|
230
252
|
const text = collapseWs(raw.text)
|
|
@@ -236,7 +258,7 @@ function normalizeBlock(raw) {
|
|
|
236
258
|
// pdf_tool(v2 起)会在块上带 kind:heading/body/list/caption/footnote。
|
|
237
259
|
// 有就用它,别再靠字号猜(小节标题常与正文同字号,只加粗)。
|
|
238
260
|
const kind = typeof raw.kind === 'string' && BLOCK_KINDS.has(raw.kind) ? raw.kind : ''
|
|
239
|
-
return { x, y, x2, y2, size: round2(raw.size), bold: raw.bold === true, text, kind }
|
|
261
|
+
return { x, y, x2, y2, size: round2(raw.size), bold: raw.bold === true, text, kind, ...tocMetadata(raw) }
|
|
240
262
|
}
|
|
241
263
|
|
|
242
264
|
const BLOCK_KINDS = new Set(['heading', 'body', 'list', 'caption', 'footnote', 'algorithm'])
|
|
@@ -247,7 +269,7 @@ function normalizePages(pages) {
|
|
|
247
269
|
const out = []
|
|
248
270
|
list.forEach((page, index) => {
|
|
249
271
|
if (!page || typeof page !== 'object') return
|
|
250
|
-
const blocks = (Array.isArray(page.blocks) ? page.blocks : []).map(normalizeBlock).filter(Boolean)
|
|
272
|
+
const blocks = expandTocBlocks((Array.isArray(page.blocks) ? page.blocks : []).filter(b => b && typeof b === 'object')).map(normalizeBlock).filter(Boolean)
|
|
251
273
|
if (!blocks.length) return
|
|
252
274
|
// text.json 里页号字段是 "n"(pdf_tool.py 写的);契约文档写的是 "page",两个都认
|
|
253
275
|
const pageNo = Math.max(1, Math.round(toNumber(page.page !== undefined ? page.page : page.n, index + 1)))
|
|
@@ -299,8 +321,10 @@ function canMergeHeadingWrap(current, block) {
|
|
|
299
321
|
const lineHeight = Math.max(current.size, block.size, 10)
|
|
300
322
|
const gap = block.y - current.y2
|
|
301
323
|
if (!(gap >= -2 && gap <= lineHeight * 0.9)) return false
|
|
302
|
-
//
|
|
303
|
-
return
|
|
324
|
+
// 独立编号是新标题;换行标题必须在同一列,允许居中行左右缩进。
|
|
325
|
+
if (/^(?:\d+(?:\.\d+)*\.?|Appendix\s+[A-Z][.:]?)\s+\S/i.test(block.text)) return false
|
|
326
|
+
const overlap = Math.min(current.x2, block.x2) - Math.max(current.x, block.x)
|
|
327
|
+
return overlap >= Math.min(current.x2 - current.x, block.x2 - block.x) * 0.5
|
|
304
328
|
}
|
|
305
329
|
|
|
306
330
|
function canMergeSamePage(current, block, size, options) {
|
|
@@ -354,6 +378,7 @@ function mergePageBlocks(blocks, bodySize, options) {
|
|
|
354
378
|
y2: block.y2,
|
|
355
379
|
size,
|
|
356
380
|
kind: block.kind || '',
|
|
381
|
+
...tocMetadata(block),
|
|
357
382
|
crossPage: false,
|
|
358
383
|
}
|
|
359
384
|
out.push(current)
|
|
@@ -381,9 +406,11 @@ function mergeAcrossPages(paragraphs, bodySize, options) {
|
|
|
381
406
|
for (const item of paragraphs) {
|
|
382
407
|
const previous = out[out.length - 1]
|
|
383
408
|
if (previous && canMergeAcrossPages(previous, item, bodySize, options)) {
|
|
409
|
+
const fragment = ({ page, text, x, y, x2, y2 }) => ({ page, text, bbox: [x, y, x2, y2] })
|
|
410
|
+
previous.pageFragments ||= [fragment(previous)]
|
|
411
|
+
previous.pageFragments.push(fragment(item))
|
|
384
412
|
previous.text = joinWrapped(previous.text, item.text)
|
|
385
413
|
previous.crossPage = true
|
|
386
|
-
// bbox 保留起始页的那一块(跨页矩形没有几何意义),只打 crossPage 标记
|
|
387
414
|
continue
|
|
388
415
|
}
|
|
389
416
|
out.push({ ...item })
|
|
@@ -491,12 +518,14 @@ export function mergeBlocks(pages, opts = {}) {
|
|
|
491
518
|
order,
|
|
492
519
|
page: item.page,
|
|
493
520
|
kind: item.kind,
|
|
521
|
+
...tocMetadata(item),
|
|
494
522
|
level: item.kind === 'heading' ? item.level : 0,
|
|
495
523
|
text: item.text,
|
|
496
524
|
hash: paragraphHash(item.kind, item.text),
|
|
497
525
|
bbox: [item.x, item.y, item.x2, item.y2],
|
|
498
526
|
size: round2(item.size),
|
|
499
527
|
crossPage: item.crossPage === true,
|
|
528
|
+
...(item.pageFragments ? { pageFragments: item.pageFragments } : {}),
|
|
500
529
|
}))
|
|
501
530
|
}
|
|
502
531
|
|
|
@@ -533,26 +562,31 @@ function findAnchor(paragraphs, item, fromIndex) {
|
|
|
533
562
|
const start = Math.min(Math.max(fromIndex, 0), paragraphs.length - 1)
|
|
534
563
|
const want = titleKey(item.title)
|
|
535
564
|
if (want) {
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
if (titleKey(paragraph.text) === want) return index
|
|
540
|
-
}
|
|
541
|
-
for (let index = start; index < paragraphs.length; index += 1) {
|
|
542
|
-
const paragraph = paragraphs[index]
|
|
543
|
-
if (paragraph.kind === 'caption' || paragraph.kind === 'formula') continue
|
|
544
|
-
if (paragraph.kind !== 'heading') continue
|
|
545
|
-
const key = titleKey(paragraph.text)
|
|
546
|
-
if (!key) continue
|
|
547
|
-
const limit = Math.max(want.length * 2.2, want.length + 12)
|
|
548
|
-
if (key.length <= limit && (key.includes(want) || want.includes(key))) return index
|
|
549
|
-
}
|
|
550
|
-
if (want.length >= 6) {
|
|
565
|
+
const nearest = (matches) => {
|
|
566
|
+
let best = -1
|
|
567
|
+
let distance = 3
|
|
551
568
|
for (let index = start; index < paragraphs.length; index += 1) {
|
|
552
569
|
const paragraph = paragraphs[index]
|
|
553
|
-
if (paragraph.
|
|
554
|
-
if (
|
|
570
|
+
if (paragraph.page > item.page + 2) break
|
|
571
|
+
if (paragraph.role === 'toc-entry' || paragraph.kind === 'caption' || paragraph.kind === 'formula') continue
|
|
572
|
+
const delta = Math.abs(paragraph.page - item.page)
|
|
573
|
+
if (delta < distance && matches(titleKey(paragraph.text), paragraph)) {
|
|
574
|
+
best = index
|
|
575
|
+
distance = delta
|
|
576
|
+
if (delta === 0) break
|
|
577
|
+
}
|
|
555
578
|
}
|
|
579
|
+
return best
|
|
580
|
+
}
|
|
581
|
+
const exact = nearest(key => key === want)
|
|
582
|
+
if (exact >= 0) return exact
|
|
583
|
+
const limit = Math.max(want.length * 2.2, want.length + 12)
|
|
584
|
+
const heading = nearest((key, paragraph) => paragraph.kind === 'heading' && key &&
|
|
585
|
+
key.length <= limit && (key.includes(want) || want.includes(key)))
|
|
586
|
+
if (heading >= 0) return heading
|
|
587
|
+
if (want.length >= 6) {
|
|
588
|
+
const body = nearest(key => key.includes(want))
|
|
589
|
+
if (body >= 0) return body
|
|
556
590
|
}
|
|
557
591
|
}
|
|
558
592
|
// 标题文字对不上(扫描件 OCR 差异等):按 outline 的页码找该页第一个段落
|
|
@@ -569,6 +603,7 @@ function toSections(anchors, paragraphs) {
|
|
|
569
603
|
id: 's' + (order + 1),
|
|
570
604
|
order,
|
|
571
605
|
title: anchor.title,
|
|
606
|
+
...(anchor.synthetic ? { synthetic: true } : {}),
|
|
572
607
|
level: anchor.level,
|
|
573
608
|
page: paragraph.page,
|
|
574
609
|
hash: titleHash(anchor.title),
|
|
@@ -580,7 +615,15 @@ function toSections(anchors, paragraphs) {
|
|
|
580
615
|
function sectionsFromOutline(paragraphs, outline, options) {
|
|
581
616
|
const anchors = []
|
|
582
617
|
let cursor = 0
|
|
583
|
-
for (
|
|
618
|
+
for (let oi = 0; oi < outline.length; oi += 1) {
|
|
619
|
+
let item = outline[oi]
|
|
620
|
+
const next = outline[oi + 1]
|
|
621
|
+
// 旧版自动 outline 逐行存标题:仅当两行恰好对应已按几何合并的一条完整标题时修复。
|
|
622
|
+
if (next && next.page === item.page && next.level === item.level && !/^\d+(?:\.\d+)*\.?\s+\S/.test(next.title)) {
|
|
623
|
+
const joined = item.title + ' ' + next.title
|
|
624
|
+
const heading = paragraphs.find(p => p.kind === 'heading' && p.page === item.page && titleKey(p.text) === titleKey(joined))
|
|
625
|
+
if (heading) { item = { ...item, title: heading.text }; oi += 1 }
|
|
626
|
+
}
|
|
584
627
|
let index = findAnchor(paragraphs, item, cursor)
|
|
585
628
|
// 两条 outline 命中同一个段落时顺延一段:每节至少要有一段,目录才不会出现空节
|
|
586
629
|
const previous = anchors.length ? anchors[anchors.length - 1].index : -1
|
|
@@ -607,7 +650,7 @@ function sectionsFromOutline(paragraphs, outline, options) {
|
|
|
607
650
|
anchors.push({ index, title: item.title, level: item.level })
|
|
608
651
|
}
|
|
609
652
|
if (!anchors.length) return []
|
|
610
|
-
if (anchors[0].index > 0) anchors.unshift({ index: 0, title: options.fallbackTitle, level: 1 })
|
|
653
|
+
if (anchors[0].index > 0) anchors.unshift({ index: 0, title: options.fallbackTitle, level: 1, synthetic: true })
|
|
611
654
|
return toSections(anchors, paragraphs)
|
|
612
655
|
}
|
|
613
656
|
|
|
@@ -629,14 +672,14 @@ function sectionsFromHeuristic(paragraphs, options) {
|
|
|
629
672
|
// 多页又量不出标题:把每页首段当节标题,至少让目录能按页跳
|
|
630
673
|
const seen = new Set()
|
|
631
674
|
paragraphs.forEach((paragraph, index) => {
|
|
632
|
-
if (seen.has(paragraph.page)) return
|
|
675
|
+
if (paragraph.role === 'toc-entry' || seen.has(paragraph.page)) return
|
|
633
676
|
seen.add(paragraph.page)
|
|
634
677
|
anchors.push({ index, title: truncateTitle(paragraph.text, 60) || '第 ' + paragraph.page + ' 页', level: 1 })
|
|
635
678
|
})
|
|
636
679
|
}
|
|
637
680
|
// 单页又没有标题:整篇一节「正文」(不拿正文首句冒充标题)
|
|
638
|
-
if (!anchors.length) anchors.push({ index: 0, title: options.fallbackTitle, level: 1 })
|
|
639
|
-
if (anchors[0].index > 0) anchors.unshift({ index: 0, title: options.fallbackTitle, level: 1 })
|
|
681
|
+
if (!anchors.length) anchors.push({ index: 0, title: options.fallbackTitle, level: 1, synthetic: true })
|
|
682
|
+
if (anchors[0].index > 0) anchors.unshift({ index: 0, title: options.fallbackTitle, level: 1, synthetic: true })
|
|
640
683
|
return toSections(anchors, paragraphs)
|
|
641
684
|
}
|
|
642
685
|
|
|
@@ -667,6 +710,7 @@ function applySectionIds(paragraphs, sections) {
|
|
|
667
710
|
section: sectionId,
|
|
668
711
|
kind: paragraph.kind,
|
|
669
712
|
level,
|
|
713
|
+
...tocMetadata(paragraph),
|
|
670
714
|
...(paragraph.blockId !== undefined ? { blockId: paragraph.blockId } : {}),
|
|
671
715
|
...(paragraph.figureIndex !== undefined ? { figureIndex: paragraph.figureIndex } : {}),
|
|
672
716
|
...(paragraph.equationNumber ? { equationNumber: paragraph.equationNumber } : {}),
|
|
@@ -677,6 +721,8 @@ function applySectionIds(paragraphs, sections) {
|
|
|
677
721
|
hash: paragraph.hash,
|
|
678
722
|
bbox: paragraph.bbox,
|
|
679
723
|
size: paragraph.size,
|
|
724
|
+
...(paragraph.geometryTrusted === false ? { geometryTrusted: false } : {}),
|
|
725
|
+
...(paragraph.pageFragments ? { pageFragments: paragraph.pageFragments } : {}),
|
|
680
726
|
crossPage: paragraph.crossPage,
|
|
681
727
|
}
|
|
682
728
|
})
|
|
@@ -814,6 +860,7 @@ function finalizeParagraphs(items, defaults = {}) {
|
|
|
814
860
|
hash: paragraphHash(kind, text),
|
|
815
861
|
bbox,
|
|
816
862
|
size: round2(item.size),
|
|
863
|
+
...(item.geometryTrusted === false ? { geometryTrusted: false } : {}),
|
|
817
864
|
crossPage: item.crossPage === true,
|
|
818
865
|
}
|
|
819
866
|
})
|
|
@@ -847,6 +894,7 @@ function degenerateDoc({ meta, text, ocrMarkdown, pdf, builtAt }) {
|
|
|
847
894
|
const { sections, paragraphs: withSections } = assignSections(paragraphs, [])
|
|
848
895
|
return {
|
|
849
896
|
version: DOC_VERSION,
|
|
897
|
+
parserBuild: LAYOUT_BUILD,
|
|
850
898
|
source,
|
|
851
899
|
builtAt,
|
|
852
900
|
title: collapseWs((meta && meta.title) || ''),
|
|
@@ -910,6 +958,7 @@ function buildDocCore(input) {
|
|
|
910
958
|
if (sections.length && withSections.length) {
|
|
911
959
|
return {
|
|
912
960
|
version: DOC_VERSION,
|
|
961
|
+
parserBuild: LAYOUT_BUILD,
|
|
913
962
|
source: 'pdf-text',
|
|
914
963
|
builtAt,
|
|
915
964
|
title: collapseWs(meta.title || ''),
|
|
@@ -932,6 +981,7 @@ function buildDocCore(input) {
|
|
|
932
981
|
const firstHeading = ocr.paragraphs.find((item) => item.kind === 'heading')
|
|
933
982
|
return {
|
|
934
983
|
version: DOC_VERSION,
|
|
984
|
+
parserBuild: LAYOUT_BUILD,
|
|
935
985
|
source: 'ocr',
|
|
936
986
|
builtAt,
|
|
937
987
|
title: collapseWs(meta.title || (firstHeading && firstHeading.text) || ''),
|
|
@@ -999,7 +1049,8 @@ export function buildLayoutDoc({ meta, layout, pdf }) {
|
|
|
999
1049
|
// or discard source text a second time; rebuilding layout is an explicit step.
|
|
1000
1050
|
// 已发布的块边界不再二次清理:合并/删除会改变 blockId 与翻译归属。
|
|
1001
1051
|
// 旧版 layout.json 若确实脏,重新解析一次即可,不能在投影层悄悄改数据。
|
|
1002
|
-
const
|
|
1052
|
+
const sourceBlocks = layout && Array.isArray(layout.blocks) ? layout.blocks : []
|
|
1053
|
+
const blocks = [...new Set(sourceBlocks.map(b => b.page))].flatMap(page => expandTocBlocks(sourceBlocks.filter(b => b.page === page)))
|
|
1003
1054
|
const legacyNums = []
|
|
1004
1055
|
const items = []
|
|
1005
1056
|
for (const block of blocks) {
|
|
@@ -1029,10 +1080,12 @@ export function buildLayoutDoc({ meta, layout, pdf }) {
|
|
|
1029
1080
|
: blockText
|
|
1030
1081
|
items.push({
|
|
1031
1082
|
kind,
|
|
1083
|
+
...tocMetadata(block),
|
|
1032
1084
|
level: kind === 'heading' ? Math.min(MAX_LEVELS, Math.max(1, Math.round(toNumber(block.level, 1)))) : 0,
|
|
1033
1085
|
page: Math.max(1, Math.round(toNumber(block.page, 1))),
|
|
1034
1086
|
text,
|
|
1035
1087
|
bbox: [x, y, x + toNumber(bbox.width), y + toNumber(bbox.height)],
|
|
1088
|
+
geometryTrusted: block.geometryTrusted !== false,
|
|
1036
1089
|
size: 0,
|
|
1037
1090
|
blockId: typeof block.blockId === 'string' && block.blockId ? block.blockId : null,
|
|
1038
1091
|
figureIndex: block.figureIndex,
|
|
@@ -1051,6 +1104,7 @@ export function buildLayoutDoc({ meta, layout, pdf }) {
|
|
|
1051
1104
|
}
|
|
1052
1105
|
const paragraphs = finalizeParagraphs(items).map((paragraph, index) => {
|
|
1053
1106
|
const extra = items[index]
|
|
1107
|
+
Object.assign(paragraph, tocMetadata(extra))
|
|
1054
1108
|
paragraph.blockId = extra.blockId
|
|
1055
1109
|
if (extra.figureIndex !== undefined && extra.figureIndex !== null) paragraph.figureIndex = extra.figureIndex
|
|
1056
1110
|
if (extra.equationNumber) paragraph.equationNumber = extra.equationNumber
|
|
@@ -1063,6 +1117,7 @@ export function buildLayoutDoc({ meta, layout, pdf }) {
|
|
|
1063
1117
|
const firstHeading = paragraphs.find(item => item.kind === 'heading')
|
|
1064
1118
|
return {
|
|
1065
1119
|
version: DOC_VERSION,
|
|
1120
|
+
parserBuild: LAYOUT_BUILD,
|
|
1066
1121
|
source: 'layout',
|
|
1067
1122
|
citationVersion: 1,
|
|
1068
1123
|
revision: typeof layout?.revision === 'string' && layout.revision ? layout.revision : null,
|
|
@@ -1114,12 +1169,60 @@ export async function getDoc(id, opts = {}) {
|
|
|
1114
1169
|
|
|
1115
1170
|
const inflight = new Map()
|
|
1116
1171
|
|
|
1172
|
+
function locateAnnotation(annotation, paragraphs, counts) {
|
|
1173
|
+
if (annotation.target === 'zh') return { reason: 'translated' }
|
|
1174
|
+
const quote = annotation.quote
|
|
1175
|
+
if (!quote?.trim()) return { reason: 'missing' }
|
|
1176
|
+
let match = null
|
|
1177
|
+
for (const paragraph of paragraphs) {
|
|
1178
|
+
const text = paragraph.text || ''
|
|
1179
|
+
const startOffset = text.indexOf(quote)
|
|
1180
|
+
if (startOffset < 0) continue
|
|
1181
|
+
if (match || counts.get(paragraph.hash) > 1 || text.indexOf(quote, startOffset + 1) >= 0) return { reason: 'ambiguous' }
|
|
1182
|
+
match = { paragraph, startOffset }
|
|
1183
|
+
}
|
|
1184
|
+
if (!match || ['heading', 'figure', 'table'].includes(match.paragraph.kind)) return { reason: 'missing' }
|
|
1185
|
+
const { paragraph, startOffset } = match
|
|
1186
|
+
const endOffset = startOffset + quote.length
|
|
1187
|
+
return { moved: { ...annotation, paragraphKey: paragraph.hash, startOffset, endOffset,
|
|
1188
|
+
prefix: paragraph.text.slice(Math.max(0, startOffset - 120), startOffset), suffix: paragraph.text.slice(endOffset, endOffset + 120),
|
|
1189
|
+
page: paragraph.page, sectionId: paragraph.section || null, blockId: paragraph.blockId || null } }
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
export async function writeRebuiltDoc(id, previous, doc) {
|
|
1193
|
+
const annotations = await store.readAnnotations(id)
|
|
1194
|
+
if (annotations.length) {
|
|
1195
|
+
const counts = new Map()
|
|
1196
|
+
for (const paragraph of doc.paragraphs) counts.set(paragraph.hash, (counts.get(paragraph.hash) || 0) + 1)
|
|
1197
|
+
const oldReviews = new Map((previous?.annotationReview || []).map(item => [item.id, item]))
|
|
1198
|
+
const oldKeys = new Set((previous?.paragraphs || []).map(paragraph => paragraph.hash))
|
|
1199
|
+
const review = []
|
|
1200
|
+
const moved = []
|
|
1201
|
+
for (const annotation of annotations) {
|
|
1202
|
+
const count = counts.get(annotation.paragraphKey)
|
|
1203
|
+
if (count === 1) continue
|
|
1204
|
+
const result = count ? { reason: 'ambiguous' } : locateAnnotation(annotation, doc.paragraphs, counts)
|
|
1205
|
+
if (result.moved) moved.push(result.moved)
|
|
1206
|
+
else {
|
|
1207
|
+
const prior = oldReviews.get(annotation.id)
|
|
1208
|
+
const revision = prior ? prior.revision : oldKeys.has(annotation.paragraphKey) ? previous.revision : null
|
|
1209
|
+
review.push({ id: annotation.id, revision: revision || null, reason: result.reason })
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
if (review.length) doc.annotationReview = review
|
|
1213
|
+
if (moved.length) await store.saveAnnotations(id, moved)
|
|
1214
|
+
}
|
|
1215
|
+
doc.annotationAnchorVersion = 1
|
|
1216
|
+
await store.writeDoc(id, doc)
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1117
1219
|
async function getDocInner(id, { rebuild = false } = {}) {
|
|
1118
1220
|
const started = Date.now()
|
|
1119
1221
|
const safeId = String(id || '')
|
|
1120
1222
|
if (!safeId) throw new Error('缺少论文 id')
|
|
1121
1223
|
const cached = await store.readDoc(safeId).catch(() => null)
|
|
1122
1224
|
const usable = isUsableDoc(cached)
|
|
1225
|
+
const currentCache = usable && cached.annotationAnchorVersion === 1
|
|
1123
1226
|
|
|
1124
1227
|
let meta = null
|
|
1125
1228
|
let metaError = null
|
|
@@ -1146,6 +1249,16 @@ async function getDocInner(id, { rebuild = false } = {}) {
|
|
|
1146
1249
|
}
|
|
1147
1250
|
const sameFile = Boolean(fingerprint && cached && cached.pdf && String(cached.pdf.sha1 || '') === fingerprint.sha1)
|
|
1148
1251
|
|
|
1252
|
+
async function finishRebuild(doc) {
|
|
1253
|
+
try {
|
|
1254
|
+
await writeRebuiltDoc(safeId, cached, doc)
|
|
1255
|
+
} catch (error) {
|
|
1256
|
+
console.error('[paper-workbench] 文档或标注定位保存失败,请重试 ' + safeId + ':' + error.message)
|
|
1257
|
+
return { doc: usable ? cached : doc, built: false, stale: true, ms: Date.now() - started }
|
|
1258
|
+
}
|
|
1259
|
+
return { doc, built: true, ...(!fingerprint ? { stale: true } : {}), ms: Date.now() - started }
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1149
1262
|
// 版面模型(PP-StructureV3):跑过一次就优先用它建模 —— 段落边界、图表位置、公式都由模型给。
|
|
1150
1263
|
// 版面结果与 PDF 是同一份才用(size + mtime 对得上),PDF 换版本就当没有。
|
|
1151
1264
|
let layout = null
|
|
@@ -1176,7 +1289,7 @@ async function getDocInner(id, { rebuild = false } = {}) {
|
|
|
1176
1289
|
String(cached.layoutBuild || '') === LAYOUT_BUILD,
|
|
1177
1290
|
)
|
|
1178
1291
|
// rebuild 不能走缓存:doc.build 的语义就是「用当前来源重算一遍」
|
|
1179
|
-
if (!rebuild &&
|
|
1292
|
+
if (!rebuild && currentCache && sameFile && !outlineChanged && sameLayout) {
|
|
1180
1293
|
return { doc: cached, built: false, ms: Date.now() - started }
|
|
1181
1294
|
}
|
|
1182
1295
|
try {
|
|
@@ -1190,14 +1303,7 @@ async function getDocInner(id, { rebuild = false } = {}) {
|
|
|
1190
1303
|
layout,
|
|
1191
1304
|
pdf: { ...fingerprint },
|
|
1192
1305
|
})
|
|
1193
|
-
if (doc.paragraphs.length)
|
|
1194
|
-
try {
|
|
1195
|
-
await store.writeDoc(safeId, doc)
|
|
1196
|
-
} catch (error) {
|
|
1197
|
-
console.error('[paper-workbench] 写 doc.json 失败 ' + safeId + ':' + (error && error.message))
|
|
1198
|
-
}
|
|
1199
|
-
return { doc, built: true, ms: Date.now() - started }
|
|
1200
|
-
}
|
|
1306
|
+
if (doc.paragraphs.length) return finishRebuild(doc)
|
|
1201
1307
|
} catch (error) {
|
|
1202
1308
|
console.error('[paper-workbench] 版面建模失败,退回文本层 ' + safeId + ':' + (error && error.message))
|
|
1203
1309
|
}
|
|
@@ -1245,7 +1351,7 @@ async function getDocInner(id, { rebuild = false } = {}) {
|
|
|
1245
1351
|
|
|
1246
1352
|
// 退化模型(一段占位)只要现在有文本层就必须重建,否则会一直显示那一行
|
|
1247
1353
|
const healed = Boolean(usable && cached.degraded === true && hasText)
|
|
1248
|
-
if (
|
|
1354
|
+
if (currentCache && sameFile && !outlineChanged && !healed && !rebuild && cached.parserBuild === LAYOUT_BUILD) {
|
|
1249
1355
|
return { doc: cached, built: false, ms: Date.now() - started }
|
|
1250
1356
|
}
|
|
1251
1357
|
// PDF 暂时定位不到:旧模型还能用就先给用户,标记 stale 让界面提示「可能已过期」
|
|
@@ -1262,16 +1368,7 @@ async function getDocInner(id, { rebuild = false } = {}) {
|
|
|
1262
1368
|
const ocrMarkdown = await store.readOcr(safeId)
|
|
1263
1369
|
const doc = buildDoc({ meta: meta || {}, text, outline, ocrMarkdown, pdf: fingerprint ? { ...fingerprint } : null })
|
|
1264
1370
|
if (!doc.paragraphs.length) throw new Error('解析后没有任何段落')
|
|
1265
|
-
|
|
1266
|
-
await store.writeDoc(safeId, doc)
|
|
1267
|
-
} catch (error) {
|
|
1268
|
-
// 写盘失败不该让用户看不到内容:下次调用会再次重建
|
|
1269
|
-
console.error('[paper-workbench] 写 doc.json 失败 ' + safeId + ':' + (error && error.message))
|
|
1270
|
-
}
|
|
1271
|
-
// PDF 定位不到时仍然能从 text.json/ocr.md 建模,但没法保证与 PDF 对齐,标 stale 提醒界面
|
|
1272
|
-
return fingerprint
|
|
1273
|
-
? { doc, built: true, ms: Date.now() - started }
|
|
1274
|
-
: { doc, built: true, stale: true, ms: Date.now() - started }
|
|
1371
|
+
return finishRebuild(doc)
|
|
1275
1372
|
} catch (error) {
|
|
1276
1373
|
if (usable) return { doc: cached, built: false, stale: true, ms: Date.now() - started }
|
|
1277
1374
|
throw fingerprintError && !fingerprint ? fingerprintError : error
|
package/lib/history.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/** 浏览历史仅保留有界书目信息;检索结果、摘要、正文和凭据不进入界面状态。 */
|
|
2
|
+
const LIMIT = 200
|
|
3
|
+
const paperIdRe = /^[a-z0-9][a-z0-9._-]{0,79}$/
|
|
4
|
+
const clean = (value, max) => typeof value === 'string' ? value.replace(/[\r\n\u0000]+/g, ' ').trim().slice(0, max) : ''
|
|
5
|
+
|
|
6
|
+
function parseHistoryUrl(value) {
|
|
7
|
+
let parsed
|
|
8
|
+
try { parsed = new URL(value) } catch { throw new Error('论文链接无效,请使用 HTTP(S) 原文链接') }
|
|
9
|
+
if (!['http:', 'https:'].includes(parsed.protocol)) throw new Error('论文链接只支持 HTTP(S)')
|
|
10
|
+
if (parsed.username || parsed.password) throw new Error('论文链接不能包含认证信息')
|
|
11
|
+
return parsed
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function normalizeHistoryItem(raw, { now = new Date().toISOString() } = {}) {
|
|
15
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('缺少论文浏览记录')
|
|
16
|
+
const title = clean(raw.title, 500)
|
|
17
|
+
if (!title) throw new Error('浏览记录缺少论文题名')
|
|
18
|
+
const paperId = paperIdRe.test(raw.paperId || '') ? raw.paperId : ''
|
|
19
|
+
let doi = clean(raw.doi, 2000)
|
|
20
|
+
if (/^https?:\/\//i.test(doi)) {
|
|
21
|
+
const parsed = parseHistoryUrl(doi)
|
|
22
|
+
if (!['doi.org', 'dx.doi.org'].includes(parsed.hostname)) throw new Error('论文 DOI 解析器链接无效')
|
|
23
|
+
doi = parsed.pathname.slice(1)
|
|
24
|
+
try { doi = decodeURIComponent(doi) } catch { /* 保留原 DOI 编码,继续校验。 */ }
|
|
25
|
+
}
|
|
26
|
+
doi = clean(doi, 200).toLowerCase()
|
|
27
|
+
if (doi && !/^10\.\d{4,9}\/\S+$/.test(doi)) throw new Error('论文 DOI 标识无效')
|
|
28
|
+
const arxivId = clean(raw.arxivId, 100).replace(/^arxiv:/i, '').replace(/v\d+$/i, '')
|
|
29
|
+
if (arxivId && !/^(?:\d{4}\.\d{4,5}|[a-z][a-z.-]*\/\d{7})$/i.test(arxivId)) throw new Error('论文 arXiv 标识无效')
|
|
30
|
+
let url = clean(raw.url || raw.absUrl, 2000)
|
|
31
|
+
if (url) {
|
|
32
|
+
const parsed = parseHistoryUrl(url)
|
|
33
|
+
// 历史只保留公开地址部分,签名参数与阅读定位均不持久化。
|
|
34
|
+
url = parsed.origin + parsed.pathname
|
|
35
|
+
}
|
|
36
|
+
if (!paperId && !doi && !arxivId && !url) throw new Error('浏览记录缺少论文标识或链接')
|
|
37
|
+
const id = doi ? 'doi:' + doi : arxivId ? 'arxiv:' + arxivId.toLowerCase() : url ? 'url:' + url : 'paper:' + paperId
|
|
38
|
+
return {
|
|
39
|
+
id, title,
|
|
40
|
+
...(doi ? { doi } : {}),
|
|
41
|
+
...(arxivId ? { arxivId } : {}),
|
|
42
|
+
...(url ? { url } : {}),
|
|
43
|
+
...(paperId ? { paperId } : {}),
|
|
44
|
+
source: clean(raw.source, 40) || (paperId ? 'library' : ''),
|
|
45
|
+
lastViewedAt: Number.isFinite(Date.parse(now)) ? new Date(now).toISOString() : new Date().toISOString(),
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function normalizeBrowseHistory(raw) {
|
|
50
|
+
if (!Array.isArray(raw)) return []
|
|
51
|
+
const items = []
|
|
52
|
+
for (const value of raw.slice(0, LIMIT * 2)) {
|
|
53
|
+
try {
|
|
54
|
+
items.push(normalizeHistoryItem(value, { now: value?.lastViewedAt }))
|
|
55
|
+
} catch { /* 损坏或旧格式条目不阻断正常界面状态。 */ }
|
|
56
|
+
}
|
|
57
|
+
const recentFirst = (a, b) => Date.parse(b.lastViewedAt) - Date.parse(a.lastViewedAt)
|
|
58
|
+
const groups = []
|
|
59
|
+
for (const item of items.sort(recentFirst)) {
|
|
60
|
+
const aliases = new Set(['doi', 'arxivId', 'url', 'paperId']
|
|
61
|
+
.filter(key => item[key])
|
|
62
|
+
.map(key => key + ':' + (key === 'doi' || key === 'arxivId' ? item[key].toLowerCase() : item[key])))
|
|
63
|
+
const matches = groups.filter(group => [...aliases].some(key => group.aliases.has(key)))
|
|
64
|
+
const merged = {}
|
|
65
|
+
// 最近记录优先,旧记录只补空字段;桥接记录可同时合并 DOI 与 arXiv 两组。
|
|
66
|
+
for (const value of [...matches.map(group => group.item), item].sort(recentFirst)) {
|
|
67
|
+
for (const [key, field] of Object.entries(value)) if (!merged[key] && field) merged[key] = field
|
|
68
|
+
}
|
|
69
|
+
for (const group of matches) {
|
|
70
|
+
for (const key of group.aliases) aliases.add(key)
|
|
71
|
+
groups.splice(groups.indexOf(group), 1)
|
|
72
|
+
}
|
|
73
|
+
groups.push({ item: normalizeHistoryItem(merged, { now: merged.lastViewedAt }), aliases })
|
|
74
|
+
}
|
|
75
|
+
return groups.map(group => group.item).sort(recentFirst).slice(0, LIMIT)
|
|
76
|
+
}
|