@intentic/fileq 1.430.0 → 1.432.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/NOTICE +58 -1
- package/README.md +29 -1
- package/bin/fileq-rg-pre +6 -2
- package/dist/app.d.ts.map +1 -1
- package/dist/app.js +4 -1
- package/dist/app.js.map +1 -1
- package/dist/commands/check.command.d.ts.map +1 -1
- package/dist/commands/check.command.js +12 -5
- package/dist/commands/check.command.js.map +1 -1
- package/dist/commands/derive.command.d.ts.map +1 -1
- package/dist/commands/derive.command.js +3 -2
- package/dist/commands/derive.command.js.map +1 -1
- package/dist/commands/read.command.d.ts.map +1 -1
- package/dist/commands/read.command.js +42 -7
- package/dist/commands/read.command.js.map +1 -1
- package/dist/commands/render.command.d.ts.map +1 -1
- package/dist/commands/render.command.js +23 -10
- package/dist/commands/render.command.js.map +1 -1
- package/dist/lib/derivers/docx-math-symbols.d.ts +14 -0
- package/dist/lib/derivers/docx-math-symbols.d.ts.map +1 -0
- package/dist/lib/derivers/docx-math-symbols.js +160 -0
- package/dist/lib/derivers/docx-math-symbols.js.map +1 -0
- package/dist/lib/derivers/docx-math.d.ts +15 -0
- package/dist/lib/derivers/docx-math.d.ts.map +1 -0
- package/dist/lib/derivers/docx-math.js +252 -0
- package/dist/lib/derivers/docx-math.js.map +1 -0
- package/dist/lib/derivers/docx.d.ts.map +1 -1
- package/dist/lib/derivers/docx.js +3 -2
- package/dist/lib/derivers/docx.js.map +1 -1
- package/dist/lib/derivers/pdf-furniture.d.ts.map +1 -1
- package/dist/lib/derivers/pdf-furniture.js +3 -0
- package/dist/lib/derivers/pdf-furniture.js.map +1 -1
- package/dist/lib/derivers/pdf-tables.d.ts +9 -0
- package/dist/lib/derivers/pdf-tables.d.ts.map +1 -0
- package/dist/lib/derivers/pdf-tables.js +319 -0
- package/dist/lib/derivers/pdf-tables.js.map +1 -0
- package/dist/lib/derivers/pdf.d.ts.map +1 -1
- package/dist/lib/derivers/pdf.js +77 -38
- package/dist/lib/derivers/pdf.js.map +1 -1
- package/dist/lib/ocr-slots.d.ts +8 -0
- package/dist/lib/ocr-slots.d.ts.map +1 -0
- package/dist/lib/ocr-slots.js +35 -0
- package/dist/lib/ocr-slots.js.map +1 -0
- package/dist/skill.d.ts.map +1 -1
- package/dist/skill.js +7 -2
- package/dist/skill.js.map +1 -1
- package/package.json +7 -7
- package/src/app.ts +4 -1
- package/src/cli.integration.test.ts +30 -8
- package/src/commands/check.command.ts +20 -5
- package/src/commands/derive.command.ts +3 -2
- package/src/commands/read.command.ts +56 -8
- package/src/commands/render.command.ts +33 -11
- package/src/derivers.integration.test.ts +131 -11
- package/src/lib/derivers/docx-math-symbols.ts +197 -0
- package/src/lib/derivers/docx-math.test.ts +131 -0
- package/src/lib/derivers/docx-math.ts +355 -0
- package/src/lib/derivers/docx.ts +5 -3
- package/src/lib/derivers/image.ts +2 -2
- package/src/lib/derivers/pdf-furniture.test.ts +9 -0
- package/src/lib/derivers/pdf-furniture.ts +5 -0
- package/src/lib/derivers/pdf-tables.test.ts +292 -0
- package/src/lib/derivers/pdf-tables.ts +465 -0
- package/src/lib/derivers/pdf.ts +94 -40
- package/src/lib/ocr-slots.integration.test.ts +64 -0
- package/src/lib/ocr-slots.ts +61 -0
- package/src/lib/sidecar.ts +1 -1
- package/src/render.integration.test.ts +5 -4
- package/src/skill.ts +10 -5
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
// Tables in a PDF's text layer: pdf.js hands a page's text over as items in drawing order, which for a table is often
|
|
2
|
+
// column by column or cell by cell, so joining them in that order loses which column a value sat in. This module puts
|
|
3
|
+
// the items back on the page by position, finds the regions whose rows share three or more columns, and renders each
|
|
4
|
+
// region as a markdown table where the drawing order first reached it. Every other item is joined exactly as before,
|
|
5
|
+
// so a page with no such region reads byte for byte as it did.
|
|
6
|
+
// The row-and-column heuristic is adapted from markitdown's word-position table detection
|
|
7
|
+
// (https://github.com/microsoft/markitdown, packages/markitdown/src/markitdown/converters/_pdf_converter.py, MIT, ../../../NOTICE,
|
|
8
|
+
// Copyright (c) Microsoft Corporation): rows grouped by y, a row with several column groups is a table row, a region is
|
|
9
|
+
// a run of them, and a region of long cells is prose. What differs: columns are found by projecting each region's
|
|
10
|
+
// cells onto the x axis (gutters are the x ranges no cell covers), so right-aligned and centred columns line up as
|
|
11
|
+
// well as left-aligned ones, and a table is cut out of the page rather than the whole page being redrawn.
|
|
12
|
+
|
|
13
|
+
import { markdownTable } from "@intentic/webq/markdown";
|
|
14
|
+
|
|
15
|
+
/** The fields of a pdf.js text item this module reads. */
|
|
16
|
+
export interface PositionedItem {
|
|
17
|
+
readonly str: string;
|
|
18
|
+
/** [a, b, c, d, e, f]: e and f are the baseline origin in page units, d the vertical scale (the font size). */
|
|
19
|
+
readonly transform: readonly number[];
|
|
20
|
+
readonly width: number;
|
|
21
|
+
readonly height: number;
|
|
22
|
+
readonly hasEOL: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// A gap of at least this many font sizes between two pieces of one row separates two cells. A word space is about a
|
|
26
|
+
// third of one, and a loose justified line rarely reaches two thirds.
|
|
27
|
+
const CELL_GAP_EM = 1;
|
|
28
|
+
// Within a cell, a gap wider than this many font sizes stands for a space the item text did not carry.
|
|
29
|
+
const SPACE_GAP_EM = 0.15;
|
|
30
|
+
// Two pieces whose baselines differ by less than this many font sizes sit on one row (a superscript included).
|
|
31
|
+
const SAME_ROW_EM = 0.5;
|
|
32
|
+
// A row whose font size differs from the region's by more than this ratio is not part of it (a heading, a total).
|
|
33
|
+
const SIZE_RATIO = 1.25;
|
|
34
|
+
// A single-cell row this close under the row above (in font sizes) and starting at a column continues that row's cell.
|
|
35
|
+
const CONTINUATION_EM = 2;
|
|
36
|
+
// Two table rows this close together (in font sizes) have no room for a line of their own between them: a line drawn
|
|
37
|
+
// there is an overlay (a footer, a watermark), not part of the reading order between them.
|
|
38
|
+
const SQUEEZED_EM = 1.6;
|
|
39
|
+
// A cell longer than this is prose; a region where more than LONG_CELL_SHARE of the cells are is a page of columns.
|
|
40
|
+
const LONG_CELL_CHARS = 40;
|
|
41
|
+
const LONG_CELL_SHARE = 0.3;
|
|
42
|
+
// A region is a table when at least this many rows have three or more cells and three columns recur in two rows.
|
|
43
|
+
const MIN_COLUMNS = 3;
|
|
44
|
+
const MIN_TABLE_ROWS = 2;
|
|
45
|
+
// A review copy's margin line numbers: at least this many bare numbers outside the text, counting up by one.
|
|
46
|
+
const MIN_LINE_NUMBERS = 5;
|
|
47
|
+
const LINE_NUMBER = /^\d{1,5}$/;
|
|
48
|
+
// A mark this short is drawn on its own baseline often enough (TeX's raised √, a dagger) that its row is the row of
|
|
49
|
+
// the text drawn just before it, when that is within a font size, rather than whichever baseline it happens to be nearer.
|
|
50
|
+
const MARK_CHARS = 2;
|
|
51
|
+
// A two-column page: a gutter in the middle third of the text that at most this share of rows cross, with at least
|
|
52
|
+
// MIN_PROSE_LINES lines of prose on each side.
|
|
53
|
+
const GUTTER_CROSSING_SHARE = 0.1;
|
|
54
|
+
const MIN_PROSE_LINES = 5;
|
|
55
|
+
|
|
56
|
+
interface Piece {
|
|
57
|
+
readonly index: number;
|
|
58
|
+
readonly text: string;
|
|
59
|
+
readonly x0: number;
|
|
60
|
+
readonly x1: number;
|
|
61
|
+
readonly y: number;
|
|
62
|
+
readonly size: number;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface Segment {
|
|
66
|
+
readonly text: string;
|
|
67
|
+
readonly x0: number;
|
|
68
|
+
readonly x1: number;
|
|
69
|
+
/** The items (by index) the cell's text came from. */
|
|
70
|
+
readonly items: readonly number[];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
interface Row {
|
|
74
|
+
readonly y: number;
|
|
75
|
+
readonly size: number;
|
|
76
|
+
readonly segments: Segment[];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
interface Column {
|
|
80
|
+
x0: number;
|
|
81
|
+
x1: number;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** One table found on a page: the markdown it renders as and the items (by index) it consumed. */
|
|
85
|
+
interface Table {
|
|
86
|
+
readonly markdown: string;
|
|
87
|
+
readonly items: readonly number[];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// An upright, unmirrored item with visible text and a size; rotated text (a margin note, an axis label) is no table's.
|
|
91
|
+
const pieceOf = (item: PositionedItem, index: number): Piece | undefined => {
|
|
92
|
+
const [a = 0, b = 0, c = 0, d = 0, e = 0, f = 0] = item.transform;
|
|
93
|
+
const size = Math.abs(d) > 0 ? Math.abs(d) : item.height;
|
|
94
|
+
if (item.str.trim() === "" || size <= 0 || a <= 0 || d <= 0 || Math.abs(b) > size * 1e-3 || Math.abs(c) > size * 1e-3) {
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
return { index, text: item.str, x0: e, x1: e + Math.max(0, item.width), y: f, size };
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
// The pieces of one row, left to right, cut into cells wherever the gap reaches CELL_GAP_EM.
|
|
101
|
+
const segmentsOf = (pieces: readonly Piece[], size: number): Segment[] => {
|
|
102
|
+
const segments: { text: string; x0: number; x1: number; items: number[] }[] = [];
|
|
103
|
+
let current: (typeof segments)[number] | undefined;
|
|
104
|
+
for (const piece of pieces) {
|
|
105
|
+
const gap = current === undefined ? Number.POSITIVE_INFINITY : piece.x0 - current.x1;
|
|
106
|
+
if (current === undefined || gap >= CELL_GAP_EM * size) {
|
|
107
|
+
current = { text: piece.text, x0: piece.x0, x1: piece.x1, items: [piece.index] };
|
|
108
|
+
segments.push(current);
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
current.text += gap > SPACE_GAP_EM * size && !/\s$/.test(current.text) && !/^\s/.test(piece.text) ? ` ${piece.text}` : piece.text;
|
|
112
|
+
current.x1 = Math.max(current.x1, piece.x1);
|
|
113
|
+
current.items.push(piece.index);
|
|
114
|
+
}
|
|
115
|
+
return segments.map((segment) => ({ ...segment, text: segment.text.replaceAll(/\s+/g, " ").trim() }));
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
// Each short mark that rides on the piece drawn just before it, mapped to the piece whose row it joins.
|
|
119
|
+
const ridersOf = (pieces: readonly Piece[]): Map<Piece, Piece> => {
|
|
120
|
+
const riders = new Map<Piece, Piece>();
|
|
121
|
+
for (const [index, piece] of pieces.entries()) {
|
|
122
|
+
const host = pieces[index - 1];
|
|
123
|
+
if (
|
|
124
|
+
host !== undefined &&
|
|
125
|
+
piece.text.trim().length <= MARK_CHARS &&
|
|
126
|
+
piece.x0 >= host.x0 &&
|
|
127
|
+
piece.y !== host.y &&
|
|
128
|
+
Math.abs(piece.y - host.y) <= Math.min(piece.size, host.size)
|
|
129
|
+
) {
|
|
130
|
+
riders.set(piece, riders.get(host) ?? host);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return riders;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
/** The page's visible pieces as rows, top to bottom, each row's pieces left to right and grouped into cells. */
|
|
137
|
+
const rowsOf = (items: readonly PositionedItem[]): Row[] => {
|
|
138
|
+
const drawn = items.flatMap((item, index) => pieceOf(item, index) ?? []);
|
|
139
|
+
const riders = ridersOf(drawn);
|
|
140
|
+
const groups: Piece[][] = [];
|
|
141
|
+
const groupOf = new Map<Piece, Piece[]>();
|
|
142
|
+
for (const piece of drawn.filter((each) => !riders.has(each)).toSorted((p, q) => q.y - p.y || p.x0 - q.x0)) {
|
|
143
|
+
const group = groups.at(-1);
|
|
144
|
+
const anchor = group?.[0];
|
|
145
|
+
if (group !== undefined && anchor !== undefined && anchor.y - piece.y < SAME_ROW_EM * Math.max(anchor.size, piece.size)) {
|
|
146
|
+
group.push(piece);
|
|
147
|
+
} else {
|
|
148
|
+
groups.push([piece]);
|
|
149
|
+
}
|
|
150
|
+
groupOf.set(piece, groups.at(-1) ?? []);
|
|
151
|
+
}
|
|
152
|
+
for (const [rider, host] of riders) {
|
|
153
|
+
groupOf.get(host)?.push(rider);
|
|
154
|
+
}
|
|
155
|
+
return groups.map((group) => {
|
|
156
|
+
const size = Math.max(...group.map((piece) => piece.size));
|
|
157
|
+
return { y: group[0]?.y ?? 0, size, segments: segmentsOf(group.toSorted((p, q) => p.x0 - q.x0), size) };
|
|
158
|
+
});
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
// Whether bare numbers read top to bottom count up the way line numbering does: rising, mostly by one.
|
|
162
|
+
const countsLines = (numbers: readonly Segment[]): boolean => {
|
|
163
|
+
const values = numbers.map((segment) => Number(segment.text));
|
|
164
|
+
const steps = values.slice(1).map((value, index) => value - (values[index] ?? 0));
|
|
165
|
+
return steps.every((step) => step > 0) && steps.filter((step) => step === 1).length >= steps.length * 0.8;
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* The rows without a review copy's margin line numbers (bare numbers counting up, set wholly left or right of every
|
|
170
|
+
* other cell on the page), which would otherwise make a column of their own beside every line of prose. Their items
|
|
171
|
+
* stay in the drawing order like any other text.
|
|
172
|
+
*/
|
|
173
|
+
const withoutLineNumbers = (rows: readonly Row[]): Row[] => {
|
|
174
|
+
const cells = rows.flatMap((row) => row.segments);
|
|
175
|
+
const words = cells.filter((cell) => !LINE_NUMBER.test(cell.text));
|
|
176
|
+
if (words.length === 0) {
|
|
177
|
+
return [...rows];
|
|
178
|
+
}
|
|
179
|
+
const left = Math.min(...words.map((cell) => cell.x0));
|
|
180
|
+
const right = Math.max(...words.map((cell) => cell.x1));
|
|
181
|
+
const margins = [
|
|
182
|
+
cells.filter((cell) => LINE_NUMBER.test(cell.text) && cell.x1 < left),
|
|
183
|
+
cells.filter((cell) => LINE_NUMBER.test(cell.text) && cell.x0 > right),
|
|
184
|
+
].filter((numbers) => numbers.length >= MIN_LINE_NUMBERS && countsLines(numbers));
|
|
185
|
+
const dropped = new Set(margins.flat());
|
|
186
|
+
return dropped.size === 0
|
|
187
|
+
? [...rows]
|
|
188
|
+
: rows.map((row) => ({ ...row, segments: row.segments.filter((segment) => !dropped.has(segment)) })).filter((row) => row.segments.length > 0);
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
// The x ranges a set of cells covers, overlapping ranges merged: what is left between them is the gutters.
|
|
192
|
+
const projection = (spans: readonly { readonly x0: number; readonly x1: number }[]): Column[] => {
|
|
193
|
+
const columns: Column[] = [];
|
|
194
|
+
for (const span of spans.toSorted((s, t) => s.x0 - t.x0)) {
|
|
195
|
+
const last = columns.at(-1);
|
|
196
|
+
if (last !== undefined && span.x0 <= last.x1) {
|
|
197
|
+
last.x1 = Math.max(last.x1, span.x1);
|
|
198
|
+
} else {
|
|
199
|
+
columns.push({ x0: span.x0, x1: span.x1 });
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return columns;
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
const overlaps = (column: Column, segment: Segment): boolean => segment.x0 < column.x1 && column.x0 < segment.x1;
|
|
206
|
+
|
|
207
|
+
// Columns of a region, from the rows with three or more cells. A row with fewer cells adds a column only where it
|
|
208
|
+
// fills a gutter: its cells are often headings spanning two columns ("Customer Information" over a label and a value),
|
|
209
|
+
// which would otherwise merge them.
|
|
210
|
+
const columnsOf = (rows: readonly Row[]): Column[] => {
|
|
211
|
+
const columns = projection(rows.filter((row) => row.segments.length >= MIN_COLUMNS).flatMap((row) => row.segments));
|
|
212
|
+
const strays = rows
|
|
213
|
+
.filter((row) => row.segments.length < MIN_COLUMNS)
|
|
214
|
+
.flatMap((row) => row.segments)
|
|
215
|
+
.filter((segment) => !columns.some((column) => overlaps(column, segment)));
|
|
216
|
+
return projection([...columns, ...strays]);
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
// The column a cell belongs to: the one its range overlaps most, else the nearest one starting at or before it.
|
|
220
|
+
const columnOf = (columns: readonly Column[], segment: Segment): number => {
|
|
221
|
+
let best = 0;
|
|
222
|
+
let bestOverlap = 0;
|
|
223
|
+
for (const [index, column] of columns.entries()) {
|
|
224
|
+
const overlap = Math.min(column.x1, segment.x1) - Math.max(column.x0, segment.x0);
|
|
225
|
+
if (overlap > bestOverlap) {
|
|
226
|
+
best = index;
|
|
227
|
+
bestOverlap = overlap;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
if (bestOverlap > 0) {
|
|
231
|
+
return best;
|
|
232
|
+
}
|
|
233
|
+
const before = columns.findLastIndex((column) => column.x0 <= segment.x0);
|
|
234
|
+
return Math.max(0, before);
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
const startsAtColumn = (columns: readonly Column[], segment: Segment, size: number): boolean =>
|
|
238
|
+
columns.some((column) => Math.abs(column.x0 - segment.x0) <= size);
|
|
239
|
+
|
|
240
|
+
interface Run {
|
|
241
|
+
/** Rows with two or more cells: they define the columns. */
|
|
242
|
+
readonly table: Row[];
|
|
243
|
+
/** Every row of the run in page order, continuation rows included. */
|
|
244
|
+
readonly rows: Row[];
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Whether a region of rows reads as a table rather than columns of prose or a two-field form.
|
|
248
|
+
const isTable = (run: Run, columns: readonly Column[]): boolean => {
|
|
249
|
+
if (run.table.filter((row) => row.segments.length >= MIN_COLUMNS).length < MIN_TABLE_ROWS) {
|
|
250
|
+
return false;
|
|
251
|
+
}
|
|
252
|
+
const rowsPerColumn = columns.map(() => new Set<Row>());
|
|
253
|
+
for (const row of run.table) {
|
|
254
|
+
for (const segment of row.segments) {
|
|
255
|
+
rowsPerColumn[columnOf(columns, segment)]?.add(row);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (rowsPerColumn.filter((rows) => rows.size >= 2).length < MIN_COLUMNS) {
|
|
259
|
+
return false;
|
|
260
|
+
}
|
|
261
|
+
const cells = run.rows.flatMap((row) => row.segments);
|
|
262
|
+
const isLong = (cell: Segment): boolean => cell.text.length > LONG_CELL_CHARS;
|
|
263
|
+
if (cells.filter(isLong).length > cells.length * LONG_CELL_SHARE) {
|
|
264
|
+
return false;
|
|
265
|
+
}
|
|
266
|
+
// A column most of whose cells are long is a column of prose beside a table (a two-column page), not a cell of it.
|
|
267
|
+
const perColumn = columns.map(() => ({ cells: 0, long: 0 }));
|
|
268
|
+
for (const cell of cells) {
|
|
269
|
+
const tally = perColumn[columnOf(columns, cell)];
|
|
270
|
+
if (tally !== undefined) {
|
|
271
|
+
tally.cells += 1;
|
|
272
|
+
tally.long += isLong(cell) ? 1 : 0;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return !perColumn.some((tally) => tally.long >= MIN_COLUMNS && tally.long * 2 >= tally.cells);
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
// The region as a markdown table, its first row the header (a PDF does not say which row is one), through the table
|
|
279
|
+
// writer fileq's other formats use, so a cell's pipe is escaped the same way.
|
|
280
|
+
const tableMarkdown = (rows: readonly Row[], columns: readonly Column[]): string =>
|
|
281
|
+
markdownTable(
|
|
282
|
+
rows.map((row) => {
|
|
283
|
+
const cells = columns.map(() => "");
|
|
284
|
+
for (const segment of row.segments) {
|
|
285
|
+
const column = columnOf(columns, segment);
|
|
286
|
+
cells[column] = cells[column] === "" ? segment.text : `${cells[column]} ${segment.text}`;
|
|
287
|
+
}
|
|
288
|
+
return cells;
|
|
289
|
+
}),
|
|
290
|
+
);
|
|
291
|
+
|
|
292
|
+
// A row the run cannot take as a table row: a continuation of the cell above it, an overlay squeezed between two table
|
|
293
|
+
// rows (left out of the run and left where the drawing order put it), or the end of the run.
|
|
294
|
+
const placeSingle = (run: Run, row: Row, next: Row | undefined): "continue" | "skip" | "end" => {
|
|
295
|
+
const last = run.rows.at(-1);
|
|
296
|
+
if (last === undefined) {
|
|
297
|
+
return "end";
|
|
298
|
+
}
|
|
299
|
+
const lastTable = run.table.at(-1) ?? last;
|
|
300
|
+
if (next !== undefined && next.segments.length >= 2 && lastTable.y - next.y <= SQUEEZED_EM * lastTable.size) {
|
|
301
|
+
return "skip";
|
|
302
|
+
}
|
|
303
|
+
const segment = row.segments[0];
|
|
304
|
+
const fits = segment !== undefined && last.y - row.y <= CONTINUATION_EM * last.size && startsAtColumn(columnsOf(run.table), segment, lastTable.size);
|
|
305
|
+
return fits ? "continue" : "end";
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
const sizeBreaks = (run: Run, row: Row): boolean => {
|
|
309
|
+
const last = run.table.at(-1);
|
|
310
|
+
return last !== undefined && Math.max(last.size, row.size) / Math.min(last.size, row.size) > SIZE_RATIO;
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
// Runs of rows that may be tables, in page order. A run ends at a row that is neither a table row nor a continuation.
|
|
314
|
+
const runsOf = (rows: readonly Row[]): Run[] => {
|
|
315
|
+
const runs: Run[] = [];
|
|
316
|
+
let run: Run = { table: [], rows: [] };
|
|
317
|
+
const close = (): void => {
|
|
318
|
+
if (run.table.length > 0) {
|
|
319
|
+
runs.push(run);
|
|
320
|
+
}
|
|
321
|
+
run = { table: [], rows: [] };
|
|
322
|
+
};
|
|
323
|
+
for (const [index, row] of rows.entries()) {
|
|
324
|
+
if (row.segments.length >= 2) {
|
|
325
|
+
if (sizeBreaks(run, row)) {
|
|
326
|
+
close();
|
|
327
|
+
}
|
|
328
|
+
run.table.push(row);
|
|
329
|
+
run.rows.push(row);
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
const placement = placeSingle(run, row, rows[index + 1]);
|
|
333
|
+
if (placement === "continue") {
|
|
334
|
+
run.rows.push(row);
|
|
335
|
+
} else if (placement === "end") {
|
|
336
|
+
close();
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
close();
|
|
340
|
+
return runs;
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
// The x of a two-column page's gutter, or undefined for a page set in one column (or a form, which has no prose).
|
|
344
|
+
const gutterOf = (rows: readonly Row[]): number | undefined => {
|
|
345
|
+
const cells = rows.flatMap((row) => row.segments);
|
|
346
|
+
const long = cells.filter((cell) => cell.text.length > LONG_CELL_CHARS);
|
|
347
|
+
if (long.length < 2 * MIN_PROSE_LINES) {
|
|
348
|
+
return undefined;
|
|
349
|
+
}
|
|
350
|
+
const left = Math.min(...cells.map((cell) => cell.x0));
|
|
351
|
+
const right = Math.max(...cells.map((cell) => cell.x1));
|
|
352
|
+
const third = (right - left) / 3;
|
|
353
|
+
// A gutter begins where a line of the left column ends, so those ends are the only places worth trying.
|
|
354
|
+
const candidates = [...new Set(cells.map((cell) => Math.round(cell.x1) + 1))].filter((x) => x > left + third && x < right - third);
|
|
355
|
+
const crossings = (x: number): number => rows.filter((row) => row.segments.some((segment) => segment.x0 < x && x < segment.x1)).length;
|
|
356
|
+
const best = candidates.map((x) => ({ x, crossing: crossings(x) })).toSorted((a, b) => a.crossing - b.crossing)[0];
|
|
357
|
+
if (best === undefined || best.crossing > rows.length * GUTTER_CROSSING_SHARE) {
|
|
358
|
+
return undefined;
|
|
359
|
+
}
|
|
360
|
+
const sides = [long.filter((cell) => cell.x1 <= best.x).length, long.filter((cell) => cell.x0 >= best.x).length];
|
|
361
|
+
return sides.every((count) => count >= MIN_PROSE_LINES) ? best.x : undefined;
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
// One side of a two-column page; a cell crossing the gutter (a full-width title or figure) is the left side's.
|
|
365
|
+
const sideOf = (rows: readonly Row[], gutter: number, side: "left" | "right"): Row[] =>
|
|
366
|
+
rows
|
|
367
|
+
.map((row) => ({ ...row, segments: row.segments.filter((segment) => (segment.x0 < gutter) === (side === "left")) }))
|
|
368
|
+
.filter((row) => row.segments.length > 0);
|
|
369
|
+
|
|
370
|
+
const tablesIn = (rows: readonly Row[]): Table[] =>
|
|
371
|
+
runsOf(rows).flatMap((run) => {
|
|
372
|
+
const columns = columnsOf(run.table);
|
|
373
|
+
if (!isTable(run, columns)) {
|
|
374
|
+
return [];
|
|
375
|
+
}
|
|
376
|
+
return [{ markdown: tableMarkdown(run.rows, columns), items: run.rows.flatMap((row) => row.segments.flatMap((segment) => segment.items)) }];
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* The page's tables: each column-aligned region, rendered, with the items it is made of. A two-column page is read one
|
|
381
|
+
* column at a time, so a table in one column takes no lines of the other as cells. A page none of whose rows has three
|
|
382
|
+
* cells can hold no table, which settles a page of prose in one pass.
|
|
383
|
+
*/
|
|
384
|
+
const tablesOf = (items: readonly PositionedItem[]): Table[] => {
|
|
385
|
+
const rows = withoutLineNumbers(rowsOf(items));
|
|
386
|
+
if (!rows.some((row) => row.segments.length >= MIN_COLUMNS)) {
|
|
387
|
+
return [];
|
|
388
|
+
}
|
|
389
|
+
const gutter = gutterOf(rows);
|
|
390
|
+
return gutter === undefined ? tablesIn(rows) : [...tablesIn(sideOf(rows, gutter, "left")), ...tablesIn(sideOf(rows, gutter, "right"))];
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
// The table each item belongs to (-1 for none). A whitespace item between two items of one table belongs to it too, so
|
|
394
|
+
// the gaps pdf.js fills with spaces do not leave stray lines where the table was.
|
|
395
|
+
const ownersOf = (items: readonly PositionedItem[], tables: readonly Table[]): Int32Array => {
|
|
396
|
+
const owner = new Int32Array(items.length).fill(-1);
|
|
397
|
+
for (const [table, { items: members }] of tables.entries()) {
|
|
398
|
+
for (const index of members) {
|
|
399
|
+
owner[index] = table;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
let previous = -1;
|
|
403
|
+
let gap: number[] = [];
|
|
404
|
+
for (const [index, item] of items.entries()) {
|
|
405
|
+
if (item.str.trim() === "" && owner[index] === -1) {
|
|
406
|
+
gap.push(index);
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
const current = owner[index] ?? -1;
|
|
410
|
+
if (current !== -1 && current === previous) {
|
|
411
|
+
for (const blank of gap) {
|
|
412
|
+
owner[blank] = current;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
gap = [];
|
|
416
|
+
previous = current;
|
|
417
|
+
}
|
|
418
|
+
return owner;
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
// Items joined as they always were: in drawing order, a line break where pdf.js saw one, runs of spaces folded.
|
|
422
|
+
const joinItems = (items: readonly PositionedItem[]): string =>
|
|
423
|
+
items
|
|
424
|
+
.map((item) => item.str + (item.hasEOL ? "\n" : ""))
|
|
425
|
+
.join("")
|
|
426
|
+
.replaceAll(/[ \t]+/g, " ")
|
|
427
|
+
.trim();
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* A page's text: its items in drawing order, except that each table region is rendered as a markdown table, set off by
|
|
431
|
+
* blank lines, where the drawing order first reaches one of its items. A page with no table reads exactly as the plain
|
|
432
|
+
* join of its items.
|
|
433
|
+
*/
|
|
434
|
+
export const pageText = (items: readonly PositionedItem[]): string => {
|
|
435
|
+
const tables = tablesOf(items);
|
|
436
|
+
if (tables.length === 0) {
|
|
437
|
+
return joinItems(items);
|
|
438
|
+
}
|
|
439
|
+
const owner = ownersOf(items, tables);
|
|
440
|
+
const blocks: string[] = [];
|
|
441
|
+
let prose: PositionedItem[] = [];
|
|
442
|
+
const emitted = new Set<number>();
|
|
443
|
+
const flush = (): void => {
|
|
444
|
+
// The items a table took leave their line breaks behind; one blank line marks where they were.
|
|
445
|
+
const text = joinItems(prose).replaceAll(/\n(?:[ \t]*\n)+/g, "\n\n");
|
|
446
|
+
if (text !== "") {
|
|
447
|
+
blocks.push(text);
|
|
448
|
+
}
|
|
449
|
+
prose = [];
|
|
450
|
+
};
|
|
451
|
+
for (const [index, item] of items.entries()) {
|
|
452
|
+
const table = owner[index] ?? -1;
|
|
453
|
+
if (table === -1) {
|
|
454
|
+
prose.push(item);
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
if (!emitted.has(table)) {
|
|
458
|
+
emitted.add(table);
|
|
459
|
+
flush();
|
|
460
|
+
blocks.push(tables[table]?.markdown ?? "");
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
flush();
|
|
464
|
+
return blocks.join("\n\n");
|
|
465
|
+
};
|
package/src/lib/derivers/pdf.ts
CHANGED
|
@@ -2,11 +2,13 @@ import { spawnSync } from "node:child_process";
|
|
|
2
2
|
import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import { execBounded, ProcessError
|
|
6
|
-
import {
|
|
5
|
+
import { execBounded, ProcessError } from "@intentic/base/process";
|
|
6
|
+
import { getDocumentProxy, getMeta } from "unpdf";
|
|
7
|
+
import { runInOcrSlot } from "../ocr-slots.js";
|
|
7
8
|
import { onPath } from "../tools.js";
|
|
8
9
|
import type { DerivedDoc, Deriver } from "./deriver.js";
|
|
9
10
|
import { stripRunningFurniture } from "./pdf-furniture.js";
|
|
11
|
+
import { pageText } from "./pdf-tables.js";
|
|
10
12
|
|
|
11
13
|
// PDF text layer, per page, via unpdf's serverless pdf.js build (no worker, canvas or DOM shims needed for text
|
|
12
14
|
// extraction).
|
|
@@ -24,6 +26,11 @@ const SCAN_THRESHOLD_CHARS_PER_PAGE = 24;
|
|
|
24
26
|
const DEFAULT_OCR_PAGES = 20;
|
|
25
27
|
const MAX_OCR_PAGES = 5000;
|
|
26
28
|
const OCR_DPI = "200";
|
|
29
|
+
// Pages drawn and read this many at a time. The drawings on disk stay one chunk's worth (all 500 at once were about
|
|
30
|
+
// 900 MB of PNG in /tmp), each reader process ends after its chunk, and the machine's OCR slot (ocr-slots.ts) is let
|
|
31
|
+
// go between chunks, so a read waiting behind a 500-page scan waits for one chunk of it. Starting a reader costs about
|
|
32
|
+
// half a second against several seconds a page.
|
|
33
|
+
const OCR_CHUNK_PAGES = 8;
|
|
27
34
|
|
|
28
35
|
/** How many pages of a scan this run recognises: FILEQ_OCR_PAGES when it is a sane count, else 20. */
|
|
29
36
|
export const ocrPageCap = (): number => {
|
|
@@ -57,34 +64,72 @@ export const ocrAvailable = (): boolean => {
|
|
|
57
64
|
|
|
58
65
|
// What `ocr` printed for its images, one page per image: it writes a form feed line between images, and an image it
|
|
59
66
|
// could not read leaves its page empty (exit 1) rather than shifting the ones after it. The pages are split on those
|
|
60
|
-
// form feeds, so the cap stays well past what
|
|
67
|
+
// form feeds, so the cap stays well past what a chunk of pages comes to: a cut middle would shift every page after it.
|
|
61
68
|
const readPages = async (images: readonly string[]): Promise<string> => {
|
|
62
|
-
const result = await
|
|
69
|
+
const result = await runInOcrSlot("ocr", images, { timeoutMs: ocrTimeoutMs(images.length), maxOutput: 64 * 1024 * 1024 });
|
|
63
70
|
if (!result.timedOut && (result.exitCode === 0 || result.exitCode === 1)) {
|
|
64
71
|
return result.stdout.text;
|
|
65
72
|
}
|
|
66
73
|
throw new ProcessError("ocr", images, result);
|
|
67
74
|
};
|
|
68
75
|
|
|
76
|
+
// The page a drawing is of, off the number pdftoppm puts in its name (`page-07.tif`).
|
|
77
|
+
const pageNumberOf = (image: string): number => Number(/-(\d+)\.tif$/.exec(image)?.[1] ?? Number.NaN);
|
|
78
|
+
|
|
79
|
+
// Pages `first` to `last` drawn and read, one entry per page whether or not it could be drawn, and the drawings
|
|
80
|
+
// removed. TIFF with PackBits is as lossless as PNG, so the reader sees the same pixels and reads the same text, but
|
|
81
|
+
// pdftoppm writes it about twelve times faster: PNG's compression cost 0.85 s a page at 200 dpi (measured 2026-11-23).
|
|
82
|
+
const recogniseChunk = async (absPath: string, dir: string, first: number, last: number): Promise<string[]> => {
|
|
83
|
+
const prefix = join(dir, "page");
|
|
84
|
+
await execBounded("pdftoppm", ["-r", OCR_DPI, "-tiff", "-tiffcompression", "packbits", "-f", String(first), "-l", String(last), absPath, prefix], {
|
|
85
|
+
timeoutMs: 60_000 + (last - first + 1) * 2_000,
|
|
86
|
+
});
|
|
87
|
+
const images = (await readdir(dir)).filter((name) => name.endsWith(".tif")).toSorted((a, b) => pageNumberOf(a) - pageNumberOf(b));
|
|
88
|
+
try {
|
|
89
|
+
const text = images.length === 0 ? [] : (await readPages(images.map((image) => join(dir, image)))).split("\f");
|
|
90
|
+
const pages = Array.from({ length: last - first + 1 }, () => "");
|
|
91
|
+
for (const [index, image] of images.entries()) {
|
|
92
|
+
const page = pageNumberOf(image) - first;
|
|
93
|
+
if (page >= 0 && page < pages.length) {
|
|
94
|
+
pages[page] = (text[index] ?? "").replaceAll(/[ \t]+/g, " ").trim();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return pages;
|
|
98
|
+
} finally {
|
|
99
|
+
await Promise.all(images.map((image) => rm(join(dir, image), { force: true })));
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
|
|
69
103
|
const recognisePages = async (absPath: string, totalPages: number, cap: number): Promise<string[]> => {
|
|
70
104
|
const dir = await mkdtemp(join(tmpdir(), "fileq-ocr-"));
|
|
71
105
|
const last = Math.min(totalPages, cap);
|
|
72
106
|
try {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
const images = (await readdir(dir)).filter((name) => name.endsWith(".png")).toSorted();
|
|
77
|
-
if (images.length === 0) {
|
|
78
|
-
return [];
|
|
107
|
+
const pages: string[] = [];
|
|
108
|
+
for (let first = 1; first <= last; first += OCR_CHUNK_PAGES) {
|
|
109
|
+
pages.push(...(await recogniseChunk(absPath, dir, first, Math.min(last, first + OCR_CHUNK_PAGES - 1))));
|
|
79
110
|
}
|
|
80
|
-
|
|
81
|
-
const pages = (await readPages(images.map((image) => join(dir, image)))).split("\f");
|
|
82
|
-
return images.map((_, index) => (pages[index] ?? "").replaceAll(/[ \t]+/g, " ").trim());
|
|
111
|
+
return pages;
|
|
83
112
|
} finally {
|
|
84
113
|
await rm(dir, { recursive: true, force: true });
|
|
85
114
|
}
|
|
86
115
|
};
|
|
87
116
|
|
|
117
|
+
type PdfDocument = Awaited<ReturnType<typeof getDocumentProxy>>;
|
|
118
|
+
|
|
119
|
+
// Each page's text, one page at a time and each let go once read: unpdf's extractText asks for every page at once,
|
|
120
|
+
// and pdf.js holds them all until the end (a 5000-page text pdf peaked at 699 MB that way, 286 MB this way). A page's
|
|
121
|
+
// items are joined in drawing order, its column-aligned regions as markdown tables (pdf-tables.ts).
|
|
122
|
+
const pageTexts = async (pdf: PdfDocument): Promise<string[]> => {
|
|
123
|
+
const pages: string[] = [];
|
|
124
|
+
for (let number = 1; number <= pdf.numPages; number++) {
|
|
125
|
+
const page = await pdf.getPage(number);
|
|
126
|
+
const content = await page.getTextContent();
|
|
127
|
+
pages.push(pageText(content.items.filter((item) => "str" in item)));
|
|
128
|
+
page.cleanup();
|
|
129
|
+
}
|
|
130
|
+
return pages;
|
|
131
|
+
};
|
|
132
|
+
|
|
88
133
|
const pagesToMarkdown = (pages: readonly string[]): string =>
|
|
89
134
|
pages.length === 1
|
|
90
135
|
? (pages[0] ?? "")
|
|
@@ -103,6 +148,36 @@ const withoutFurniture = (pages: readonly string[]): { markdown: string; notes:
|
|
|
103
148
|
return { markdown: pagesToMarkdown(kept), notes: furnitureNotes(removed, example) };
|
|
104
149
|
};
|
|
105
150
|
|
|
151
|
+
const derivePdf = async (absPath: string, pdf: PdfDocument): Promise<DerivedDoc> => {
|
|
152
|
+
const totalPages = pdf.numPages;
|
|
153
|
+
const pages = await pageTexts(pdf);
|
|
154
|
+
const meta = await getMeta(pdf).catch(() => undefined);
|
|
155
|
+
const info = meta?.info as Record<string, unknown> | undefined;
|
|
156
|
+
const title = typeof info?.["Title"] === "string" && info["Title"] !== "" ? info["Title"] : undefined;
|
|
157
|
+
const totalChars = pages.reduce((sum, page) => sum + page.length, 0);
|
|
158
|
+
if (totalChars < SCAN_THRESHOLD_CHARS_PER_PAGE * totalPages) {
|
|
159
|
+
const plural = totalPages === 1 ? "" : "s";
|
|
160
|
+
if (!ocrAvailable()) {
|
|
161
|
+
return {
|
|
162
|
+
markdown: "",
|
|
163
|
+
title,
|
|
164
|
+
notes: [`no usable text layer across ${totalPages} page${plural} (a scan?): OCR is not part of this tier`],
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
const cap = ocrPageCap();
|
|
168
|
+
const recognised = await recognisePages(absPath, totalPages, cap);
|
|
169
|
+
const notes = [
|
|
170
|
+
`scanned: text recognised by OCR (PaddleOCR) on ${recognised.length} of ${totalPages} page${plural} — recognised, not exact; check figures against the page image`,
|
|
171
|
+
];
|
|
172
|
+
if (totalPages > cap) {
|
|
173
|
+
notes.push(capNote(cap));
|
|
174
|
+
}
|
|
175
|
+
const { markdown, notes: stripped } = withoutFurniture(recognised);
|
|
176
|
+
return { markdown, title, notes: [...notes, ...stripped] };
|
|
177
|
+
}
|
|
178
|
+
return { title, ...withoutFurniture(pages) };
|
|
179
|
+
};
|
|
180
|
+
|
|
106
181
|
export const pdfDeriver: Deriver = {
|
|
107
182
|
// The stamp names OCR capability, since a sidecar written before the reader was available must read as stale now
|
|
108
183
|
// that it's here. A static name would leave a pre-OCR sidecar looking current forever. It names the reader too:
|
|
@@ -110,35 +185,14 @@ export const pdfDeriver: Deriver = {
|
|
|
110
185
|
get name(): string {
|
|
111
186
|
return ocrAvailable() ? "pdf+ppocr" : "pdf";
|
|
112
187
|
},
|
|
113
|
-
version:
|
|
188
|
+
version: 3,
|
|
114
189
|
derive: async (absPath): Promise<DerivedDoc> => {
|
|
115
190
|
const pdf = await getDocumentProxy(new Uint8Array(await readFile(absPath)));
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
const totalChars = pages.reduce((sum, page) => sum + page.length, 0);
|
|
122
|
-
if (totalChars < SCAN_THRESHOLD_CHARS_PER_PAGE * totalPages) {
|
|
123
|
-
const plural = totalPages === 1 ? "" : "s";
|
|
124
|
-
if (!ocrAvailable()) {
|
|
125
|
-
return {
|
|
126
|
-
markdown: "",
|
|
127
|
-
title,
|
|
128
|
-
notes: [`no usable text layer across ${totalPages} page${plural} (a scan?): OCR is not part of this tier`],
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
|
-
const cap = ocrPageCap();
|
|
132
|
-
const recognised = await recognisePages(absPath, totalPages, cap);
|
|
133
|
-
const notes = [
|
|
134
|
-
`scanned: text recognised by OCR (PaddleOCR) on ${recognised.length} of ${totalPages} page${plural} — recognised, not exact; check figures against the page image`,
|
|
135
|
-
];
|
|
136
|
-
if (totalPages > cap) {
|
|
137
|
-
notes.push(capNote(cap));
|
|
138
|
-
}
|
|
139
|
-
const { markdown, notes: stripped } = withoutFurniture(recognised);
|
|
140
|
-
return { markdown, title, notes: [...notes, ...stripped] };
|
|
191
|
+
// One fileq run derives a batch of files, so each document is let go before the next.
|
|
192
|
+
try {
|
|
193
|
+
return await derivePdf(absPath, pdf);
|
|
194
|
+
} finally {
|
|
195
|
+
await pdf.loadingTask.destroy();
|
|
141
196
|
}
|
|
142
|
-
return { title, ...withoutFurniture(pages) };
|
|
143
197
|
},
|
|
144
198
|
};
|