Repository navigation
Expand file tree
/
Copy pathpdf-classifier.js
More file actions
406 lines (389 loc) · 14.2 KB
/
Copy pathpdf-classifier.js
File metadata and controls
406 lines (389 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
const fsp = require("node:fs/promises");
const { loadPdfjs, getPdfjsDocumentOptions } = require("./pdfjs");
const MIN_NATIVE_CHARACTERS = 24;
const MIN_PRINTABLE_RATIO = 0.8;
const FULL_PAGE_IMAGE_COVERAGE = 0.7;
function boundedNumber(value, minimum = 0, maximum = Number.MAX_SAFE_INTEGER) {
const numeric = Number(value);
if (!Number.isFinite(numeric)) return minimum;
return Math.min(maximum, Math.max(minimum, numeric));
}
function classifyPageMetrics(metrics = {}) {
if (metrics.blank === true) return "native";
const characterCount = boundedNumber(metrics.characterCount);
const printableRatio = boundedNumber(metrics.printableRatio, 0, 1);
const imageCoverage = boundedNumber(metrics.imageCoverage, 0, 1);
const reliableText = characterCount >= MIN_NATIVE_CHARACTERS
&& printableRatio >= MIN_PRINTABLE_RATIO;
const printableShortText = characterCount > 0
&& characterCount < MIN_NATIVE_CHARACTERS
&& printableRatio >= MIN_PRINTABLE_RATIO;
return ((reliableText || printableShortText) && imageCoverage < FULL_PAGE_IMAGE_COVERAGE)
? "native"
: "scanned";
}
function classifyDocument(pages = []) {
const normalized = pages.map((page, index) => {
const metrics = {
pageNumber: Number.isInteger(page.pageNumber) && page.pageNumber > 0
? page.pageNumber
: index + 1,
characterCount: boundedNumber(page.characterCount),
printableRatio: boundedNumber(page.printableRatio, 0, 1),
imageCoverage: boundedNumber(page.imageCoverage, 0, 1),
...(page.blank === true ? { blank: true } : {})
};
return { ...metrics, kind: classifyPageMetrics(metrics) };
});
const kinds = new Set(normalized.map((page) => page.kind));
if (kinds.size > 1) {
// 多数派原则:只有极少数扫描页(封面/插图/二维码页,如单词书封面 1/58)
// 时按 native 处理,让文字页走 docengine——否则整本走 docstructure 结构化
// 引擎,对以文字为主的文档反而失败(2026-08-15「单词之间:低频词.pdf」事故)。
const scannedRatio = normalized.filter((page) => page.kind === "scanned").length / normalized.length;
if (scannedRatio < 0.2) {
return { kind: "native", pages: normalized };
}
return { kind: "mixed", pages: normalized };
}
return {
kind: normalized[0]?.kind || "scanned",
pages: normalized
};
}
function multiplyTransforms(left, right) {
return [
left[0] * right[0] + left[2] * right[1],
left[1] * right[0] + left[3] * right[1],
left[0] * right[2] + left[2] * right[3],
left[1] * right[2] + left[3] * right[3],
left[0] * right[4] + left[2] * right[5] + left[4],
left[1] * right[4] + left[3] * right[5] + left[5]
];
}
function finiteNumericArray(value, expectedLength) {
try {
const numbers = Array.from(value || [], Number);
return numbers.length === expectedLength && numbers.every(Number.isFinite)
? numbers
: null;
} catch {
return null;
}
}
function transformedRectangleBounds(transform, rectangle) {
const points = [
[rectangle.x0, rectangle.y0],
[rectangle.x1, rectangle.y0],
[rectangle.x0, rectangle.y1],
[rectangle.x1, rectangle.y1]
].map(([x, y]) => ({
x: transform[0] * x + transform[2] * y + transform[4],
y: transform[1] * x + transform[3] * y + transform[5]
}));
if (!points.every((point) => Number.isFinite(point.x) && Number.isFinite(point.y))) {
return null;
}
return {
x0: Math.min(...points.map((point) => point.x)),
y0: Math.min(...points.map((point) => point.y)),
x1: Math.max(...points.map((point) => point.x)),
y1: Math.max(...points.map((point) => point.y))
};
}
function intersectRectangles(left, right) {
if (!left || !right) return null;
const intersection = {
x0: Math.max(left.x0, right.x0),
y0: Math.max(left.y0, right.y0),
x1: Math.min(left.x1, right.x1),
y1: Math.min(left.y1, right.y1)
};
return intersection.x1 > intersection.x0 && intersection.y1 > intersection.y0
? intersection
: null;
}
function rectangleUnionArea(rectangles) {
const valid = rectangles.filter((rectangle) => {
const values = [rectangle?.x0, rectangle?.y0, rectangle?.x1, rectangle?.y1];
return values.every(Number.isFinite)
&& rectangle.x1 > rectangle.x0
&& rectangle.y1 > rectangle.y0;
});
const xValues = [...new Set(valid.flatMap((rectangle) => [rectangle.x0, rectangle.x1]))]
.sort((left, right) => left - right);
let area = 0;
for (let index = 0; index < xValues.length - 1; index += 1) {
const x0 = xValues[index];
const x1 = xValues[index + 1];
if (x1 <= x0) continue;
const intervals = valid
.filter((rectangle) => rectangle.x0 < x1 && rectangle.x1 > x0)
.map((rectangle) => [rectangle.y0, rectangle.y1])
.sort((left, right) => left[0] - right[0]);
let coveredHeight = 0;
let currentStart;
let currentEnd;
for (const [start, end] of intervals) {
if (currentStart === undefined) {
currentStart = start;
currentEnd = end;
} else if (start <= currentEnd) {
currentEnd = Math.max(currentEnd, end);
} else {
coveredHeight += currentEnd - currentStart;
currentStart = start;
currentEnd = end;
}
}
if (currentStart !== undefined) coveredHeight += currentEnd - currentStart;
area += (x1 - x0) * coveredHeight;
}
return area;
}
function imageCoverageFromOperators(operatorList, OPS, viewport) {
const width = Number(viewport?.width);
const height = Number(viewport?.height);
const initialTransform = Array.from(viewport?.transform || [], Number);
if (!(width > 0 && height > 0) || initialTransform.length !== 6 || !initialTransform.every(Number.isFinite)) {
return 0;
}
const directImageOperators = new Set([
OPS.paintImageXObject,
OPS.paintInlineImageXObject,
OPS.paintImageMaskXObject
].filter(Number.isInteger));
const unitRectangle = { x0: 0, y0: 0, x1: 1, y1: 1 };
const pageRectangle = { x0: 0, y0: 0, x1: width, y1: height };
let state = { transform: initialTransform, clip: pageRectangle };
let graphicsStack = [];
const formStack = [];
const rectangles = [];
let malformed = false;
const cloneState = (source) => ({
transform: source.transform.slice(),
clip: source.clip && { ...source.clip }
});
const addPaintedUnitRectangle = (transform) => {
// PDF images paint a transformed unit rectangle. We intentionally retain
// its axis-aligned bounds: this is bounded and conservative, but can
// overcount rotated or sheared polygons until polygon union is warranted.
const bounds = transformedRectangleBounds(transform, unitRectangle);
const clipped = intersectRectangles(bounds, state.clip);
if (clipped) rectangles.push(clipped);
};
const addTransformedInstances = (transforms) => {
for (const instanceTransform of transforms) {
const parsed = finiteNumericArray(instanceTransform, 6);
if (!parsed) {
malformed = true;
continue;
}
addPaintedUnitRectangle(multiplyTransforms(state.transform, parsed));
}
};
const transformsFromPositions = (matrixValues, positions) => {
const parsedMatrix = finiteNumericArray(matrixValues, 4);
let parsedPositions;
try {
parsedPositions = Array.from(positions || [], Number);
} catch {
parsedPositions = [];
}
if (!parsedMatrix || parsedPositions.length % 2 !== 0 || !parsedPositions.every(Number.isFinite)) {
malformed = true;
return [];
}
const [a, b, c, d] = parsedMatrix;
const transforms = [];
for (let index = 0; index < parsedPositions.length; index += 2) {
transforms.push([a, b, c, d, parsedPositions[index], parsedPositions[index + 1]]);
}
return transforms;
};
for (let index = 0; index < (operatorList?.fnArray || []).length; index += 1) {
const operator = operatorList.fnArray[index];
const args = operatorList?.argsArray?.[index] || [];
if (operator === OPS.save) {
graphicsStack.push(cloneState(state));
continue;
}
if (operator === OPS.restore) {
if (graphicsStack.length) {
state = graphicsStack.pop();
} else {
malformed = true;
}
continue;
}
if (operator === OPS.transform) {
const next = finiteNumericArray(args, 6);
if (next) {
state.transform = multiplyTransforms(state.transform, next);
} else {
malformed = true;
}
continue;
}
if (operator === OPS.paintFormXObjectBegin) {
formStack.push({
state: cloneState(state),
graphicsStack: graphicsStack.map(cloneState)
});
const formMatrix = args[0] == null ? null : finiteNumericArray(args[0], 6);
if (args[0] != null && !formMatrix) {
malformed = true;
state.clip = null;
} else if (formMatrix) {
state.transform = multiplyTransforms(state.transform, formMatrix);
}
if (args[1] != null) {
const bbox = finiteNumericArray(args[1], 4);
if (!bbox || bbox[2] <= bbox[0] || bbox[3] <= bbox[1]) {
malformed = true;
state.clip = null;
} else {
const formBounds = transformedRectangleBounds(state.transform, {
x0: bbox[0],
y0: bbox[1],
x1: bbox[2],
y1: bbox[3]
});
state.clip = intersectRectangles(state.clip, formBounds);
}
}
continue;
}
if (operator === OPS.paintFormXObjectEnd) {
const frame = formStack.pop();
if (!frame) {
malformed = true;
} else {
if (graphicsStack.length !== frame.graphicsStack.length) malformed = true;
state = frame.state;
graphicsStack = frame.graphicsStack;
}
continue;
}
if (directImageOperators.has(operator) || operator === OPS.paintSolidColorImageMask) {
addPaintedUnitRectangle(state.transform);
continue;
}
if (operator === OPS.paintImageXObjectRepeat) {
addTransformedInstances(transformsFromPositions([args[1], 0, 0, args[2]], args[3]));
continue;
}
if (operator === OPS.paintImageMaskXObjectRepeat) {
addTransformedInstances(transformsFromPositions(
[args[1], args[2] ?? 0, args[3] ?? 0, args[4]],
args[5]
));
continue;
}
if (operator === OPS.paintImageMaskXObjectGroup) {
const images = args[0];
if (!Array.isArray(images)) {
malformed = true;
} else {
addTransformedInstances(images.map((image) => image?.transform));
}
continue;
}
if (operator === OPS.paintInlineImageXObjectGroup) {
const map = args[1];
if (!Array.isArray(map)) {
malformed = true;
} else {
addTransformedInstances(map.map((entry) => entry?.transform));
}
}
}
if (graphicsStack.length || formStack.length) malformed = true;
const coverage = malformed ? 1 : rectangleUnionArea(rectangles) / (width * height);
return Math.min(1, Math.max(0, Number.isFinite(coverage) ? coverage : 1));
}
function textMetrics(textContent) {
const characters = (textContent?.items || [])
.flatMap((item) => Array.from(typeof item.str === "string" ? item.str : ""))
.filter((character) => !/\s/u.test(character));
const printableCount = characters.filter((character) => !/\p{C}/u.test(character)).length;
return {
characterCount: characters.length,
printableRatio: characters.length ? printableCount / characters.length : 0
};
}
async function ocrImageCoverageFromOperators(operatorList, OPS, viewport, objects) {
const coverage = imageCoverageFromOperators(operatorList, OPS, viewport);
if (!(coverage > 0 && coverage < 0.001)) return coverage;
const imageOperations = new Set(Object.entries(OPS).filter(([name]) => /image/i.test(name)).map(([, code]) => code));
let count = 0;
for (let i = 0; i < (operatorList?.fnArray || []).length; i++) {
const operation = operatorList.fnArray[i];
if (!imageOperations.has(operation)) continue;
// Only positively identified tiny constant-color image tiles can be
// treated as decoration. Masks, unresolved images, nonuniform pixels and
// larger coverage retain the existing conservative OCR requirement.
if (operation !== OPS.paintImageXObject) return coverage;
const [id, width, height] = operatorList.argsArray[i] || [];
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 16 || height > 16) return coverage;
let image, timer;
try {
image = await new Promise((resolve, reject) => {
timer = setTimeout(() => resolve(null), 1000);
try { objects?.get(id, resolve); } catch (error) { reject(error); }
});
} catch { return coverage; }
finally { clearTimeout(timer); }
const data = image?.data;
const channels = data?.length / (width * height);
if (![3, 4].includes(channels)) return coverage;
for (let index = channels; index < data.length; index++) {
if (data[index] !== data[index % channels]) return coverage;
}
count++;
}
return count ? 0 : coverage;
}
async function classifyPdf(inputPath) {
const pdfjs = await loadPdfjs();
const data = new Uint8Array(await fsp.readFile(inputPath));
const loadingTask = pdfjs.getDocument(getPdfjsDocumentOptions({
data,
disableFontFace: true,
useSystemFonts: true,
isEvalSupported: false
}));
try {
const pdf = await loadingTask.promise;
const pages = [];
for (let pageNumber = 1; pageNumber <= pdf.numPages; pageNumber += 1) {
const page = await pdf.getPage(pageNumber);
const viewport = page.getViewport({ scale: 1 });
const [textContent, operatorList] = await Promise.all([
page.getTextContent(),
page.getOperatorList()
]);
const metrics = textMetrics(textContent);
pages.push({
pageNumber,
...metrics,
...(!metrics.characterCount && operatorList.fnArray.length === 0 ? { blank: true } : {}),
imageCoverage: imageCoverageFromOperators(operatorList, pdfjs.OPS, viewport)
});
}
return classifyDocument(pages);
} finally {
await loadingTask.destroy();
}
}
module.exports = {
MIN_NATIVE_CHARACTERS,
MIN_PRINTABLE_RATIO,
FULL_PAGE_IMAGE_COVERAGE,
rectangleUnionArea,
imageCoverageFromOperators,
ocrImageCoverageFromOperators,
classifyPageMetrics,
classifyDocument,
classifyPdf
};