@dsh-libing/knowledge-base 0.1.3 → 0.1.4
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 +4 -0
- package/README.md +4 -0
- package/lib/agent-access.d.ts +23 -0
- package/lib/agent-access.js +28 -0
- package/lib/chunks.js +27 -5
- package/lib/client.js +9 -9
- package/lib/config.js +9 -1
- package/lib/document/convert.js +52 -16
- package/lib/document/pdf-layout.js +45 -10
- package/lib/document/pdf-session.js +10 -4
- package/lib/document/pdf-vision.js +8 -3
- package/lib/document/pdf-worker.js +76 -21
- package/lib/document/pdf.js +39 -9
- package/lib/document/zip.js +14 -6
- package/lib/figures/image-client.js +9 -4
- package/lib/figures/image-worker.js +15 -6
- package/lib/figures/process.js +13 -3
- package/lib/index.js +6 -2
- package/lib/indexes.js +8 -4
- package/lib/job-storage.js +6 -3
- package/lib/jobs.js +18 -9
- package/lib/models.js +7 -2
- package/lib/retrieval.js +36 -9
- package/lib/routes.js +58 -15
- package/lib/runtime.js +9 -3
- package/lib/skills.js +6 -3
- package/lib/store.js +29 -14
- package/lib/tools.js +12 -4
- package/lib/util.js +2 -1
- package/package.json +1 -1
package/lib/config.js
CHANGED
|
@@ -10,4 +10,12 @@ export function resolveConfig(raw = {}) {
|
|
|
10
10
|
return settingsSchema.parse({ ...raw, dataRoot });
|
|
11
11
|
}
|
|
12
12
|
const defaults = resolveConfig();
|
|
13
|
-
export const Config = Schema.object(Object.fromEntries(Object.entries(defaults).filter(([key]) => !['skipImages', 'acceptPartial'].includes(key)).map(([key, value]) => [key,
|
|
13
|
+
export const Config = Schema.object(Object.fromEntries(Object.entries(defaults).filter(([key]) => !['skipImages', 'acceptPartial'].includes(key)).map(([key, value]) => [key, (() => {
|
|
14
|
+
if (typeof value === 'number') {
|
|
15
|
+
return Schema.number().min(1).default(value);
|
|
16
|
+
}
|
|
17
|
+
if (typeof value === 'string') {
|
|
18
|
+
return Schema.string().default(value);
|
|
19
|
+
}
|
|
20
|
+
return Schema.boolean().default(value);
|
|
21
|
+
})()])));
|
package/lib/document/convert.js
CHANGED
|
@@ -12,7 +12,15 @@ import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
|
|
12
12
|
import { tmpdir } from 'node:os';
|
|
13
13
|
const parser = new XMLParser({ ignoreAttributes: false, removeNSPrefix: true, parseTagValue: false, trimValues: false });
|
|
14
14
|
const xmlSchema = z.lazy(() => z.union([z.string(), z.number(), z.boolean(), z.null(), z.array(xmlSchema), z.record(z.string(), xmlSchema)]));
|
|
15
|
-
const list = (value) =>
|
|
15
|
+
const list = (value) => {
|
|
16
|
+
if (value === undefined) {
|
|
17
|
+
return [];
|
|
18
|
+
}
|
|
19
|
+
if (Array.isArray(value)) {
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
return [value];
|
|
23
|
+
};
|
|
16
24
|
const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
17
25
|
function child(value, ...keys) {
|
|
18
26
|
for (const key of keys)
|
|
@@ -43,8 +51,13 @@ function wordText(value) {
|
|
|
43
51
|
}
|
|
44
52
|
const normalize = (value) => value.replace(/\s/gu, '');
|
|
45
53
|
function audit(files) {
|
|
46
|
-
const doc = parseXml(required(files['word/document.xml']))
|
|
47
|
-
const
|
|
54
|
+
const doc = parseXml(required(files['word/document.xml']));
|
|
55
|
+
const styles = files['word/styles.xml'] ? parseXml(files['word/styles.xml']) : {};
|
|
56
|
+
const warnings = [];
|
|
57
|
+
const styleLevels = {};
|
|
58
|
+
const headingLevels = {};
|
|
59
|
+
const outlineLevels = {};
|
|
60
|
+
const anchors = new Set();
|
|
48
61
|
const styleRows = list(child(styles, 'styles', 'style'));
|
|
49
62
|
const resolveLevel = (styleId, seen = new Set()) => {
|
|
50
63
|
if (seen.has(styleId) || !styleId)
|
|
@@ -53,19 +66,33 @@ function audit(files) {
|
|
|
53
66
|
const row = styleRows.find(v => xmlString(child(v, '@_styleId')) === styleId);
|
|
54
67
|
if (!row)
|
|
55
68
|
return;
|
|
56
|
-
const explicit = child(row, 'pPr', 'outlineLvl', '@_val')
|
|
57
|
-
|
|
69
|
+
const explicit = child(row, 'pPr', 'outlineLvl', '@_val');
|
|
70
|
+
const name = xmlString(child(row, 'name', '@_val')) || styleId;
|
|
71
|
+
const common = /^(?:heading|标题)\s*([1-9])$/iu.exec(name);
|
|
72
|
+
if (explicit !== undefined && Number(explicit) < 9) {
|
|
73
|
+
return Number(explicit) + 1;
|
|
74
|
+
}
|
|
75
|
+
if (common) {
|
|
76
|
+
return Number(common[1]);
|
|
77
|
+
}
|
|
78
|
+
return resolveLevel(xmlString(child(row, 'basedOn', '@_val')), seen);
|
|
58
79
|
};
|
|
59
80
|
for (const row of styleRows) {
|
|
60
|
-
const styleId = xmlString(child(row, '@_styleId'))
|
|
81
|
+
const styleId = xmlString(child(row, '@_styleId'));
|
|
82
|
+
const level = resolveLevel(styleId);
|
|
61
83
|
if (level)
|
|
62
84
|
styleLevels[styleId] = level;
|
|
63
85
|
}
|
|
64
|
-
let expectedFigures = 0
|
|
86
|
+
let expectedFigures = 0;
|
|
87
|
+
let expectedTables = 0;
|
|
88
|
+
let textBoxes = 0;
|
|
89
|
+
let footnoteRefs = 0;
|
|
65
90
|
const expectedHeadings = [];
|
|
66
91
|
visit(doc, (key, value) => {
|
|
67
92
|
if (key === 'p') {
|
|
68
|
-
const outline = child(value, 'pPr', 'outlineLvl', '@_val')
|
|
93
|
+
const outline = child(value, 'pPr', 'outlineLvl', '@_val');
|
|
94
|
+
const style = xmlString(child(value, 'pPr', 'pStyle', '@_val'));
|
|
95
|
+
const level = outline !== undefined && Number(outline) < 9 ? Number(outline) + 1 : styleLevels[style];
|
|
69
96
|
if (outline !== undefined && Number(outline) < 9)
|
|
70
97
|
outlineLevels[normalize(wordText(value))] = Number(outline) + 1;
|
|
71
98
|
if (level && !/^TOC/iu.test(style)) {
|
|
@@ -119,7 +146,8 @@ function safeLink(value) { return /^(?:https?:|mailto:|#)/i.test(value || '') ?
|
|
|
119
146
|
function inline(node, internalRefs) {
|
|
120
147
|
if ('value' in node)
|
|
121
148
|
return node.value.replace(/([\\`*[\]<>])/g, '\\$1');
|
|
122
|
-
const t = tag(node)
|
|
149
|
+
const t = tag(node);
|
|
150
|
+
const body = children(node).map(n => inline(n, internalRefs)).join('');
|
|
123
151
|
if (['script', 'style', 'iframe', 'object'].includes(t))
|
|
124
152
|
return '';
|
|
125
153
|
if (t === 'img')
|
|
@@ -159,8 +187,10 @@ function tableHtml(rows) {
|
|
|
159
187
|
}
|
|
160
188
|
export async function convertDocx(buffer, destination, config, signal) {
|
|
161
189
|
checkAbort(signal);
|
|
162
|
-
const files = unpackDocx(buffer, config)
|
|
163
|
-
const
|
|
190
|
+
const files = unpackDocx(buffer, config);
|
|
191
|
+
const originalAudit = audit(files);
|
|
192
|
+
const assets = [];
|
|
193
|
+
const warnings = [...originalAudit.warnings];
|
|
164
194
|
const mimeExtension = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif', 'image/webp': 'webp', 'image/bmp': 'bmp', 'image/tiff': 'tif', 'image/x-emf': 'emf', 'image/x-wmf': 'wmf', 'image/svg+xml': 'svg' };
|
|
165
195
|
const addAsset = async (data, mime, origin) => {
|
|
166
196
|
const assetId = `a-${hash(data).slice(0, 20)}`;
|
|
@@ -174,7 +204,8 @@ export async function convertDocx(buffer, destination, config, signal) {
|
|
|
174
204
|
};
|
|
175
205
|
const rawMedia = Object.entries(files).filter(([name]) => name.startsWith('word/media/'));
|
|
176
206
|
for (const [name, bytes] of rawMedia) {
|
|
177
|
-
const ext = (name.split('.').at(-1) || '').toLowerCase()
|
|
207
|
+
const ext = (name.split('.').at(-1) || '').toLowerCase();
|
|
208
|
+
const mime = Object.entries(mimeExtension).find(([, x]) => x === ext || ext === 'jpeg' && x === 'jpg')?.[0] || 'application/octet-stream';
|
|
178
209
|
await addAsset(Buffer.from(bytes), mime, name);
|
|
179
210
|
}
|
|
180
211
|
const result = await mammoth.convertToHtml({ buffer }, {
|
|
@@ -208,11 +239,14 @@ export async function convertDocx(buffer, destination, config, signal) {
|
|
|
208
239
|
// Unmapped styles lose formatting, not paragraph text; heading coverage is audited separately.
|
|
209
240
|
blocking: !/^Unrecognised (?:paragraph|run) style:/i.test(m.message) && /image|unrecognised|unsupported/i.test(m.message),
|
|
210
241
|
})));
|
|
211
|
-
const fragment = parseFragment(result.value)
|
|
242
|
+
const fragment = parseFragment(result.value);
|
|
243
|
+
const blocks = [];
|
|
244
|
+
const internalRefs = [];
|
|
212
245
|
let figureCount = 0;
|
|
213
246
|
const add = (value) => { blocks.push(makeBlock({ blockId: `b-${String(blocks.length + 1).padStart(6, '0')}`, ...value })); return required(blocks.at(-1)); };
|
|
214
247
|
const addInline = (node, type = 'paragraph', prefix = '') => {
|
|
215
|
-
const body = inline(node, internalRefs)
|
|
248
|
+
const body = inline(node, internalRefs);
|
|
249
|
+
const pieces = body.split(String.fromCharCode(1)).filter(Boolean);
|
|
216
250
|
for (const piece of pieces) {
|
|
217
251
|
if (piece.startsWith('asset:')) {
|
|
218
252
|
figureCount++;
|
|
@@ -227,7 +261,8 @@ export async function convertDocx(buffer, destination, config, signal) {
|
|
|
227
261
|
if (/^h[1-9]$/.test(t))
|
|
228
262
|
add({ type: 'heading', level: Number(t[1]), text: htmlText(node).trim(), anchor: attr(node, 'id') || null });
|
|
229
263
|
else if (t === 'table') {
|
|
230
|
-
const rows = tableCells(node)
|
|
264
|
+
const rows = tableCells(node);
|
|
265
|
+
const table = add({ type: 'table', rows, text: rows.map(row => row.map(c => c.text).join(' | ')).join('\n'), markdown: tableHtml(rows) });
|
|
231
266
|
const scan = (n) => {
|
|
232
267
|
if (tag(n) === 'img') {
|
|
233
268
|
const assetId = (attr(n, 'src') || '').replace(/^asset:/, '');
|
|
@@ -241,7 +276,8 @@ export async function convertDocx(buffer, destination, config, signal) {
|
|
|
241
276
|
scan(node);
|
|
242
277
|
}
|
|
243
278
|
else if (t === 'p') {
|
|
244
|
-
const t = htmlText(node).trim()
|
|
279
|
+
const t = htmlText(node).trim();
|
|
280
|
+
const previous = blocks.at(-1);
|
|
245
281
|
if (/^(?:图|Figure)\s*[A-Za-z]?\d[\d.\-–]*/i.test(t) && previous?.type === 'figure') {
|
|
246
282
|
previous.caption = t;
|
|
247
283
|
add({ type: 'caption', text: t, figureRef: previous.occurrenceId });
|
|
@@ -19,7 +19,8 @@ export function lines(spans) {
|
|
|
19
19
|
}
|
|
20
20
|
return rows.sort((a, b) => a.y - b.y).map(r => {
|
|
21
21
|
const items = r.spans.sort((a, b) => readingBox(a)[0] - readingBox(b)[0]);
|
|
22
|
-
let text = ''
|
|
22
|
+
let text = '';
|
|
23
|
+
let last;
|
|
23
24
|
for (const s of items) {
|
|
24
25
|
if (last && readingBox(s)[0] - readingBox(last)[2] > Math.max(1, s.fontSize * .18) && !/\s$/.test(text))
|
|
25
26
|
text += ' ';
|
|
@@ -83,16 +84,23 @@ function geometricTables(page, spans, occupied) {
|
|
|
83
84
|
group.push(required(rows[++i]));
|
|
84
85
|
if (group.length < 2)
|
|
85
86
|
continue;
|
|
86
|
-
const ids = new Set()
|
|
87
|
+
const ids = new Set();
|
|
88
|
+
const cells = group.map(r => r.cells.map(b => { const ss = spans.filter(s => { const x = (s.bbox[0] + s.bbox[2]) / 2; const y = (s.bbox[1] + s.bbox[3]) / 2; return x > b[0] && x < b[2] && y > b[1] && y < b[3]; }); ss.forEach(s => ids.add(s.id)); return { text: textOf(ss), spanIds: ss.map(s => s.id), bbox: b, colspan: 1, rowspan: 1 }; }));
|
|
87
89
|
if (cells.some(r => r.every(c => !c.text)))
|
|
88
90
|
continue;
|
|
89
|
-
const bbox = required(union(group.flatMap(r => r.cells)))
|
|
91
|
+
const bbox = required(union(group.flatMap(r => r.cells)));
|
|
92
|
+
const identified = /field|offset|bits|name|description|字段|偏移|名称|参数|描述|位范围/i.test(required(cells[0]).map(c => c.text).join(' '));
|
|
90
93
|
tables.push({ rows: cells, bbox, ids, identified });
|
|
91
94
|
}
|
|
92
95
|
return tables;
|
|
93
96
|
}
|
|
94
97
|
export function nativeLayout(page, info) {
|
|
95
|
-
const byMarked = new Map()
|
|
98
|
+
const byMarked = new Map();
|
|
99
|
+
const used = new Set();
|
|
100
|
+
const blocks = [];
|
|
101
|
+
const figures = [];
|
|
102
|
+
const warnings = (page.warnings || []).map(message => ({ code: 'pdf-engine-warning', page: page.page, message: `PDF 第 ${page.page} 页解析器警告:${message}`, blocking: true }));
|
|
103
|
+
const excluded = page.spans.filter(s => s.artifact).map(s => ({ kind: 'tagged-artifact', text: s.text, bbox: s.bbox }));
|
|
96
104
|
const textSpans = page.spans.filter(s => !s.artifact);
|
|
97
105
|
for (const s of textSpans) {
|
|
98
106
|
if (!byMarked.has(s.mcid))
|
|
@@ -128,7 +136,8 @@ export function nativeLayout(page, info) {
|
|
|
128
136
|
if (!rows.length)
|
|
129
137
|
return;
|
|
130
138
|
const irregular = rows.some(r => r.length !== required(rows[0]).length);
|
|
131
|
-
const textBox = required(union(spans.map(s => s.bbox)))
|
|
139
|
+
const textBox = required(union(spans.map(s => s.bbox)));
|
|
140
|
+
const nearby = page.drawings.filter(d => d.kind === 'path' && d.bbox[1] >= textBox[1] - 20 && d.bbox[3] <= textBox[3] + 20 && intersects(d.bbox, boundedBox(textBox, page, 10))).map(d => d.bbox);
|
|
132
141
|
const tableBox = boundedBox(required(union([textBox, ...nearby])), page, 3);
|
|
133
142
|
add('table', spans, { source: source(tableBox), rows, markdown: tableMarkdown(rows), needsReview: irregular, caption: '', layoutBasis: 'structure-tags', ...textBox[3] > page.height * .85 && !closedTableBottom(page, textBox, tableBox) ? { openEnd: true } : {} });
|
|
134
143
|
if (irregular)
|
|
@@ -136,7 +145,10 @@ export function nativeLayout(page, info) {
|
|
|
136
145
|
return;
|
|
137
146
|
}
|
|
138
147
|
if (node.role === 'Figure') {
|
|
139
|
-
const marked = ids(node)
|
|
148
|
+
const marked = ids(node);
|
|
149
|
+
const spans = get(node);
|
|
150
|
+
const boxes = [...page.drawings.filter(d => d.mcid !== null && marked.includes(d.mcid)).map(d => d.bbox), ...spans.map(s => s.bbox)];
|
|
151
|
+
const bbox = union(boxes);
|
|
140
152
|
if (!bbox)
|
|
141
153
|
return;
|
|
142
154
|
consume(spans);
|
|
@@ -148,7 +160,15 @@ export function nativeLayout(page, info) {
|
|
|
148
160
|
return;
|
|
149
161
|
}
|
|
150
162
|
if (['Code', 'Formula', 'Note'].includes(node.role || '')) {
|
|
151
|
-
add(
|
|
163
|
+
add((() => {
|
|
164
|
+
if (node.role === 'Code') {
|
|
165
|
+
return 'code';
|
|
166
|
+
}
|
|
167
|
+
if (node.role === 'Formula') {
|
|
168
|
+
return 'formula';
|
|
169
|
+
}
|
|
170
|
+
return 'note';
|
|
171
|
+
})(), get(node));
|
|
152
172
|
return;
|
|
153
173
|
}
|
|
154
174
|
if (node.role === 'P') {
|
|
@@ -194,8 +214,21 @@ export function nativeLayout(page, info) {
|
|
|
194
214
|
const match = info.outline.find(o => {
|
|
195
215
|
if (o.page !== page.page || normalize(o.title) !== normalize(b.text))
|
|
196
216
|
return false;
|
|
197
|
-
const candidates = blocks.filter(c => normalize(c.text) === normalize(o.title))
|
|
198
|
-
const
|
|
217
|
+
const candidates = blocks.filter(c => normalize(c.text) === normalize(o.title));
|
|
218
|
+
const t = page.viewportTransform;
|
|
219
|
+
const axis = page.rotation % 180 ? 0 : 1;
|
|
220
|
+
let target;
|
|
221
|
+
if (o.y !== null && Number.isFinite(o.y) && t) {
|
|
222
|
+
if (axis === 0) {
|
|
223
|
+
target = required(t[2]) * o.y + required(t[4]);
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
target = required(t[3]) * o.y + required(t[5]);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
else {
|
|
230
|
+
target = null;
|
|
231
|
+
}
|
|
199
232
|
const score = (c) => target === null ? (c.type === 'heading' ? 0 : 100) + c.source.bbox[1] / 1000 : Math.abs(c.source.bbox[axis] - target);
|
|
200
233
|
return candidates.sort((a, b) => score(a) - score(b))[0] === b && (target === null || score(b) < 100);
|
|
201
234
|
});
|
|
@@ -225,7 +258,9 @@ export function nativeLayout(page, info) {
|
|
|
225
258
|
blocks.sort((a, b) => a.source.bbox[1] - b.source.bbox[1] || a.source.bbox[0] - b.source.bbox[0]);
|
|
226
259
|
const coverage = [...[...figures, ...blocks.filter(b => b.type === 'table')].map(b => boundedBox(b.source.bbox, page, 15)), ...excluded.map(e => boundedBox(e.bbox, page, 2))];
|
|
227
260
|
const unexplained = page.drawings.filter(d => d.bbox[2] - d.bbox[0] > 25 && d.bbox[3] - d.bbox[1] > 12 && d.bbox[1] > 65 && d.bbox[3] < page.height - 40 && !coverage.some(b => intersects(b, d.bbox)));
|
|
228
|
-
const raw = textSpans.map(s => s.text).join('')
|
|
261
|
+
const raw = textSpans.map(s => s.text).join('');
|
|
262
|
+
const garbled = textSpans.filter(s => (s.text.includes('\ufffd') || s.text.includes('\0')));
|
|
263
|
+
const ocr = (raw.length < 30 && page.drawings.length > 0) || garbled.length > textSpans.length * .3;
|
|
229
264
|
if (garbled.length)
|
|
230
265
|
warnings.push({ code: 'pdf-garbled-text', page: page.page, message: `PDF 第 ${page.page} 页存在缺字或乱码,需要核对识别区域`, blocking: true });
|
|
231
266
|
const multiColumn = lines(textSpans.filter(s => !coverage.some(b => intersects(s.bbox, b)))).filter(l => l.spans.some((s, i) => i && s.bbox[0] - required(l.spans[i - 1]).bbox[2] > page.width * .13)).length >= 3;
|
|
@@ -24,7 +24,8 @@ export class PdfSession {
|
|
|
24
24
|
this.signal = signal;
|
|
25
25
|
checkAbort(signal);
|
|
26
26
|
// Production uses the shipped JS worker. Source tests use the same TS through the installed tsx loader.
|
|
27
|
-
const js = new URL('./pdf-worker.js', import.meta.url)
|
|
27
|
+
const js = new URL('./pdf-worker.js', import.meta.url);
|
|
28
|
+
const source = !existsSync(fileURLToPath(js));
|
|
28
29
|
this.worker = new Worker(source ? new URL('./pdf-worker.ts', import.meta.url) : js, { workerData: { file, config: { maxInputBytes: config.maxInputBytes, pdfMaxPages: config.pdfMaxPages, pdfMaxPagePixels: config.pdfMaxPagePixels } }, resourceLimits: { maxOldGenerationSizeMb: 512 }, execArgv: source ? ['--import', 'tsx/esm'] : [] });
|
|
29
30
|
const open = deferred();
|
|
30
31
|
this.ready = open.promise;
|
|
@@ -85,7 +86,8 @@ export class PdfSession {
|
|
|
85
86
|
throw this.error;
|
|
86
87
|
if (this.closed)
|
|
87
88
|
throw new Error('PDF 解析进程已关闭');
|
|
88
|
-
const id = ++this.seq
|
|
89
|
+
const id = ++this.seq;
|
|
90
|
+
const value = await new Promise((resolve, reject) => { const timer = setTimeout(() => this.fail(new Error(`PDF 第 ${page} 页处理超时`)), this.config.pdfPageTimeoutMs); this.pending.set(id, { resolve, reject, timer }); this.worker.postMessage({ id, command, page, bbox }); });
|
|
89
91
|
return command === 'page' ? nativePageSchema.parse(value) : renderSchema.parse(value);
|
|
90
92
|
}
|
|
91
93
|
close() {
|
|
@@ -114,9 +116,13 @@ export function pageRange(start, end, count) {
|
|
|
114
116
|
export async function inspectPdf(file, config, signal) {
|
|
115
117
|
const session = new PdfSession(file, config, signal);
|
|
116
118
|
try {
|
|
117
|
-
const info = await session.ready
|
|
119
|
+
const info = await session.ready;
|
|
120
|
+
const n = info.pageCount;
|
|
121
|
+
const samples = [...new Set([1, Math.min(3, n), Math.ceil(n / 3), Math.ceil(n * 2 / 3), n])];
|
|
122
|
+
const pages = [];
|
|
118
123
|
for (const page of samples) {
|
|
119
|
-
const value = await session.call('page', page)
|
|
124
|
+
const value = await session.call('page', page);
|
|
125
|
+
const text = value.spans.filter(s => !s.artifact).map(s => s.text).join('');
|
|
120
126
|
pages.push({ page, chars: Array.from(text).length, hasGraphics: value.drawings.length > 0, possibleOcr: text.length < 30 && value.drawings.length > 0, hasStructure: Boolean(value.tree) });
|
|
121
127
|
}
|
|
122
128
|
return { sourceFormat: 'pdf', pageCount: n, outlineCount: info.outline.length, samples: pages, possibleOcr: pages.some(p => p.possibleOcr), note: '仅抽样预检;正式构建逐页核对,图表及扫描识别共用模型预算。' };
|
|
@@ -16,7 +16,9 @@ export async function restoreLayout(page, layout, file, job, models, signal) {
|
|
|
16
16
|
throw new Error('此页需要版面识别/OCR,请配置图片模型并启用图片理解');
|
|
17
17
|
if (!job.visionCapability)
|
|
18
18
|
await models.preflight(job, signal);
|
|
19
|
-
const spans = page.spans.filter(s => !s.artifact)
|
|
19
|
+
const spans = page.spans.filter(s => !s.artifact);
|
|
20
|
+
const ocr = layout.ocr;
|
|
21
|
+
const badIds = new Set(spans.filter(s => (s.text.includes('\ufffd') || s.text.includes('\0'))).map(s => s.id));
|
|
20
22
|
if (chars(JSON.stringify(spans)) > 90000)
|
|
21
23
|
throw new Error('此页原生文字对象超过版面识别输入上限,请缩小页范围或使用专用解析器');
|
|
22
24
|
const prepared = await prepareImage(models.ctx, file, job.config, signal);
|
|
@@ -29,7 +31,8 @@ export async function restoreLayout(page, layout, file, job, models, signal) {
|
|
|
29
31
|
const value = assignmentSchema.parse(raw);
|
|
30
32
|
if (!Array.isArray(value.blocks) || !value.blocks.length || value.blocks.length > 2000 || !Array.isArray(value.uncertainties) || value.uncertainties.length > 100)
|
|
31
33
|
throw new Error('PDF 版面识别 JSON 无效');
|
|
32
|
-
const used = new Set()
|
|
34
|
+
const used = new Set();
|
|
35
|
+
const byId = new Map(spans.map(s => [s.id, s]));
|
|
33
36
|
const take = (row, allowEmpty = false) => {
|
|
34
37
|
if (ocr && (!row.spanIds || Array.isArray(row.spanIds) && !row.spanIds.length)) {
|
|
35
38
|
if (typeof row.text !== 'string' || chars(row.text) > 30000 || !allowEmpty && !row.text.trim())
|
|
@@ -97,7 +100,9 @@ export async function restoreLayout(page, layout, file, job, models, signal) {
|
|
|
97
100
|
}
|
|
98
101
|
// The assigned strings must lie inside their claimed region. No numeric text rewriting is accepted.
|
|
99
102
|
for (const id of block.spanIds || []) {
|
|
100
|
-
const s = required(byId.get(id))
|
|
103
|
+
const s = required(byId.get(id));
|
|
104
|
+
const x = (s.bbox[0] + s.bbox[2]) / 2;
|
|
105
|
+
const y = (s.bbox[1] + s.bbox[3]) / 2;
|
|
101
106
|
if (x < b[0] - 2 || x > b[2] + 2 || y < b[1] - 2 || y > b[3] + 2)
|
|
102
107
|
throw new Error('PDF 文字与识别区域不匹配');
|
|
103
108
|
}
|
|
@@ -14,11 +14,14 @@ const matrixSchema = z.tuple([z.number(), z.number(), z.number(), z.number(), z.
|
|
|
14
14
|
const markTag = (value) => z.union([z.string(), z.object({ name: z.string() })]).transform(value => typeof value === 'string' ? value : value.name).parse(value);
|
|
15
15
|
const numeric = (value) => z.array(z.number().finite()).parse(value instanceof Float32Array || value instanceof Float64Array ? Array.from(value) : value);
|
|
16
16
|
// PDF.js uses napi-rs on Node. Correct only subpixel clip skew in this isolated worker's supported canvas prototype.
|
|
17
|
-
const proto = Object.getPrototypeOf(createCanvas(1, 1).getContext('2d'))
|
|
17
|
+
const proto = Object.getPrototypeOf(createCanvas(1, 1).getContext('2d'));
|
|
18
|
+
const nativeClip = proto.clip;
|
|
18
19
|
proto.clip = function (path, rule) {
|
|
19
|
-
const original = this.getTransform()
|
|
20
|
+
const original = this.getTransform();
|
|
21
|
+
const tiny = (value) => value !== 0 && Math.abs(value) < 1e-7;
|
|
20
22
|
if (path instanceof Path2D && (tiny(original.b) || tiny(original.c))) {
|
|
21
|
-
const matrix = this.getTransform()
|
|
23
|
+
const matrix = this.getTransform();
|
|
24
|
+
const transformed = new Path2D();
|
|
22
25
|
if (tiny(matrix.b))
|
|
23
26
|
matrix.b = 0;
|
|
24
27
|
if (tiny(matrix.c))
|
|
@@ -33,13 +36,25 @@ proto.clip = function (path, rule) {
|
|
|
33
36
|
}
|
|
34
37
|
}
|
|
35
38
|
else
|
|
36
|
-
Reflect.apply(nativeClip, this,
|
|
39
|
+
Reflect.apply(nativeClip, this, (() => {
|
|
40
|
+
if (path === undefined) {
|
|
41
|
+
return [];
|
|
42
|
+
}
|
|
43
|
+
if (rule === undefined) {
|
|
44
|
+
return [path];
|
|
45
|
+
}
|
|
46
|
+
return [path, rule];
|
|
47
|
+
})());
|
|
37
48
|
};
|
|
38
|
-
const require = createRequire(import.meta.url)
|
|
39
|
-
|
|
49
|
+
const require = createRequire(import.meta.url);
|
|
50
|
+
const base = dirname(require.resolve('pdfjs-dist/package.json'));
|
|
51
|
+
const config = input.config;
|
|
52
|
+
let doc;
|
|
53
|
+
let activePage = 0;
|
|
40
54
|
const engineWarnings = new Map();
|
|
41
55
|
console.warn = (...parts) => {
|
|
42
|
-
const value = parts.map(String).join(' ').replace(/^Warning:\s*/u, '').slice(0, 1000)
|
|
56
|
+
const value = parts.map(String).join(' ').replace(/^Warning:\s*/u, '').slice(0, 1000);
|
|
57
|
+
const list = engineWarnings.get(activePage) || [];
|
|
43
58
|
if (list.length < 100 && !list.includes(value))
|
|
44
59
|
list.push(value);
|
|
45
60
|
engineWarnings.set(activePage, list);
|
|
@@ -70,7 +85,8 @@ async function info() {
|
|
|
70
85
|
for (const entry of items || []) {
|
|
71
86
|
if (outline.length >= 10000 || level > 32)
|
|
72
87
|
throw new Error('PDF 书签层级或数量超过上限');
|
|
73
|
-
let page = null
|
|
88
|
+
let page = null;
|
|
89
|
+
let y = null;
|
|
74
90
|
try {
|
|
75
91
|
const raw = typeof entry.dest === 'string' ? await doc.getDestination(entry.dest) : entry.dest;
|
|
76
92
|
if (Array.isArray(raw) && raw.length) {
|
|
@@ -93,8 +109,11 @@ async function nativePage(n) {
|
|
|
93
109
|
activePage = n;
|
|
94
110
|
const page = await doc.getPage(n);
|
|
95
111
|
try {
|
|
96
|
-
const viewport = page.getViewport({ scale: 1 })
|
|
97
|
-
const
|
|
112
|
+
const viewport = page.getViewport({ scale: 1 });
|
|
113
|
+
const content = await page.getTextContent({ includeMarkedContent: true });
|
|
114
|
+
const tree = prune(await page.getStructTree());
|
|
115
|
+
const spans = [];
|
|
116
|
+
const marks = [];
|
|
98
117
|
let seq = 0;
|
|
99
118
|
for (const item of content.items) {
|
|
100
119
|
if ('type' in item) {
|
|
@@ -106,17 +125,47 @@ async function nativePage(n) {
|
|
|
106
125
|
}
|
|
107
126
|
if (!item.str.trim())
|
|
108
127
|
continue;
|
|
109
|
-
const t = matrixSchema.parse(Util.transform(viewport.transform, item.transform))
|
|
110
|
-
const
|
|
111
|
-
const
|
|
112
|
-
const
|
|
113
|
-
const
|
|
114
|
-
const
|
|
128
|
+
const t = matrixSchema.parse(Util.transform(viewport.transform, item.transform));
|
|
129
|
+
const h = Math.hypot(t[2], t[3]) || item.height || 10;
|
|
130
|
+
const style = content.styles[item.fontName];
|
|
131
|
+
const a = style?.ascent ?? .8;
|
|
132
|
+
const a0 = [t[4] + t[2] * a, t[5] + t[3] * a];
|
|
133
|
+
const b0 = [t[4] + t[2] * (a - 1), t[5] + t[3] * (a - 1)];
|
|
134
|
+
const angle = Math.atan2(t[1], t[0]);
|
|
135
|
+
const w = item.width || h / 2;
|
|
136
|
+
const dx = Math.cos(angle) * w;
|
|
137
|
+
const dy = Math.sin(angle) * w;
|
|
138
|
+
const points = [a0, b0, [a0[0] + dx, a0[1] + dy], [b0[0] + dx, b0[1] + dy]];
|
|
139
|
+
const bbox = [Math.min(...points.map(p => p[0])), Math.min(...points.map(p => p[1])), Math.max(...points.map(p => p[0])), Math.max(...points.map(p => p[1]))];
|
|
140
|
+
const rotation = ((page.rotate % 360) + 360) % 360;
|
|
141
|
+
const W = viewport.width;
|
|
142
|
+
const H = viewport.height;
|
|
143
|
+
let readingBox;
|
|
144
|
+
if (rotation === 90) {
|
|
145
|
+
readingBox = [bbox[1], W - bbox[2], bbox[3], W - bbox[0]];
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
if (rotation === 180) {
|
|
149
|
+
readingBox = [W - bbox[2], H - bbox[3], W - bbox[0], H - bbox[1]];
|
|
150
|
+
}
|
|
151
|
+
else {
|
|
152
|
+
if (rotation === 270) {
|
|
153
|
+
readingBox = [H - bbox[3], bbox[0], H - bbox[1], bbox[2]];
|
|
154
|
+
}
|
|
155
|
+
else {
|
|
156
|
+
readingBox = bbox;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
115
160
|
spans.push({ id: `s${++seq}`, text: item.str, mcid: [...marks].reverse().find(m => m.id)?.id || null, artifact: marks.some(m => m.artifact), bbox, readingBox, fontSize: h, fontName: style?.fontFamily || item.fontName });
|
|
116
161
|
if (spans.length > 100000)
|
|
117
162
|
throw new Error(`PDF 第 ${n} 页文字对象过多`);
|
|
118
163
|
}
|
|
119
|
-
const operators = await page.getOperatorList()
|
|
164
|
+
const operators = await page.getOperatorList();
|
|
165
|
+
const drawings = [];
|
|
166
|
+
const stack = [];
|
|
167
|
+
const mc = [];
|
|
168
|
+
const prefix = `p${page.ref?.num || n}R_mc`;
|
|
120
169
|
let matrix = [1, 0, 0, 1, 0, 0];
|
|
121
170
|
const add = (b, kind, shape = null) => {
|
|
122
171
|
const bounds = box(matrixSchema.parse(Util.transform(viewport.transform, matrix)), b);
|
|
@@ -126,7 +175,8 @@ async function nativePage(n) {
|
|
|
126
175
|
drawings.push({ bbox: bounds, kind, shape, mcid: id === undefined ? null : prefix + id });
|
|
127
176
|
};
|
|
128
177
|
for (let i = 0; i < operators.fnArray.length; i++) {
|
|
129
|
-
const op = required(operators.fnArray[i])
|
|
178
|
+
const op = required(operators.fnArray[i]);
|
|
179
|
+
const args = operators.argsArray[i] || [];
|
|
130
180
|
if (op === OPS.save)
|
|
131
181
|
stack.push([...matrix]);
|
|
132
182
|
else if (op === OPS.restore)
|
|
@@ -147,7 +197,8 @@ async function nativePage(n) {
|
|
|
147
197
|
else if (op === OPS.endMarkedContent)
|
|
148
198
|
mc.pop();
|
|
149
199
|
else if (op === OPS.constructPath && [OPS.stroke, OPS.fill, OPS.eoFill, OPS.fillStroke, OPS.eoFillStroke].includes(z.number().parse(args[0])) && args[2]) {
|
|
150
|
-
const paths = Array.isArray(args[1]) ? args[1] : []
|
|
200
|
+
const paths = Array.isArray(args[1]) ? args[1] : [];
|
|
201
|
+
const path = paths[0] === undefined ? [] : numeric(paths[0]);
|
|
151
202
|
add(bboxSchema.parse(numeric(args[2])), 'path', path.length === 13 && path[0] === 0 && path[3] === 1 && path[6] === 1 && path[9] === 1 && path[12] === 4 ? 'rect' : null);
|
|
152
203
|
}
|
|
153
204
|
else if ([OPS.paintImageXObject, OPS.paintInlineImageXObject, OPS.paintImageMaskXObject].includes(op))
|
|
@@ -163,13 +214,17 @@ async function nativePage(n) {
|
|
|
163
214
|
}
|
|
164
215
|
async function render(n, bbox) {
|
|
165
216
|
activePage = n;
|
|
166
|
-
const page = await doc.getPage(n)
|
|
217
|
+
const page = await doc.getPage(n);
|
|
218
|
+
const v = page.getViewport({ scale: 1 });
|
|
219
|
+
const b = bbox || [0, 0, v.width, v.height];
|
|
167
220
|
if (b[0] < 0 || b[1] < 0 || b[2] > v.width + .1 || b[3] > v.height + .1 || b[2] <= b[0] || b[3] <= b[1])
|
|
168
221
|
throw new Error('PDF 裁切区域无效');
|
|
169
222
|
const scale = Math.min(2, Math.sqrt(config.pdfMaxPagePixels / (v.width * v.height)));
|
|
170
223
|
if (scale < .5)
|
|
171
224
|
throw new Error(`PDF 第 ${n} 页页面尺寸过大`);
|
|
172
|
-
const viewport = page.getViewport({ scale })
|
|
225
|
+
const viewport = page.getViewport({ scale });
|
|
226
|
+
const canvas = createCanvas(Math.ceil(viewport.width), Math.ceil(viewport.height));
|
|
227
|
+
const crop = createCanvas(Math.max(1, Math.ceil((b[2] - b[0]) * scale)), Math.max(1, Math.ceil((b[3] - b[1]) * scale)));
|
|
173
228
|
try {
|
|
174
229
|
// PDF.js publishes DOM-only render types for its supported Node napi-rs canvas. This bridge uses that same tested Canvas2D implementation.
|
|
175
230
|
await page.render({ canvas: null, canvasContext: canvas.getContext('2d'), viewport, background: 'rgb(255,255,255)' }).promise;
|
package/lib/document/pdf.js
CHANGED
|
@@ -10,10 +10,14 @@ import { blockMarkdown } from "./convert.js";
|
|
|
10
10
|
import { BudgetError } from "../models.js";
|
|
11
11
|
export async function convertPdf(file, destination, job, models, signal) {
|
|
12
12
|
let session = new PdfSession(file, job.config, signal);
|
|
13
|
-
const assets = new Map()
|
|
13
|
+
const assets = new Map();
|
|
14
|
+
const pages = [];
|
|
15
|
+
const blocks = [];
|
|
16
|
+
const warnings = [];
|
|
14
17
|
job.parserVersion = PDF_PARSER_VERSION;
|
|
15
18
|
const addAsset = async (data, origin, source) => {
|
|
16
|
-
const assetId = `a-${hash(data).slice(0, 20)}
|
|
19
|
+
const assetId = `a-${hash(data).slice(0, 20)}`;
|
|
20
|
+
const asset = { assetId, mime: 'image/png', path: `assets/${assetId}.png`, bytes: data.length, origin, source };
|
|
17
21
|
if (!assets.has(assetId)) {
|
|
18
22
|
await atomicWrite(join(destination, asset.path), Buffer.from(data));
|
|
19
23
|
assets.set(assetId, asset);
|
|
@@ -21,7 +25,8 @@ export async function convertPdf(file, destination, job, models, signal) {
|
|
|
21
25
|
return asset;
|
|
22
26
|
};
|
|
23
27
|
try {
|
|
24
|
-
const info = await session.ready
|
|
28
|
+
const info = await session.ready;
|
|
29
|
+
const range = pageRange(job.pageStart, job.pageEnd, info.pageCount);
|
|
25
30
|
warnings.push(...(info.warnings || []).map(message => ({ code: 'pdf-engine-warning', message: `PDF 打开警告:${message}`, blocking: true })));
|
|
26
31
|
job.pdf = { pageCount: info.pageCount, selectedPages: range, outlineCount: info.outline.length };
|
|
27
32
|
job.progress = { ...job.progress, totalPages: range.count, parsedPages: 0, ocrPages: 0, tables: 0 };
|
|
@@ -34,7 +39,9 @@ export async function convertPdf(file, destination, job, models, signal) {
|
|
|
34
39
|
const receipt = join(destination, 'pdf-pages', `${n}-${key}.json`);
|
|
35
40
|
let result = await readJson(receipt, pageReceiptSchema, null);
|
|
36
41
|
if (!result) {
|
|
37
|
-
let page
|
|
42
|
+
let page;
|
|
43
|
+
let layout;
|
|
44
|
+
let previewAsset;
|
|
38
45
|
try {
|
|
39
46
|
if (session.closed) {
|
|
40
47
|
session = new PdfSession(file, job.config, signal);
|
|
@@ -94,7 +101,15 @@ export async function convertPdf(file, destination, job, models, signal) {
|
|
|
94
101
|
}
|
|
95
102
|
return { ...value, localIndex: i };
|
|
96
103
|
});
|
|
97
|
-
result = { blocks: pageBlocks, assets: localAssets, warnings: layout.warnings, audit: { page: n, width: page.width, height: page.height, pageLabel: info.pageLabels?.[n - 1] || null, status:
|
|
104
|
+
result = { blocks: pageBlocks, assets: localAssets, warnings: layout.warnings, audit: { page: n, width: page.width, height: page.height, pageLabel: info.pageLabels?.[n - 1] || null, status: (() => {
|
|
105
|
+
if (layout.warnings.some(w => w.blocking)) {
|
|
106
|
+
return 'needs-review';
|
|
107
|
+
}
|
|
108
|
+
if (layout.navigation) {
|
|
109
|
+
return 'navigation';
|
|
110
|
+
}
|
|
111
|
+
return 'parsed';
|
|
112
|
+
})(), ocr: layout.ocr, spanCount: layout.spanCount, artifactCount: layout.artifactCount, excluded: layout.excluded, tables: pageBlocks.filter(b => b.type === 'table').length, figures: pageBlocks.filter(b => b.type === 'figure').length, headings: pageBlocks.filter(b => b.type === 'heading').map(b => ({ text: b.text, basis: b.headingBasis, level: b.level })), previewAssetId: previewAsset?.assetId || null } };
|
|
98
113
|
}
|
|
99
114
|
catch (error) {
|
|
100
115
|
if (error instanceof BudgetError || signal?.aborted)
|
|
@@ -148,10 +163,23 @@ export async function convertPdf(file, destination, job, models, signal) {
|
|
|
148
163
|
if (pages.length >= 3) {
|
|
149
164
|
const repeated = new Map();
|
|
150
165
|
for (const b of blocks) {
|
|
151
|
-
const box = b.source?.bbox
|
|
166
|
+
const box = b.source?.bbox;
|
|
167
|
+
const p = pages.find(p => p.page === b.source?.page);
|
|
152
168
|
if (b.type !== 'paragraph' || !box || b.text.length > 160)
|
|
153
169
|
continue;
|
|
154
|
-
const key = normalize(b.text).replace(/\d+/g, '#')
|
|
170
|
+
const key = normalize(b.text).replace(/\d+/g, '#');
|
|
171
|
+
let edge;
|
|
172
|
+
if (box[1] < 40) {
|
|
173
|
+
edge = 'top';
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
if (box[1] > (p?.height || 842) - 45) {
|
|
177
|
+
edge = 'bottom';
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
edge = null;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
155
183
|
if (edge) {
|
|
156
184
|
const k = edge + ':' + key;
|
|
157
185
|
repeated.set(k, [...(repeated.get(k) || []), b]);
|
|
@@ -179,11 +207,13 @@ export async function convertPdf(file, destination, job, models, signal) {
|
|
|
179
207
|
repeated.push(item);
|
|
180
208
|
previous--;
|
|
181
209
|
}
|
|
182
|
-
const a = blocks[previous]
|
|
210
|
+
const a = blocks[previous];
|
|
211
|
+
const last = a?.source?.locations?.at(-1) || a?.source;
|
|
183
212
|
const tableId = (t) => /^(?:表|Table)\s*([A-Z\d][\w.\-–]*)/iu.exec(t.caption)?.[1];
|
|
184
213
|
if (!a || a.type !== 'table' || !a.source || !last?.bbox || !a.rows[0] || !b.rows[0])
|
|
185
214
|
continue;
|
|
186
|
-
const height = pages.find(p => p.page === last.page)?.height || 842
|
|
215
|
+
const height = pages.find(p => p.page === last.page)?.height || 842;
|
|
216
|
+
const nextHeight = pages.find(p => p.page === b.source?.page)?.height || 842;
|
|
187
217
|
if (b.source.page === last.page + 1 && tableId(a) && tableId(a) === tableId(b) && last.bbox[3] > height * .8 && b.source.bbox[1] < nextHeight * .25 && !a.needsReview && !b.needsReview && JSON.stringify(a.rows[0].map(c => normalize(c.text))) === JSON.stringify(b.rows[0].map(c => normalize(c.text))) && a.rows[0].length === b.rows[0].length && [...a.rows, ...b.rows].every(r => r.length === required(a.rows[0]).length && r.every(c => c.rowspan === 1 && c.colspan === 1))) {
|
|
188
218
|
a.rows.push(...b.rows.slice(1));
|
|
189
219
|
const { locations, ...first } = a.source;
|