@intentic/fileq 1.431.0 → 1.433.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 +22 -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 +3 -6
- package/dist/lib/derivers/pdf.js.map +1 -1
- package/dist/skill.d.ts.map +1 -1
- package/dist/skill.js +7 -2
- package/dist/skill.js.map +1 -1
- package/package.json +6 -6
- 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 +104 -0
- 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/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 +5 -9
- package/src/render.integration.test.ts +5 -4
- package/src/skill.ts +7 -2
|
@@ -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
|
@@ -8,6 +8,7 @@ import { runInOcrSlot } from "../ocr-slots.js";
|
|
|
8
8
|
import { onPath } from "../tools.js";
|
|
9
9
|
import type { DerivedDoc, Deriver } from "./deriver.js";
|
|
10
10
|
import { stripRunningFurniture } from "./pdf-furniture.js";
|
|
11
|
+
import { pageText } from "./pdf-tables.js";
|
|
11
12
|
|
|
12
13
|
// PDF text layer, per page, via unpdf's serverless pdf.js build (no worker, canvas or DOM shims needed for text
|
|
13
14
|
// extraction).
|
|
@@ -116,19 +117,14 @@ const recognisePages = async (absPath: string, totalPages: number, cap: number):
|
|
|
116
117
|
type PdfDocument = Awaited<ReturnType<typeof getDocumentProxy>>;
|
|
117
118
|
|
|
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,
|
|
119
|
-
// and pdf.js holds them all until the end (a 5000-page text pdf peaked at 699 MB that way, 286 MB this way).
|
|
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).
|
|
120
122
|
const pageTexts = async (pdf: PdfDocument): Promise<string[]> => {
|
|
121
123
|
const pages: string[] = [];
|
|
122
124
|
for (let number = 1; number <= pdf.numPages; number++) {
|
|
123
125
|
const page = await pdf.getPage(number);
|
|
124
126
|
const content = await page.getTextContent();
|
|
125
|
-
pages.push(
|
|
126
|
-
content.items
|
|
127
|
-
.map((item) => ("str" in item ? item.str + (item.hasEOL ? "\n" : "") : ""))
|
|
128
|
-
.join("")
|
|
129
|
-
.replaceAll(/[ \t]+/g, " ")
|
|
130
|
-
.trim(),
|
|
131
|
-
);
|
|
127
|
+
pages.push(pageText(content.items.filter((item) => "str" in item)));
|
|
132
128
|
page.cleanup();
|
|
133
129
|
}
|
|
134
130
|
return pages;
|
|
@@ -189,7 +185,7 @@ export const pdfDeriver: Deriver = {
|
|
|
189
185
|
get name(): string {
|
|
190
186
|
return ocrAvailable() ? "pdf+ppocr" : "pdf";
|
|
191
187
|
},
|
|
192
|
-
version:
|
|
188
|
+
version: 3,
|
|
193
189
|
derive: async (absPath): Promise<DerivedDoc> => {
|
|
194
190
|
const pdf = await getDocumentProxy(new Uint8Array(await readFile(absPath)));
|
|
195
191
|
// One fileq run derives a batch of files, so each document is let go before the next.
|
|
@@ -89,7 +89,7 @@ describe("pdf", () => {
|
|
|
89
89
|
writeFileSync(join(root, "short.pdf"), pagesPdf(2));
|
|
90
90
|
const { out, exitCode } = await fileq("render", join(root, "short.pdf"), "--pages", "5-9");
|
|
91
91
|
expect(exitCode).toBe(2);
|
|
92
|
-
expect(out).toBe(`fileq: cannot render ${join(root, "short.pdf")}: the document has 2 pages; --pages names none of them\n`);
|
|
92
|
+
expect(out).toBe(`fileq: error: usage: cannot render ${join(root, "short.pdf")}: the document has 2 pages; --pages names none of them\n`);
|
|
93
93
|
});
|
|
94
94
|
|
|
95
95
|
test.skipIf(!raster.runs)(raster.title("a long document draws its first twenty pages and says how to get the rest"), async () => {
|
|
@@ -111,7 +111,8 @@ describe("tools", () => {
|
|
|
111
111
|
process.env["PATH"] = "/nonexistent";
|
|
112
112
|
const { out, exitCode } = await fileq("render", join(root, "plain.pdf"));
|
|
113
113
|
expect(exitCode).toBe(2);
|
|
114
|
-
expect(out).toContain("
|
|
114
|
+
expect(out).toContain("fileq: error: missing_tool: cannot render");
|
|
115
|
+
expect(out).toContain("rendering pages needs pdftoppm (poppler-utils) or mutool (mupdf-tools) on PATH, and neither is here\nfileq: next: install one");
|
|
115
116
|
});
|
|
116
117
|
|
|
117
118
|
test("in an Intentic sandbox (its environment command on PATH) it prints the command that asks for the office pack", async () => {
|
|
@@ -124,7 +125,7 @@ describe("tools", () => {
|
|
|
124
125
|
const { out, exitCode } = await fileq("render", join(root, "sandboxed.pdf"));
|
|
125
126
|
expect(exitCode).toBe(2);
|
|
126
127
|
expect(out).toContain(
|
|
127
|
-
'neither is here: ask the owner for the office image pack (LibreOffice and poppler) with `environment propose office --pack --why "to look at the document I made"`',
|
|
128
|
+
'neither is here\nfileq: next: ask the owner for the office image pack (LibreOffice and poppler) with `environment propose office --pack --why "to look at the document I made"`',
|
|
128
129
|
);
|
|
129
130
|
});
|
|
130
131
|
|
|
@@ -144,7 +145,7 @@ describe("tools", () => {
|
|
|
144
145
|
writeFileSync(join(root, "photo.png"), pngBytes());
|
|
145
146
|
const { out, exitCode } = await fileq("render", join(root, "photo.png"));
|
|
146
147
|
expect(exitCode).toBe(1);
|
|
147
|
-
expect(out).
|
|
148
|
+
expect(out).toBe(`fileq: error: unsupported: cannot render ${join(root, "photo.png")}: an image is already pixels: Read it directly\n`);
|
|
148
149
|
});
|
|
149
150
|
});
|
|
150
151
|
|
package/src/skill.ts
CHANGED
|
@@ -84,7 +84,9 @@ cached by content, so a repeat read of unchanged content is instant.
|
|
|
84
84
|
## Read a file
|
|
85
85
|
\`fileq <file>\` (or \`fileq read <file> --budget 8000\`)
|
|
86
86
|
- Prints a capsule (format, token cost), the content up to the budget, and \`saved:\` — the markdown file
|
|
87
|
-
carrying the whole thing. Over budget, the
|
|
87
|
+
carrying the whole thing. Over budget, the last line says where the rest starts: \`[cut at line 212 of 1480,
|
|
88
|
+
~19,100 of 23,100 tokens left: continue with Read <file> from line 212, or raise --budget]\`. Read that file
|
|
89
|
+
from that line rather than from the top.
|
|
88
90
|
- Formats: docx and odt (headings, lists, tables), xlsx (capped tables), pptx (slides + speaker notes),
|
|
89
91
|
pdf (text layer; ${OCR_FORMAT[host]}, and the note says the words are
|
|
90
92
|
recognised, not exact), epub (chapters in reading order), ipynb (cells, fenced code, capped outputs),
|
|
@@ -106,7 +108,10 @@ ${OCR_REFUSAL[host]}
|
|
|
106
108
|
- Plain text (md, csv, txt, code) is not fileq's business: Read it directly — but see below for the big ones.
|
|
107
109
|
- Web pages belong to \`webq\`; images for a vision model belong to the Read tool, which shows the pixels.
|
|
108
110
|
|
|
109
|
-
${SEARCH[host]}${host === "sandbox" ? TEXTCONV : ""}Exit codes: 0 content, 1 nothing derivable, 2 broken invocation or install.
|
|
111
|
+
${SEARCH[host]}${host === "sandbox" ? TEXTCONV : ""}Exit codes: 0 content, 1 nothing derivable, 2 broken invocation or install. A failure is one line,
|
|
112
|
+
\`fileq: error: <code>: <message>\`, often followed by \`fileq: next: <step>\`: do the step. The codes are
|
|
113
|
+
\`usage\`, \`not_found\`, \`unsupported\`, \`too_large\`, \`unreadable\` (damaged, locked or password-protected),
|
|
114
|
+
\`missing_tool\`, \`broken_install\` and \`internal\`; the last two are fileq's fault, never an empty document.
|
|
110
115
|
|
|
111
116
|
## After you produce a document
|
|
112
117
|
A deck, report, spreadsheet or PDF made for someone is not finished until you have checked it and looked at it.
|