@li-canghai/dsh-paper 0.8.0 → 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.
@@ -1,35 +1,35 @@
1
- $ErrorActionPreference = 'Stop'
2
- [Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)
3
- [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
4
-
5
- try {
6
- $Request = [Console]::In.ReadToEnd() | ConvertFrom-Json
7
- if ($Request.task -eq 'certificates') {
8
- $Certificates = @()
9
- foreach ($Location in @('CurrentUser', 'LocalMachine')) {
10
- foreach ($StoreName in @('Root', 'CertificateAuthority')) {
11
- $Store = New-Object System.Security.Cryptography.X509Certificates.X509Store($StoreName, $Location)
12
- try {
13
- $Store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly)
14
- foreach ($Certificate in $Store.Certificates) {
15
- $Certificates += '-----BEGIN CERTIFICATE-----' + "`n" + [Convert]::ToBase64String($Certificate.RawData) + "`n-----END CERTIFICATE-----"
16
- }
17
- } finally { $Store.Close() }
18
- }
19
- }
20
- @{ certificates = @($Certificates) } | ConvertTo-Json -Compress
21
- exit 0
22
- }
23
- $Destination = [Uri]$Request.url
24
- if ($Destination.Scheme -notin @('http', 'https')) { exit 1 }
25
- $SystemProxy = [System.Net.WebRequest]::GetSystemWebProxy()
26
- $ProxyAddress = $SystemProxy.GetProxy($Destination)
27
- $Address = $null
28
- if ($null -ne $ProxyAddress -and $ProxyAddress.AbsoluteUri -ne $Destination.AbsoluteUri) {
29
- $Address = $ProxyAddress.AbsoluteUri
30
- }
31
- @{ proxy = $Address } | ConvertTo-Json -Compress
32
- } catch {
33
- # Configuration values and proxy authentication details stay out of diagnostics.
34
- exit 1
35
- }
1
+ $ErrorActionPreference = 'Stop'
2
+ [Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)
3
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
4
+
5
+ try {
6
+ $Request = [Console]::In.ReadToEnd() | ConvertFrom-Json
7
+ if ($Request.task -eq 'certificates') {
8
+ $Certificates = @()
9
+ foreach ($Location in @('CurrentUser', 'LocalMachine')) {
10
+ foreach ($StoreName in @('Root', 'CertificateAuthority')) {
11
+ $Store = New-Object System.Security.Cryptography.X509Certificates.X509Store($StoreName, $Location)
12
+ try {
13
+ $Store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly)
14
+ foreach ($Certificate in $Store.Certificates) {
15
+ $Certificates += '-----BEGIN CERTIFICATE-----' + "`n" + [Convert]::ToBase64String($Certificate.RawData) + "`n-----END CERTIFICATE-----"
16
+ }
17
+ } finally { $Store.Close() }
18
+ }
19
+ }
20
+ @{ certificates = @($Certificates) } | ConvertTo-Json -Compress
21
+ exit 0
22
+ }
23
+ $Destination = [Uri]$Request.url
24
+ if ($Destination.Scheme -notin @('http', 'https')) { exit 1 }
25
+ $SystemProxy = [System.Net.WebRequest]::GetSystemWebProxy()
26
+ $ProxyAddress = $SystemProxy.GetProxy($Destination)
27
+ $Address = $null
28
+ if ($null -ne $ProxyAddress -and $ProxyAddress.AbsoluteUri -ne $Destination.AbsoluteUri) {
29
+ $Address = $ProxyAddress.AbsoluteUri
30
+ }
31
+ @{ proxy = $Address } | ConvertTo-Json -Compress
32
+ } catch {
33
+ # Configuration values and proxy authentication details stay out of diagnostics.
34
+ exit 1
35
+ }
@@ -92,26 +92,37 @@ def _text_page(page, index: int, output_dir: Path, page_count: int):
92
92
  raise ValueError("PDF text coordinate conversion failed")
93
93
  return [px.value * 1000 / device_width, py.value * 1000 / device_height]
94
94
 
95
+ def char_box(at):
96
+ left, bottom, right, top = text.get_charbox(at, loose=True)
97
+ corners = [point(left, bottom), point(left, top), point(right, bottom), point(right, top)]
98
+ return [min(p[0] for p in corners), min(p[1] for p in corners),
99
+ max(p[0] for p in corners), max(p[1] for p in corners)]
100
+
95
101
  words = []
96
- letters, boxes = [], []
102
+ letters, boxes, glyphs = [], [], []
97
103
 
98
104
  def flush():
99
105
  if letters and boxes:
100
106
  words.append({"text": "".join(letters), "bbox": [
101
107
  min(box[0] for box in boxes), min(box[1] for box in boxes),
102
108
  max(box[2] for box in boxes), max(box[3] for box in boxes),
103
- ]})
109
+ ], "chars": list(glyphs)})
104
110
  letters.clear()
105
111
  boxes.clear()
112
+ glyphs.clear()
106
113
 
107
114
  text = page.get_textpage()
108
115
  try:
109
116
  for at in range(text.count_chars()):
110
117
  letter = text.get_text_range(at, 1)
111
118
  # PDFium replaces a discretionary line-end hyphen with U+FFFE and
112
- # omits the line break. Keep its physical word on this line.
119
+ # omits the line break. The sentinel still has a native char box:
120
+ # preserve it so a page-final "high-" remains character-aligned.
113
121
  if letter == "\ufffe":
122
+ box = char_box(at)
114
123
  letters.append("-")
124
+ boxes.append(box)
125
+ glyphs.append({"text": "-", "bbox": box})
115
126
  flush()
116
127
  continue
117
128
  if not letter or letter.isspace() or ord(letter[0]) < 32:
@@ -122,10 +133,13 @@ def _text_page(page, index: int, output_dir: Path, page_count: int):
122
133
  box = [min(p[0] for p in corners), min(p[1] for p in corners), max(p[0] for p in corners), max(p[1] for p in corners)]
123
134
  letters.append(letter)
124
135
  boxes.append(box)
136
+ # 与 PDFium 每一个原生字符一一对应;不能只保存整词 bbox:
137
+ # 等宽/斜体/压缩字体的字内位置与浏览器 serif 差异可超过 10 PDF px。
138
+ glyphs.append({"text": letter, "bbox": box})
125
139
  flush()
126
140
  finally:
127
141
  text.close()
128
- result = {"schemaVersion": 2, "page": index, "pageCount": page_count, "width": width, "height": height, "words": words}
142
+ result = {"schemaVersion": 3, "page": index, "pageCount": page_count, "width": width, "height": height, "words": words}
129
143
  target = output_dir / f"{index}.text.json"
130
144
  temporary = target.with_name(f".{target.name}.{os.getpid()}.tmp")
131
145
  temporary.write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
package/lib/pdf-page.js CHANGED
@@ -76,6 +76,10 @@ export function cropPdfGroups(page, groups, canvas) {
76
76
  words: group.words.map(word => ({
77
77
  ...word,
78
78
  bbox: mapBox(word.bbox),
79
+ // gap 是水平长度,不是坐标点:裁后 0–1000 画布缩窄 visible.width,
80
+ // 因此长度必须除以同一个比例。客户端随后乘裁后页宽,物理像素间距才不变。
81
+ gap: Number.isFinite(word.gap) ? word.gap / visible.width : word.gap,
82
+ ...(Array.isArray(word.chars) ? { chars: word.chars.map(char => ({ ...char, bbox: mapBox(char.bbox) })) } : {}),
79
83
  line: Array.isArray(word.line) && word.line.length === 2
80
84
  ? [mapY(word.line[0]), mapY(word.line[1])]
81
85
  : word.line,
@@ -95,10 +99,15 @@ function clamp1000(value) {
95
99
  }
96
100
 
97
101
  export function validPdfPage(value, page) {
98
- return value?.schemaVersion === 2 && value.page === page
102
+ return value?.schemaVersion === 3 && value.page === page
99
103
  && Number.isSafeInteger(value.pageCount) && value.pageCount >= page
100
104
  && Number.isFinite(value.width) && value.width > 0 && Number.isFinite(value.height) && value.height > 0
101
- && Array.isArray(value.words) && value.words.every(word => typeof word?.text === 'string' && validBox(word.bbox))
105
+ // v3 adds PDFium character positions. Also require complete text coverage:
106
+ // older v3 caches omitted the native box for PDFium's U+FFFE line-end hyphen.
107
+ // Reject them so readPdfPage rebuilds the cache with the complete glyph sequence.
108
+ && Array.isArray(value.words) && value.words.every(word => typeof word?.text === 'string' && validBox(word.bbox)
109
+ && Array.isArray(word.chars) && word.chars.every(char => typeof char?.text === 'string' && char.text.length > 0 && validBox(char.bbox))
110
+ && word.chars.map(char => char.text).join('') === word.text)
102
111
  }
103
112
 
104
113
  function validBox(box) {
@@ -111,10 +120,20 @@ function sameLine(a, b) {
111
120
 
112
121
  const matchingText = value => plainInlineText(value).normalize('NFKC').toLowerCase().replace(/[^\p{L}\p{N}]/gu, '')
113
122
 
114
- /** Match physical PDF lines to parsed paragraph ids; figure boxes may exclude their captions. */
123
+ /**
124
+ * **结构性块**:文字在 caption 里,PDF 文字层的正文词永远不该归给它们。
125
+ *
126
+ * 🔴 判据必须是块类型而不是"有没有 sourceText":text 块里有 5.8% 是跨页续文的尾部
127
+ * (sourceText 为空但文字层有词),按"有没有字"判会把它们一起改坏。
128
+ * 实测全库:table / image / chart / code 四类 100% 无 sourceText,而 text 只 5.8%。
129
+ */
130
+ const STRUCTURAL_KINDS = new Set(['image', 'figure', 'table', 'chart', 'code'])
131
+
115
132
  export function pdfPageGroups(page, blocks) {
116
133
  const rows = (Array.isArray(blocks) ? blocks : []).filter(block => block.page === page.page && validBox(block.bbox))
117
134
  const texts = new Map(rows.map(row => [row.id, matchingText(row.sourceText ?? '')]))
135
+ // 块类型:结构性块不参与正文词归属(见 STRUCTURAL_KINDS)。
136
+ const styles = new Map(rows.map(row => [row.id, String(row.type ?? '')]))
118
137
  const lines = []
119
138
  for (const word of page.words) {
120
139
  const previous = lines.at(-1)?.words.at(-1)
@@ -129,18 +148,67 @@ export function pdfPageGroups(page, blocks) {
129
148
  const matches = text.length >= 12 ? rows.filter(row => texts.get(row.id).includes(text)) : []
130
149
  const x = (line.words[0].bbox[0] + line.words.at(-1).bbox[2]) / 2
131
150
  const y = line.words.reduce((sum, word) => sum + (word.bbox[1] + word.bbox[3]) / 2, 0) / line.words.length
132
- let chosen = null, best = Infinity
133
- for (const row of matches.length ? matches : rows) {
151
+ // 🔴 **结构性块(图片 / 图表 / 表格 / 代码)只在它压着正文时才退让**,其余情形照旧。
152
+ //
153
+ // 背景:图片 / 图表的 bbox 常常压在正文段落上。兜底分支按 score 挑最近的块时,第二项
154
+ // 是包含框面积,面积更小的那一方胜出 —— 于是图片块把正文行抢走。后果远不止少一行字:
155
+ // 同一段文字被拆进**两个 DOM 容器**,渲染顺序随块顺序断开,浏览器按 DOM 顺序铺开原生
156
+ // 选区,用户从段首拖到中间就整段涂蓝(实测 ResNet 第 2 页首段:image 块 blk-24 面积
157
+ // 39163 < 正文块 blk-23 的 77815,抢走 3 行含行内公式的文字,复制出来的顺序因此呈现
158
+ // "公式那几行跑到末尾")。
159
+ //
160
+ // 🔴 那一行**为什么匹配不上正文块**:blk-23 的 sourceText 是 LaTeX
161
+ // (`$\mathcal{H}(\mathbf{x})$`),经 matchingText 后是 `mathcalhmathbfx`,而 PDF 文字层
162
+ // 抽出来的是排版后的 `H(x)` —— 两者永远对不上,所以这批行必然走兜底分支。
163
+ // 也就是说,靠"内容匹配"挡不住它,判据必须落在几何上。
164
+ const scoreOf = row => {
134
165
  const [left, top, right, bottom] = row.bbox
135
166
  const dx = Math.max(left - x, 0, x - right), dy = Math.max(top - y, 0, y - bottom)
136
- const score = Math.hypot(dx, dy) * 1000000 + (right - left) * (bottom - top)
137
- if ((matches.length || Math.hypot(dx, dy) <= 50) && score < best) { best = score; chosen = row }
167
+ return { distance: Math.hypot(dx, dy), score: Math.hypot(dx, dy) * 1000000 + (right - left) * (bottom - top) }
168
+ }
169
+ /**
170
+ * 这一行抢不抢得走:结构性块(图片/图表)只有在**不与任何文字块重叠**时才配拿词。
171
+ *
172
+ * 🔴 判据必须是「几何重叠」而不是「有没有 sourceText」也不是「无条件惩罚」——
173
+ * 两者都被实测否掉了:
174
+ * · 按 sourceText 判:text 块有 5.8% 是跨页续文尾部(sourceText 空但有词),会误伤;
175
+ * · 无条件惩罚:表格自己格子里的字(ResNet p7 blk-119 的 "output map size 32×32…"
176
+ * 夹在 blk-116 与 blk-120 之间、不与任何文字块重叠)会被整批赶走。
177
+ * 而图片块 blk-24 与正文块 blk-23 重叠 69% —— 它罩住的词本来就是正文的。
178
+ */
179
+ const overlapsText = row => rows.some(other => other !== row
180
+ && !STRUCTURAL_KINDS.has(styles.get(other.id))
181
+ && row.bbox[0] < other.bbox[2] && other.bbox[0] < row.bbox[2]
182
+ && row.bbox[1] < other.bbox[3] && other.bbox[1] < row.bbox[3])
183
+ const pick = (candidates) => {
184
+ let chosenRow = null, bestScore = Infinity
185
+ for (const row of candidates) {
186
+ const { distance, score } = scoreOf(row)
187
+ if (!matches.length && distance > 50) continue
188
+ if (score < bestScore) { bestScore = score; chosenRow = row }
189
+ }
190
+ return chosenRow
138
191
  }
192
+ const pool = matches.length ? matches : rows
193
+ // 第一轮:内容匹配里有没有文字块 —— 有就直接在那些里挑(公式行的 matches 为空,走第二轮)。
194
+ const textMatched = matches.filter(row => !STRUCTURAL_KINDS.has(styles.get(row.id)))
195
+ let chosen = textMatched.length > 0 ? pick(textMatched) : null
196
+ // 第二轮:在**不与文字块重叠**的候选里挑。文字块永远在内,结构性块看它是否压着正文。
197
+ if (chosen === null) chosen = pick(pool.filter(row => !STRUCTURAL_KINDS.has(styles.get(row.id)) || !overlapsText(row)))
198
+ // 第三轮:实在没有候选(例如整页只有一张图),才放开限制。
199
+ if (chosen === null) chosen = pick(pool)
139
200
  if (!chosen) continue
140
201
  if (!grouped.has(chosen.id)) grouped.set(chosen.id, { id: chosen.id, words: [] })
141
202
  for (const word of line.words) {
142
203
  const text = word.text.normalize('NFKC').replace(/\u00ad/g, '')
143
- if (text) grouped.get(chosen.id).words.push({ text, bbox: word.bbox })
204
+ if (text) grouped.get(chosen.id).words.push({
205
+ text, bbox: word.bbox,
206
+ // Preserve native boxes through paragraph grouping. The browser only
207
+ // uses them when the full normalized string matches one-to-one.
208
+ ...(Array.isArray(word.chars) ? { chars: word.chars.map(char => ({
209
+ text: char.text.normalize('NFKC').replace(/\u00ad/g, ''), bbox: char.bbox,
210
+ })) } : {}),
211
+ })
144
212
  }
145
213
  }
146
214
  return [...grouped.values()].filter(group => group.words.length > 0).map(group => {
@@ -164,7 +232,17 @@ export function pdfPageGroups(page, blocks) {
164
232
  // 「含空格的字串」等分,负字距被算大、整词的字被压窄;行末空格又被浏览器悬挂/裁掉,
165
233
  // 选区右沿于是止于倒数一个字形,末字右边那一格永远盖不住。
166
234
  const sameLine = next !== undefined && next.line === word.line
167
- return { text: (joined ? word.text.slice(0, -1) : word.text) + (sameLine && !joined ? ' ' : ''), bbox: word.bbox,
235
+ const nativeChars = Array.isArray(word.chars) ? word.chars : null
236
+ const trimmedHyphen = joined && nativeChars?.at(-1)?.text === '-'
237
+ const chars = trimmedHyphen ? nativeChars.slice(0, -1) : nativeChars
238
+ // When the normalized paragraph joins a line-end hyphen to the next
239
+ // line, remove it from text, glyphs, and the visible word edge together.
240
+ // A page-final hyphen is not joined and keeps its own native glyph box.
241
+ const bbox = trimmedHyphen && chars.length
242
+ ? [word.bbox[0], word.bbox[1], Math.max(...chars.map(char => char.bbox[2])), word.bbox[3]]
243
+ : word.bbox
244
+ return { text: (joined ? word.text.slice(0, -1) : word.text) + (sameLine && !joined ? ' ' : ''), bbox,
245
+ ...(chars ? { chars } : {}),
168
246
  line: [word.line.top, word.line.bottom], gap: sameLine ? Math.max(0, next.bbox[0] - word.bbox[2]) : 0 }
169
247
  })
170
248
  const bbox = words.reduce((box, word) => [Math.min(box[0], word.bbox[0]), Math.min(box[1], word.line[0]), Math.max(box[2], word.bbox[2]), Math.max(box[3], word.line[1])], [Infinity, Infinity, -Infinity, -Infinity])
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@li-canghai/dsh-paper",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "description": "PDF transcription with stable block ids, folder scanning up to two sub-levels, and session-scoped paper context with drag-select batch injection and removal for DSH.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",