@li-canghai/dsh-paper 0.0.0-stage → 0.8.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.
Files changed (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -2
  3. package/cordis.patch.yml +4 -0
  4. package/lib/annotate-tool.js +334 -0
  5. package/lib/arxiv-id.js +74 -0
  6. package/lib/asset-routes.js +210 -0
  7. package/lib/bibliography-formats.js +126 -0
  8. package/lib/bibliography-import.js +105 -0
  9. package/lib/bibliography-service.js +43 -0
  10. package/lib/bibliography.js +42 -0
  11. package/lib/block-authors.js +292 -0
  12. package/lib/block-cache.js +39 -0
  13. package/lib/blocks-markdown.js +157 -0
  14. package/lib/blocks-reconcile.js +218 -0
  15. package/lib/blocks.js +1344 -0
  16. package/lib/citation-metadata.js +260 -0
  17. package/lib/citation-styles.js +120 -0
  18. package/lib/client-parts/01-pure-helpers.js +2762 -0
  19. package/lib/client-parts/02-author-year.js +95 -0
  20. package/lib/client.js +10381 -0
  21. package/lib/code-source.js +68 -0
  22. package/lib/concurrency-gate.js +91 -0
  23. package/lib/context.js +233 -0
  24. package/lib/csl/SOURCES.md +10 -0
  25. package/lib/csl/gb-t-7714.csl +441 -0
  26. package/lib/csl/ieee.csl +520 -0
  27. package/lib/csl/locales-zh-CN.xml +438 -0
  28. package/lib/csl/nature.csl +190 -0
  29. package/lib/discussion.js +400 -0
  30. package/lib/documents.js +67 -0
  31. package/lib/export.js +848 -0
  32. package/lib/file-lock.js +177 -0
  33. package/lib/gloss.js +181 -0
  34. package/lib/glossary.js +279 -0
  35. package/lib/index.js +3862 -0
  36. package/lib/inline-html.js +53 -0
  37. package/lib/install-dependency.js +120 -0
  38. package/lib/item-ops.js +83 -0
  39. package/lib/job-facade.js +58 -0
  40. package/lib/json-store.js +54 -0
  41. package/lib/library-model.js +132 -0
  42. package/lib/library-service.js +180 -0
  43. package/lib/library-tool.js +982 -0
  44. package/lib/library.js +814 -0
  45. package/lib/markdown-assets.js +138 -0
  46. package/lib/markdown-literals.js +93 -0
  47. package/lib/metadata-enrichment.js +516 -0
  48. package/lib/metadata-fetch.js +146 -0
  49. package/lib/metadata-node.js +158 -0
  50. package/lib/metadata-proxy.ps1 +35 -0
  51. package/lib/mineru-config.js +95 -0
  52. package/lib/mineru-sdk-helper.py +123 -0
  53. package/lib/mineru-sdk.js +182 -0
  54. package/lib/mineru.js +268 -0
  55. package/lib/mirror-export.js +240 -0
  56. package/lib/outline.js +296 -0
  57. package/lib/page-image-helper.py +308 -0
  58. package/lib/page-image.js +454 -0
  59. package/lib/paper-metadata.js +242 -0
  60. package/lib/parse-export.js +631 -0
  61. package/lib/pdf-analysis-tool.js +750 -0
  62. package/lib/pdf-metadata-helper.py +75 -0
  63. package/lib/pdf-metadata.js +141 -0
  64. package/lib/pdf-page.js +261 -0
  65. package/lib/pdf-scan.js +134 -0
  66. package/lib/pdf-text.js +68 -0
  67. package/lib/picker.js +305 -0
  68. package/lib/portable.js +379 -0
  69. package/lib/purge.js +170 -0
  70. package/lib/read-tool.js +660 -0
  71. package/lib/reader-store.js +497 -0
  72. package/lib/reading-order.js +207 -0
  73. package/lib/rename-document.js +480 -0
  74. package/lib/rename.js +372 -0
  75. package/lib/renderer-status.js +161 -0
  76. package/lib/resolver.js +1152 -0
  77. package/lib/result-archive.js +157 -0
  78. package/lib/revisions.js +330 -0
  79. package/lib/search-database.js +62 -0
  80. package/lib/search-index.js +601 -0
  81. package/lib/search-scan.js +185 -0
  82. package/lib/search-source.js +23 -0
  83. package/lib/search-terms.js +539 -0
  84. package/lib/section-audit.js +209 -0
  85. package/lib/selection-message.js +332 -0
  86. package/lib/serial-tail.js +21 -0
  87. package/lib/slicing.js +425 -0
  88. package/lib/source-resolver.js +581 -0
  89. package/lib/stem-repair.js +189 -0
  90. package/lib/storage.js +562 -0
  91. package/lib/store-paths.js +253 -0
  92. package/lib/table-gfm.js +236 -0
  93. package/lib/tasks.js +270 -0
  94. package/lib/tex-align.js +509 -0
  95. package/lib/tex-blocks.js +653 -0
  96. package/lib/tex-fetch.js +455 -0
  97. package/lib/tex-figures.js +140 -0
  98. package/lib/tex-inline.js +166 -0
  99. package/lib/tex-merge.js +279 -0
  100. package/lib/tex-pipeline.js +242 -0
  101. package/lib/tex-prepare.js +746 -0
  102. package/lib/tex-tables.js +210 -0
  103. package/lib/text-similarity.js +85 -0
  104. package/lib/tool-contract.js +86 -0
  105. package/lib/tool-host.js +1058 -0
  106. package/lib/tool-identity.js +214 -0
  107. package/lib/translatable-text.js +48 -0
  108. package/lib/translate-prompts.js +709 -0
  109. package/lib/translate-queue.js +418 -0
  110. package/lib/translate-task.js +158 -0
  111. package/lib/translate.js +909 -0
  112. package/lib/update-check.js +438 -0
  113. package/lib/update-contracts.js +75 -0
  114. package/lib/usage.js +282 -0
  115. package/package.json +55 -4
@@ -0,0 +1,185 @@
1
+ /**
2
+ * 跨篇检索的**扫描实现** —— 索引出现之前的唯一实现,现在是**回退基准**。
3
+ *
4
+ * 它读全部候选篇的 Markdown、切块、逐段打分。慢(73 篇 ~340 ms),但不需要任何额外文件,
5
+ * 所以它定义了「正确答案」:索引路径必须与它逐条相同(`search-equivalence.test.js` 钉住)。
6
+ *
7
+ * 打分与切词一律从 `search-terms.js` 取 —— 与索引路径共用同一份词干化与同一张种类权重表。
8
+ */
9
+
10
+ import { markedSegments } from './blocks.js'
11
+ import { readSearchMarkdown } from './search-source.js'
12
+ import {
13
+ clampSearchOffset, clampSnippetChars, degradedMinHits, isPlainWord, kindWeightOf, parseQuery,
14
+ scoreOfBlock, scoreSegment, SCORING_VERSION, snippetOf, stemOf, withPartialHitBoost,
15
+ } from './search-terms.js'
16
+ import { hydrateDocument } from './portable.js'
17
+
18
+ /**
19
+ * 扫一遍候选篇,给出**整条全序**(不切片、不截片段)。
20
+ *
21
+ * 全序的定序键与索引路径逐项相同:得分降序 → 论文相关度 → 篇 id → 篇内块序号。
22
+ * 最后两项让同分时两条路径排出**同一条序列** —— 否则同一个 offset 在两边指向不同位置,
23
+ * 翻页就不可复现。
24
+ *
25
+ * @param {{records: object[], query: string, limit?: number, offset?: number, snippetChars?: number,
26
+ * skipIds?: Set<string>}} input `skipIds` = 调用方已经证明不可能命中的篇(正文里没有查询
27
+ * 所需的字符)。它们不读盘、不切词,但仍计入 `scanned`:那不是「没搜」,是「搜过、确定不命中」。
28
+ * @returns {Promise<{rows: object[], matched: number, scanned: number, unmarked: string[]}>}
29
+ */
30
+ export async function scanMatches(input) {
31
+ // 两遍:先严格 AND,零命中时才放宽到多数单元命中。
32
+ // 为什么不在同一遍里「先试全命中、不中再降级」:那会让 stats(块数/块长/df)在两次
33
+ // 之间累积,BM25 的分母跟着翻倍,分数与索引路径就对不上了。重扫一遍是最不容易错的做法,
34
+ // 而它只在「本来一条都搜不到」的时候发生 —— 那条路上本来就没什么可失去的。
35
+ const strict = await scanOnce(input)
36
+ if (strict.matched > 0) return strict
37
+ const { words, phrases } = parseQuery(input.query ?? '')
38
+ // 单词语查询不存在「部分命中」:退化与严格是同一件事,省一次全库重扫。
39
+ if (words.length + phrases.length <= 1) return strict
40
+ const minHits = degradedMinHits(words.length + phrases.length)
41
+ if (minHits >= words.length + phrases.length) return strict
42
+ const degraded = await scanOnce({ ...input, minHits })
43
+ return degraded.matched > 0
44
+ ? { ...degraded, degraded: true, totalUnits: words.length + phrases.length }
45
+ : strict
46
+ }
47
+
48
+ /**
49
+ * 一趟扫描。\`minHits\` 缺省 = 严格 AND(全部单元命中)。
50
+ */
51
+ async function scanOnce({
52
+ records, query, snippetChars, scoringVersion = SCORING_VERSION, skipIds, minHits, order = 'score',
53
+ }) {
54
+ const { words, phrases } = parseQuery(query)
55
+ const stemCache = new Map()
56
+ const wantedWords = words.map(term => ({
57
+ term,
58
+ plain: isPlainWord(term),
59
+ stem: isPlainWord(term) ? stemOf(term) : '',
60
+ }))
61
+
62
+ // BM25 的分母(块数、平均块长、每词出现在多少块)要在**判定之后**才有,
63
+ // 所以先收集命中量与块长度,第二遍再折算成分数。两遍都在内存里,不额外读盘。
64
+
65
+ const stats = { blocks: 0, length: 0, df: new Map() }
66
+ const found = []
67
+ const unmarked = []
68
+ const unreadable = []
69
+ let scanned = 0
70
+ for (const raw of records) {
71
+ const document = hydrateDocument(raw)
72
+ const markdownPath = typeof document.markdownPath === 'string' ? document.markdownPath : ''
73
+ if (markdownPath === '') { unreadable.push(document.pdfName ?? String(raw.id)); continue }
74
+ if (skipIds !== undefined && skipIds.has(raw.id)) {
75
+ scanned += 1
76
+ continue
77
+ }
78
+ let markdown
79
+ // 文件不见了就是这篇搜不到:一次检索不该因为一篇的磁盘问题整次失败。
80
+ try { markdown = await readSearchMarkdown(document) } catch { unreadable.push(document.pdfName ?? String(raw.id)); continue }
81
+ const segments = markedSegments(markdown, { preserveIndent: true })
82
+ if (segments.length === 0) {
83
+ unmarked.push(document.pdfName ?? String(raw.id))
84
+ continue
85
+ }
86
+ scanned += 1
87
+ const rows = []
88
+ for (let index = 0; index < segments.length; index += 1) {
89
+ const segment = segments[index]
90
+ const hit = scoreSegment(segment.text, wantedWords, phrases, stemCache, stats, minHits)
91
+ if (hit === null) continue
92
+ rows.push({
93
+ blockId: segment.blockId,
94
+ index,
95
+ flat: hit.flat,
96
+ firstAt: hit.firstAt,
97
+ occurrences: hit.occurrences,
98
+ counts: hit.counts,
99
+ length: hit.length,
100
+ weight: kindWeightOf(segment.blockId),
101
+ // 命中几个查询单元 —— 退化检索靠它把「更全的块」排在前面。
102
+ hitUnits: hit.hitUnits,
103
+ totalUnits: hit.totalUnits,
104
+ })
105
+ }
106
+ if (rows.length === 0) continue
107
+ found.push({ paper: document.pdfName ?? String(raw.id), documentId: raw.id, rows })
108
+ }
109
+
110
+ // 第二遍:df / 平均块长都齐了,按选定的评分版本折算。v1 与索引路径的
111
+ // 「出现次数 × 种类权重」逐字节相同;v2 是 Σ BM25 × 种类权重。
112
+ const averageLength = stats.blocks > 0 ? stats.length / stats.blocks : 0
113
+ for (const entry of found) {
114
+ for (const row of entry.rows) {
115
+ row.score = withPartialHitBoost(scoreOfBlock({
116
+ occurrences: row.occurrences,
117
+ weight: row.weight,
118
+ termFrequencies: row.counts,
119
+ documentFrequencies: stats.df,
120
+ blockCount: stats.blocks,
121
+ blockLength: row.length,
122
+ averageLength,
123
+ scoringVersion,
124
+ }), row)
125
+ }
126
+ entry.rank = entry.rows.reduce((sum, row) => sum + row.score, 0)
127
+ }
128
+
129
+ // 论文之间按整篇得分排:paperRank 回答「哪几篇最相关」,与段落的 score 是两件事。
130
+ // 篇级定序与索引路径逐项相同:整篇得分降序 → 篇名 → 篇 id。
131
+ found.sort((a, b) => b.rank - a.rank
132
+ || a.paper.localeCompare(b.paper)
133
+ || a.documentId.localeCompare(b.documentId))
134
+ const paperRankOf = new Map(found.map((entry, index) => [entry.documentId, index + 1]))
135
+
136
+ const ordered = []
137
+ for (const entry of found) {
138
+ for (const row of entry.rows) {
139
+ ordered.push({
140
+ paper: entry.paper,
141
+ documentId: entry.documentId,
142
+ blockId: row.blockId,
143
+ index: row.index,
144
+ paperRank: paperRankOf.get(entry.documentId) ?? 1,
145
+ score: row.score,
146
+ flat: row.flat,
147
+ firstAt: row.firstAt,
148
+ hitUnits: row.hitUnits,
149
+ totalUnits: row.totalUnits,
150
+ })
151
+ }
152
+ }
153
+ ordered.sort((a, b) => (order === 'paper' ? a.paperRank - b.paperRank : 0)
154
+ || b.score - a.score
155
+ || a.paperRank - b.paperRank
156
+ || a.documentId.localeCompare(b.documentId)
157
+ || a.index - b.index)
158
+
159
+ return { rows: ordered, matched: ordered.length, scanned, unmarked, unreadable }
160
+ }
161
+
162
+ /**
163
+ * 把一条全序切成这一页,并给每条补上片段。
164
+ *
165
+ * 片段只给这一页做:全量 556 条都截一遍是白花的钱。两条路径共用它,片段的截法才不会分叉。
166
+ *
167
+ * @param {{rows: object[], offset: number, limit: number, snippetChars: number}} input
168
+ */
169
+ export function pageOf({ rows, offset, limit, snippetChars }) {
170
+ const width = clampSnippetChars(snippetChars)
171
+ return rows.slice(offset, offset + limit).map(row => ({
172
+ paper: row.paper,
173
+ documentId: row.documentId,
174
+ blockId: row.blockId,
175
+ paperRank: row.paperRank,
176
+ score: Math.round(row.score * 100) / 100,
177
+ snippet: snippetOf(row.flat, row.firstAt, width),
178
+ // 只在部分命中时回:全词命中是常态,写出来只是噪声。
179
+ ...(Number.isFinite(row.hitUnits) && Number.isFinite(row.totalUnits) && row.hitUnits < row.totalUnits
180
+ ? { matched: row.hitUnits + '/' + row.totalUnits }
181
+ : {}),
182
+ }))
183
+ }
184
+
185
+ export { clampSearchOffset }
@@ -0,0 +1,23 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { readFile } from 'node:fs/promises'
3
+ import { createBlockReader } from './block-cache.js'
4
+ import { repairAssetMarkers } from './blocks.js'
5
+
6
+ const readBlocks = createBlockReader()
7
+
8
+ /** Include the repair rule and block-list bytes without parsing every unchanged paper on each query. */
9
+ export async function searchContentFingerprint(document) {
10
+ if (typeof document.contentPath !== 'string' || document.contentPath === '') return ''
11
+ try {
12
+ return createHash('sha256').update('asset-markers:v1\0').update(await readFile(document.contentPath)).digest('hex')
13
+ } catch { return 'asset-markers:v1:unavailable' }
14
+ }
15
+
16
+ /** Legacy asset markers are derived in memory; stored Markdown and user anchors remain untouched. */
17
+ export async function readSearchMarkdown(document, source) {
18
+ const markdown = source ?? (typeof document.markdown === 'string' ? document.markdown : await readFile(document.markdownPath, 'utf8'))
19
+ if (!/^<!-- b:[\w.-]+ -->\r?$/m.test(markdown)) return markdown
20
+ if (typeof document.contentPath !== 'string' || document.contentPath === '') return markdown
21
+ const { blocks } = await readBlocks(document.contentPath)
22
+ return repairAssetMarkers(markdown, blocks)
23
+ }