llm-large-files 0.1.0 → 0.2.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +1 -1
  3. package/dist/analyze.d.ts.map +1 -1
  4. package/dist/analyze.js +5 -1
  5. package/dist/analyze.js.map +1 -1
  6. package/dist/extract.d.ts +17 -1
  7. package/dist/extract.d.ts.map +1 -1
  8. package/dist/extract.js +73 -23
  9. package/dist/extract.js.map +1 -1
  10. package/dist/gemini/chat.d.ts +22 -2
  11. package/dist/gemini/chat.d.ts.map +1 -1
  12. package/dist/gemini/chat.js +41 -24
  13. package/dist/gemini/chat.js.map +1 -1
  14. package/dist/gemini/generate.d.ts.map +1 -1
  15. package/dist/gemini/generate.js +4 -1
  16. package/dist/gemini/generate.js.map +1 -1
  17. package/dist/index.d.ts +2 -1
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/library.d.ts +6 -0
  22. package/dist/library.d.ts.map +1 -1
  23. package/dist/library.js +15 -1
  24. package/dist/library.js.map +1 -1
  25. package/dist/map-reduce.d.ts +7 -0
  26. package/dist/map-reduce.d.ts.map +1 -1
  27. package/dist/map-reduce.js +58 -16
  28. package/dist/map-reduce.js.map +1 -1
  29. package/dist/pdf-layout.d.ts +32 -0
  30. package/dist/pdf-layout.d.ts.map +1 -0
  31. package/dist/pdf-layout.js +790 -0
  32. package/dist/pdf-layout.js.map +1 -0
  33. package/dist/plan.d.ts.map +1 -1
  34. package/dist/plan.js +6 -2
  35. package/dist/plan.js.map +1 -1
  36. package/dist/search.d.ts +8 -4
  37. package/dist/search.d.ts.map +1 -1
  38. package/dist/search.js +49 -24
  39. package/dist/search.js.map +1 -1
  40. package/dist/text.d.ts +18 -4
  41. package/dist/text.d.ts.map +1 -1
  42. package/dist/text.js +155 -15
  43. package/dist/text.js.map +1 -1
  44. package/dist/tools.d.ts.map +1 -1
  45. package/dist/tools.js +11 -3
  46. package/dist/tools.js.map +1 -1
  47. package/dist/types.d.ts +6 -0
  48. package/dist/types.d.ts.map +1 -1
  49. package/docs/api.md +20 -3
  50. package/docs/configuration.md +73 -5
  51. package/docs/getting-started.md +7 -4
  52. package/docs/how-it-works.md +26 -8
  53. package/docs/security.md +18 -5
  54. package/package.json +91 -91
  55. package/src/analyze.ts +3 -1
  56. package/src/extract.ts +77 -22
  57. package/src/gemini/chat.ts +60 -25
  58. package/src/gemini/generate.ts +3 -1
  59. package/src/index.ts +2 -1
  60. package/src/library.ts +241 -226
  61. package/src/map-reduce.ts +69 -16
  62. package/src/node/handlers.ts +122 -122
  63. package/src/pdf-layout.ts +771 -0
  64. package/src/plan.ts +100 -98
  65. package/src/search.ts +48 -25
  66. package/src/stores.ts +132 -132
  67. package/src/text.ts +131 -14
  68. package/src/tools.ts +274 -264
  69. package/src/types.ts +174 -168
@@ -0,0 +1,790 @@
1
+ /**
2
+ * Rebuilds table rows from the position of each piece of text on a PDF page.
3
+ *
4
+ * A PDF has no tables, only text placed at coordinates. Read in file order, a row with an empty
5
+ * cell looks the same as a row without that column, so values slide under the wrong header. This
6
+ * module finds the tables by their geometry and writes each row as `| cell | cell | | cell |`.
7
+ * Everything that is not a table is left in the order pdf.js gives it.
8
+ *
9
+ * It is conservative on purpose: when the evidence for a table is weak, the text stays as it was.
10
+ */
11
+ // All distances below are in multiples of the font size.
12
+ /** Pieces whose baselines are closer than this are on one line. */
13
+ const BASELINE_TOLERANCE = 0.4;
14
+ /** A smaller piece of text this close above or below the line is a footnote mark or an index. */
15
+ const SCRIPT_TOLERANCE = 0.7;
16
+ /** pdf.js keeps words up to this far apart in one piece; a wider gap may be a space or a column. */
17
+ const WORD_GAP = 0.6;
18
+ /** Pieces closer than this are read as one cell: a bold word, a change of script, a wide space. */
19
+ const PIECE_GAP = 0.35;
20
+ /** A gap this wide inside one column means the line was laid out on other columns. */
21
+ const CELL_GAP = 0.8;
22
+ /** A gap that can be seen at all: narrower ones are kerning inside a word. */
23
+ const VISIBLE_GAP = 0.1;
24
+ /** How close a piece of text must come to a column to count as part of it. */
25
+ const COLUMN_TOUCH = 0.25;
26
+ /** How close two cells' edges or centres must be to count as lined up, while a table is traced. */
27
+ const ROW_ALIGNMENT = 0.3;
28
+ /** The tallest step between two lines of one table. */
29
+ const ROW_STEP = 4;
30
+ /** A step down or up in file order larger than these starts a separate block of text. */
31
+ const BLOCK_STEP_DOWN = 5;
32
+ const BLOCK_STEP_UP = 12;
33
+ /** Lines of one wrapped cell are at most this far apart. */
34
+ const WRAPPED_STEP = 1.55;
35
+ /** Lines that span several columns (a sub-heading inside a table) tolerated in a row. */
36
+ const SPANNING_LINES = 2;
37
+ /** A column of whole sentences (a page column, not a table column) has cells at least this long. */
38
+ const PROSE_CELL_CHARACTERS = 30;
39
+ const MIN_COLUMNS = 3;
40
+ const QUARTER_COS = [1, 0, -1, 0];
41
+ const QUARTER_SIN = [0, 1, 0, -1];
42
+ /** PDF space has y pointing up; without a viewport matrix, flip it. */
43
+ const FLIP_Y = [1, 0, 0, -1, 0, 0];
44
+ /** The page text in pdf.js order: what `unpdf.extractText` returns for one page. */
45
+ export function plainPageText(items) {
46
+ let text = "";
47
+ for (const item of items)
48
+ if (typeof item.str === "string")
49
+ text += item.str + (item.hasEOL ? "\n" : "");
50
+ return text;
51
+ }
52
+ function median(values) {
53
+ if (values.length === 0)
54
+ return 0;
55
+ const sorted = [...values].sort((left, right) => left - right);
56
+ return sorted[Math.floor(sorted.length / 2)];
57
+ }
58
+ /**
59
+ * Text pieces in upright coordinates (x along the text, y down the page), grouped by the direction
60
+ * the text runs in: a table printed sideways is analysed on its own, turned upright.
61
+ */
62
+ function toPieces(items, viewport) {
63
+ const groups = [[], [], [], []];
64
+ items.forEach((item, index) => {
65
+ if (typeof item.str !== "string" || !item.str.trim())
66
+ return;
67
+ const matrix = item.transform;
68
+ if (!Array.isArray(matrix) || matrix.length < 6)
69
+ return;
70
+ const a = viewport[0] * matrix[0] + viewport[2] * matrix[1];
71
+ const b = viewport[1] * matrix[0] + viewport[3] * matrix[1];
72
+ const x = viewport[0] * matrix[4] + viewport[2] * matrix[5] + viewport[4];
73
+ const y = viewport[1] * matrix[4] + viewport[3] * matrix[5] + viewport[5];
74
+ const scale = Math.hypot(a, b);
75
+ if (!Number.isFinite(scale) || scale === 0 || !Number.isFinite(x) || !Number.isFinite(y))
76
+ return;
77
+ const angle = Math.atan2(b, a);
78
+ const quarter = Math.round(angle / (Math.PI / 2));
79
+ if (Math.abs(angle - quarter * (Math.PI / 2)) > 0.09)
80
+ return; // slanted text is left as it is
81
+ const group = ((quarter % 4) + 4) % 4;
82
+ const cos = QUARTER_COS[group];
83
+ const sin = QUARTER_SIN[group];
84
+ const size = item.height > 0 ? item.height : scale;
85
+ const width = item.width > 0 ? item.width : item.str.length * size * 0.5;
86
+ const x0 = x * cos + y * sin;
87
+ groups[group].push({ index, group, text: item.str.trim(), x0, x1: x0 + width, y: y * cos - x * sin, size });
88
+ });
89
+ return groups;
90
+ }
91
+ /**
92
+ * Splits text into blocks where the file order jumps far away, as it does from the foot of one
93
+ * page column to the head of the next. Tables are only looked for inside a block, so the prose of
94
+ * a neighbouring column is never mistaken for cells of the same row.
95
+ */
96
+ function toBlocks(pieces) {
97
+ const blocks = [];
98
+ let current = [];
99
+ for (const piece of pieces) {
100
+ const last = current.at(-1);
101
+ if (last) {
102
+ const size = Math.max(last.size, piece.size);
103
+ const step = piece.y - last.y;
104
+ if (step > BLOCK_STEP_DOWN * size || step < -BLOCK_STEP_UP * size) {
105
+ blocks.push(current);
106
+ current = [];
107
+ }
108
+ }
109
+ current.push(piece);
110
+ }
111
+ if (current.length > 0)
112
+ blocks.push(current);
113
+ return blocks;
114
+ }
115
+ /** Lines of text, top to bottom. Pieces closer than `glue` font sizes form one segment. */
116
+ function toLines(pieces, glue) {
117
+ const sorted = [...pieces].sort((left, right) => left.y - right.y || left.x0 - right.x0);
118
+ const groups = [];
119
+ let lineY = 0;
120
+ let lineSize = 0;
121
+ for (const piece of sorted) {
122
+ const current = groups.at(-1);
123
+ const larger = Math.max(piece.size, lineSize);
124
+ const tolerance = Math.min(piece.size, lineSize) < 0.8 * larger ? SCRIPT_TOLERANCE : BASELINE_TOLERANCE;
125
+ if (current && piece.y - lineY <= tolerance * larger) {
126
+ current.push(piece);
127
+ // A raised mark may come first: the line's baseline is that of its full-size text.
128
+ if (piece.size > lineSize / 0.8)
129
+ lineY = piece.y;
130
+ lineSize = larger;
131
+ }
132
+ else {
133
+ groups.push([piece]);
134
+ lineY = piece.y;
135
+ lineSize = piece.size;
136
+ }
137
+ }
138
+ return groups.map((group) => {
139
+ group.sort((left, right) => left.x0 - right.x0);
140
+ const size = median(group.map((piece) => piece.size));
141
+ const segments = [];
142
+ for (const piece of group) {
143
+ const last = segments.at(-1);
144
+ if (last && piece.x0 - last.x1 < glue * size) {
145
+ last.x1 = Math.max(last.x1, piece.x1);
146
+ last.pieces.push(piece);
147
+ }
148
+ else {
149
+ segments.push({ x0: piece.x0, x1: piece.x1, pieces: [piece] });
150
+ }
151
+ }
152
+ // The baseline of the line is where its full-size text sits, not a raised footnote mark.
153
+ return { y: median(group.filter((piece) => piece.size >= 0.8 * size).map((piece) => piece.y)), size, segments };
154
+ });
155
+ }
156
+ /**
157
+ * The pieces of a segment that have a visible gap between them. Pieces a word space apart are
158
+ * read as one cell, but when the columns around them say otherwise (each part sits in a column
159
+ * of its own), they are two cells whose columns happen to be that close.
160
+ */
161
+ function partsOf(segment, size) {
162
+ const parts = [];
163
+ for (const piece of segment.pieces) {
164
+ const last = parts.at(-1);
165
+ if (last && piece.x0 - last.x1 < VISIBLE_GAP * size) {
166
+ last.x1 = Math.max(last.x1, piece.x1);
167
+ last.pieces.push(piece);
168
+ }
169
+ else {
170
+ parts.push({ x0: piece.x0, x1: piece.x1, pieces: [piece] });
171
+ }
172
+ }
173
+ return parts;
174
+ }
175
+ const regionSize = (lines) => median(lines.map((line) => line.size)) || 1;
176
+ const tooFarBelow = (line, previous) => line.y - previous.y > ROW_STEP * Math.max(line.size, previous.size);
177
+ // ---------- Finding a table: lines whose pieces keep to the same columns ----------
178
+ /** Where a cell goes: the column it lies in, "across" if it lies in several, else a column it nearly touches. */
179
+ function placeCell(columns, cell, touch) {
180
+ const under = columns.filter((column) => cell.x0 < column.x1 && cell.x1 > column.x0);
181
+ if (under.length > 1)
182
+ return "across";
183
+ if (under.length === 1)
184
+ return under[0];
185
+ let nearest;
186
+ let distance = touch;
187
+ for (const column of columns) {
188
+ const gap = Math.max(column.x0 - cell.x1, cell.x0 - column.x1);
189
+ if (gap < distance) {
190
+ distance = gap;
191
+ nearest = column;
192
+ }
193
+ }
194
+ return nearest;
195
+ }
196
+ /**
197
+ * The columns after adding a line, or undefined if the line is not a row of this table: its text
198
+ * runs across two columns, or its cells do not line up with the cells above them. Cells of a
199
+ * column share a left edge, a right edge or a centre; words of a sentence under a table sit in
200
+ * the same columns by chance, but not on those edges.
201
+ */
202
+ function addLine(columns, line) {
203
+ const touch = COLUMN_TOUCH * line.size;
204
+ const tolerance = ROW_ALIGNMENT * line.size;
205
+ const next = columns.map((column) => ({ ...column, cells: [...column.cells] }));
206
+ let placed = 0;
207
+ let aligned = 0;
208
+ const put = (cell, mayAddColumn) => {
209
+ const column = placeCell(next, cell, touch);
210
+ if (column === "across" || (!column && !mayAddColumn))
211
+ return false;
212
+ if (column) {
213
+ placed++;
214
+ const centre = (cell.x0 + cell.x1) / 2;
215
+ if (column.cells.some((other) => Math.abs(other.x0 - cell.x0) <= tolerance || Math.abs(other.x1 - cell.x1) <= tolerance
216
+ || Math.abs((other.x0 + other.x1) / 2 - centre) <= tolerance))
217
+ aligned++;
218
+ column.x0 = Math.min(column.x0, cell.x0);
219
+ column.x1 = Math.max(column.x1, cell.x1);
220
+ column.cells.push({ x0: cell.x0, x1: cell.x1 });
221
+ }
222
+ else {
223
+ next.push({ x0: cell.x0, x1: cell.x1, cells: [{ x0: cell.x0, x1: cell.x1 }] });
224
+ }
225
+ return true;
226
+ };
227
+ for (const segment of line.segments) {
228
+ if (put(segment, true))
229
+ continue;
230
+ // Text across two columns may be two cells that sit close together: then each of its parts
231
+ // lies in a column that is already there.
232
+ const parts = partsOf(segment, line.size);
233
+ if (parts.length < 2 || !parts.every((part) => put(part, false)))
234
+ return undefined;
235
+ }
236
+ if (aligned * 2 < placed)
237
+ return undefined;
238
+ return next.sort((left, right) => left.x0 - right.x0);
239
+ }
240
+ /** Grows a table downwards from a line with at least two cells, while the columns hold. */
241
+ function growRegion(lines, start) {
242
+ let columns = lines[start].segments.map((segment) => ({ x0: segment.x0, x1: segment.x1, cells: [{ x0: segment.x0, x1: segment.x1 }] }));
243
+ let end = start;
244
+ let index = start + 1;
245
+ while (index < lines.length) {
246
+ // A line that crosses columns is accepted only if a normal row follows it closely.
247
+ let probe = index;
248
+ let added;
249
+ while (probe < lines.length && probe - index <= SPANNING_LINES) {
250
+ if (tooFarBelow(lines[probe], lines[probe - 1]))
251
+ break;
252
+ added = addLine(columns, lines[probe]);
253
+ if (added)
254
+ break;
255
+ probe++;
256
+ }
257
+ if (!added)
258
+ break;
259
+ if (probe > index && lines[probe].segments.length < 2)
260
+ break;
261
+ columns = added;
262
+ end = probe;
263
+ index = probe + 1;
264
+ }
265
+ // Text under the table that is not the rest of a wrapped cell does not belong to it.
266
+ while (end > start) {
267
+ const line = lines[end];
268
+ if (line.segments.length >= 2)
269
+ break;
270
+ const segment = line.segments[0];
271
+ let continues = false;
272
+ for (let above = end - 1; above >= start && !continues; above--) {
273
+ const lower = lines[above + 1];
274
+ const upper = lines[above];
275
+ if (lower.y - upper.y > WRAPPED_STEP * Math.max(lower.size, upper.size))
276
+ break;
277
+ continues = upper.segments.some((other) => other.x0 < segment.x1 && other.x1 > segment.x0);
278
+ }
279
+ if (continues)
280
+ break;
281
+ end--;
282
+ }
283
+ return end;
284
+ }
285
+ /**
286
+ * The columns of a region, taken from its most detailed lines first. A heading that spans two
287
+ * columns then lies across both and is treated as a spanning cell, instead of gluing them together.
288
+ */
289
+ function refineColumns(lines) {
290
+ const columns = [];
291
+ const detailedFirst = [...lines].sort((left, right) => right.segments.length - left.segments.length);
292
+ for (const line of detailedFirst) {
293
+ const touch = COLUMN_TOUCH * line.size;
294
+ for (const segment of line.segments) {
295
+ const across = placeCell(columns, segment, touch) === "across";
296
+ for (const cell of across ? partsOf(segment, line.size) : [segment]) {
297
+ const column = placeCell(columns, cell, touch);
298
+ if (column === "across")
299
+ continue;
300
+ if (column) {
301
+ column.x0 = Math.min(column.x0, cell.x0);
302
+ column.x1 = Math.max(column.x1, cell.x1);
303
+ }
304
+ else if (!across) {
305
+ columns.push({ x0: cell.x0, x1: cell.x1 });
306
+ }
307
+ }
308
+ }
309
+ }
310
+ return columns.sort((left, right) => left.x0 - right.x0);
311
+ }
312
+ /** The columns a piece of text lies in. */
313
+ function columnsUnder(columns, segment) {
314
+ return columns.flatMap((column, index) => (segment.x0 < column.x1 && segment.x1 > column.x0 ? [index] : []));
315
+ }
316
+ function columnOf(columns, segment, rightToLeft) {
317
+ // A cell that spans columns goes in the first of them, in reading order.
318
+ let chosen = -1;
319
+ for (let index = 0; index < columns.length; index++) {
320
+ const column = columns[index];
321
+ if (segment.x0 < column.x1 && segment.x1 > column.x0) {
322
+ if (chosen === -1 || rightToLeft)
323
+ chosen = index;
324
+ }
325
+ }
326
+ if (chosen !== -1)
327
+ return chosen;
328
+ let nearest = 0;
329
+ let distance = Infinity;
330
+ columns.forEach((column, index) => {
331
+ const gap = Math.max(column.x0 - segment.x1, segment.x0 - column.x1);
332
+ if (gap < distance) {
333
+ distance = gap;
334
+ nearest = index;
335
+ }
336
+ });
337
+ return nearest;
338
+ }
339
+ /**
340
+ * The cells of a region. `clashes[line]` is true when two separate pieces of that line fall in one
341
+ * column: the line was laid out on other columns than these, so it belongs to another table.
342
+ * `spanning` counts the lines with a cell across several columns.
343
+ */
344
+ function toGrid(lines, columns, rightToLeft) {
345
+ const clashes = [];
346
+ let spanning = 0;
347
+ const grid = lines.map((line) => {
348
+ const row = columns.map(() => []);
349
+ const edge = [];
350
+ let clash = false;
351
+ let across = false;
352
+ for (const segment of line.segments) {
353
+ // Text over two columns is two close cells if each of its parts sits in one column, and
354
+ // otherwise a cell that spans them.
355
+ let cells = [segment];
356
+ if (columnsUnder(columns, segment).length > 1) {
357
+ const parts = partsOf(segment, line.size);
358
+ if (parts.length > 1 && parts.every((part) => columnsUnder(columns, part).length === 1))
359
+ cells = parts;
360
+ else
361
+ across = true;
362
+ }
363
+ for (const cell of cells) {
364
+ const column = columnOf(columns, cell, rightToLeft);
365
+ if (edge[column] !== undefined && cell.x0 - edge[column] >= CELL_GAP * line.size)
366
+ clash = true;
367
+ edge[column] = cell.x1;
368
+ row[column].push(...cell.pieces);
369
+ }
370
+ }
371
+ clashes.push(clash);
372
+ if (across)
373
+ spanning++;
374
+ return row;
375
+ });
376
+ return { grid, clashes, spanning };
377
+ }
378
+ /** The longest run of lines without a clash, as [first, last]. */
379
+ function longestClearRun(clashes) {
380
+ let best = [0, -1];
381
+ let from = 0;
382
+ for (let index = 0; index <= clashes.length; index++) {
383
+ if (index < clashes.length && !clashes[index])
384
+ continue;
385
+ if (index - from > best[1] - best[0] + 1)
386
+ best = [from, index - 1];
387
+ from = index + 1;
388
+ }
389
+ return best;
390
+ }
391
+ /**
392
+ * A column with a single cell is usually not a column:
393
+ * - a word that pdf.js kept apart from the rest of its cell (it sits a word space away), or
394
+ * - a heading that spans two columns ("2025" above "H1" and "H2") and sits between them.
395
+ * The first is joined to its cell; the second moves into the column before it, which is where a
396
+ * spanning cell is conventionally written.
397
+ */
398
+ function absorbLoneColumns(grid, rightToLeft) {
399
+ if (grid.length < 3)
400
+ return grid;
401
+ let columns = grid[0].length;
402
+ for (let column = 0; column < columns && columns > 1; column++) {
403
+ const filled = grid.flatMap((row, line) => (row[column].length > 0 ? [line] : []));
404
+ if (filled.length !== 1)
405
+ continue;
406
+ const row = grid[filled[0]];
407
+ const cell = row[column];
408
+ const size = Math.max(...cell.map((piece) => piece.size));
409
+ const left = Math.min(...cell.map((piece) => piece.x0));
410
+ const right = Math.max(...cell.map((piece) => piece.x1));
411
+ const before = rightToLeft ? column + 1 : column - 1;
412
+ const after = rightToLeft ? column - 1 : column + 1;
413
+ const exists = (index) => index >= 0 && index < columns;
414
+ const distance = (index) => {
415
+ const other = row[index];
416
+ if (other.length === 0)
417
+ return Infinity;
418
+ return index < column ? left - Math.max(...other.map((piece) => piece.x1)) : Math.min(...other.map((piece) => piece.x0)) - right;
419
+ };
420
+ const near = [before, after].filter(exists).find((index) => distance(index) <= WORD_GAP * size);
421
+ const empty = [before, after].filter(exists).find((index) => row[index].length === 0);
422
+ const target = near ?? empty;
423
+ if (target === undefined)
424
+ continue;
425
+ row[target].push(...cell);
426
+ for (const each of grid)
427
+ each.splice(column, 1);
428
+ columns--;
429
+ column--;
430
+ }
431
+ return grid;
432
+ }
433
+ /**
434
+ * Where a second table starts, if two tables with different columns sit directly under each other:
435
+ * the first line from which some columns are never used again and others are used for the first time.
436
+ */
437
+ function stackedTableStart(grid) {
438
+ const first = [];
439
+ const last = [];
440
+ for (let column = 0; column < grid[0].length; column++) {
441
+ const used = grid.flatMap((row, line) => (row[column].length > 0 ? [line] : []));
442
+ if (used.length === 0)
443
+ continue;
444
+ first.push(used[0]);
445
+ last.push(used.at(-1));
446
+ }
447
+ for (let line = 1; line < grid.length; line++) {
448
+ if (last.some((value) => value < line) && first.some((value) => value >= line))
449
+ return line;
450
+ }
451
+ return undefined;
452
+ }
453
+ // ---------- Checks that tell a table from text that merely lines up ----------
454
+ const RIGHT_TO_LEFT = /[\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufeff]/g;
455
+ const LEFT_TO_RIGHT = /[A-Za-z\u00c0-\u024f\u0370-\u052f]/g;
456
+ function isRightToLeft(lines) {
457
+ let rightToLeft = 0;
458
+ let leftToRight = 0;
459
+ for (const line of lines) {
460
+ for (const segment of line.segments) {
461
+ for (const piece of segment.pieces) {
462
+ rightToLeft += piece.text.match(RIGHT_TO_LEFT)?.length ?? 0;
463
+ leftToRight += piece.text.match(LEFT_TO_RIGHT)?.length ?? 0;
464
+ }
465
+ }
466
+ }
467
+ return rightToLeft > leftToRight;
468
+ }
469
+ /** Digits with hardly any letters: "1,204", "17%", "(310)", "2026-01-03". "H1" and "Q2" are labels. */
470
+ function isNumeric(text) {
471
+ const digits = text.match(/\d/g)?.length ?? 0;
472
+ const letters = text.match(/\p{L}/gu)?.length ?? 0;
473
+ return digits > 0 && letters * 2 <= digits;
474
+ }
475
+ /** The text of one line's pieces in one cell, in reading order. */
476
+ function joinPieces(pieces, rightToLeft) {
477
+ const ordered = [...pieces].sort((left, right) => (rightToLeft ? right.x0 - left.x0 : left.x0 - right.x0));
478
+ let text = "";
479
+ ordered.forEach((piece, index) => {
480
+ if (index > 0) {
481
+ const previous = ordered[index - 1];
482
+ const gap = rightToLeft ? previous.x0 - piece.x1 : piece.x0 - previous.x1;
483
+ if (gap > VISIBLE_GAP * Math.max(piece.size, previous.size))
484
+ text += " ";
485
+ }
486
+ text += piece.text;
487
+ });
488
+ return text;
489
+ }
490
+ /** Columns that are their own run of whole sentences in file order: page columns, not table columns. */
491
+ function proseColumns(grid, rightToLeft) {
492
+ const order = grid.flatMap((row) => row.flatMap((cell) => cell.map((piece) => piece.index))).sort((left, right) => left - right);
493
+ const rank = new Map(order.map((index, position) => [index, position]));
494
+ const result = [];
495
+ for (let column = 0; column < grid[0].length; column++) {
496
+ const cells = grid.map((row) => row[column]).filter((cell) => cell.length > 0);
497
+ if (cells.length < 3)
498
+ continue;
499
+ if (median(cells.map((cell) => joinPieces(cell, rightToLeft).length)) < PROSE_CELL_CHARACTERS)
500
+ continue;
501
+ const ranks = cells.flatMap((cell) => cell.map((piece) => rank.get(piece.index)));
502
+ if (Math.max(...ranks) - Math.min(...ranks) + 1 === ranks.length)
503
+ result.push(column);
504
+ }
505
+ return result;
506
+ }
507
+ /** How many of `values` lie within `tolerance` of the most common value. */
508
+ function largestCluster(values, tolerance) {
509
+ let best = 0;
510
+ for (const value of values)
511
+ best = Math.max(best, values.filter((other) => Math.abs(other - value) <= tolerance).length);
512
+ return best;
513
+ }
514
+ /**
515
+ * Cells of a real column share a left edge, a right edge, or a centre. Words of justified prose
516
+ * that happen to sit under each other do not, apart from the two margins, so the columns between
517
+ * the first and the last are the ones that count.
518
+ */
519
+ function hasAlignedColumns(grid, lines) {
520
+ const size = regionSize(lines);
521
+ const gaps = lines.flatMap((line) => line.segments.slice(1).map((segment, index) => segment.x0 - line.segments[index].x1));
522
+ // Wide gaps cannot be word spaces, so positions may be loose (scans with a text layer are).
523
+ // Narrow gaps can be, so the cells must line up exactly, as they do in a typeset table.
524
+ const tolerance = median(gaps) >= 2 * size ? 0.3 * size : Math.max(0.75, 0.1 * size);
525
+ const columns = grid[0].length;
526
+ let candidates = 0;
527
+ let aligned = 0;
528
+ let inner = 0;
529
+ let innerAligned = 0;
530
+ for (let column = 0; column < columns; column++) {
531
+ const cells = grid.map((row) => row[column]).filter((cell) => cell.length > 0);
532
+ if (cells.length < 2)
533
+ continue;
534
+ const left = cells.map((cell) => Math.min(...cell.map((piece) => piece.x0)));
535
+ const right = cells.map((cell) => Math.max(...cell.map((piece) => piece.x1)));
536
+ const centre = left.map((value, index) => (value + right[index]) / 2);
537
+ const best = Math.max(largestCluster(left, tolerance), largestCluster(right, tolerance), largestCluster(centre, tolerance));
538
+ const isAligned = best >= Math.max(2, Math.ceil(0.6 * cells.length));
539
+ candidates++;
540
+ if (isAligned)
541
+ aligned++;
542
+ if (column > 0 && column < columns - 1) {
543
+ inner++;
544
+ if (isAligned)
545
+ innerAligned++;
546
+ }
547
+ }
548
+ if (candidates < 2 || inner === 0)
549
+ return false;
550
+ // With two or three lines there is little evidence, so every column has to line up.
551
+ if (lines.length <= 3)
552
+ return aligned === candidates;
553
+ return innerAligned >= Math.ceil(0.7 * inner) && aligned >= 2;
554
+ }
555
+ function looksLikeTable(grid, lines) {
556
+ if (grid[0].length < MIN_COLUMNS)
557
+ return false;
558
+ const filledPerLine = grid.map((row) => row.filter((cell) => cell.length > 0).length);
559
+ return filledPerLine.filter((count) => count >= 2).length >= 2
560
+ && filledPerLine.some((count) => count >= 3)
561
+ && hasAlignedColumns(grid, lines);
562
+ }
563
+ // ---------- Writing the rows ----------
564
+ /**
565
+ * Which lines start a new row. A row with a wrapped cell takes several lines; they are joined
566
+ * only when the table clearly has two kinds of step (within a row, and between rows) and the
567
+ * joined lines do not look like rows of their own.
568
+ */
569
+ function rowStarts(lines, grid) {
570
+ const starts = lines.map(() => true);
571
+ if (lines.length < 3)
572
+ return starts;
573
+ const size = regionSize(lines);
574
+ const steps = lines.slice(1).map((line, index) => (line.y - lines[index].y) / size);
575
+ const tight = steps.filter((step) => step <= WRAPPED_STEP);
576
+ const loose = steps.filter((step) => step > WRAPPED_STEP);
577
+ if (tight.length === 0 || loose.length === 0 || Math.min(...loose) < 1.3 * Math.max(...tight))
578
+ return starts;
579
+ let from = 0;
580
+ for (let index = 1; index <= lines.length; index++) {
581
+ if (index < lines.length && steps[index - 1] <= WRAPPED_STEP)
582
+ continue;
583
+ // Lines from..index-1 are one candidate row.
584
+ const count = index - from;
585
+ if (count > 1) {
586
+ let filledColumns = 0;
587
+ let fullColumns = 0;
588
+ let repeatedNumbers = false;
589
+ for (let column = 0; column < grid[0].length; column++) {
590
+ const cells = [];
591
+ for (let line = from; line < index; line++)
592
+ if (grid[line][column].length > 0)
593
+ cells.push(grid[line][column]);
594
+ if (cells.length === 0)
595
+ continue;
596
+ filledColumns++;
597
+ if (cells.length === count)
598
+ fullColumns++;
599
+ if (cells.filter((cell) => isNumeric(cell.map((piece) => piece.text).join(""))).length > 1)
600
+ repeatedNumbers = true;
601
+ }
602
+ // Two numbers in one column, or most columns filled on every line: these are separate rows.
603
+ if (!repeatedNumbers && fullColumns * 2 <= filledColumns) {
604
+ for (let line = from + 1; line < index; line++)
605
+ starts[line] = false;
606
+ }
607
+ }
608
+ from = index;
609
+ }
610
+ return starts;
611
+ }
612
+ function cellText(lines, rightToLeft) {
613
+ let text = "";
614
+ for (const pieces of lines) {
615
+ if (pieces.length === 0)
616
+ continue;
617
+ const part = joinPieces(pieces, rightToLeft);
618
+ // "long-" + "standing" is one word; anything else gets a space.
619
+ text += text === "" || (/[A-Za-z0-9]-$/.test(text) && /^[A-Za-z0-9]/.test(part)) ? part : ` ${part}`;
620
+ }
621
+ return text.replace(/\s+/g, " ").replace(/\|/g, "\\|").trim();
622
+ }
623
+ function toTable(lines, grid, rightToLeft) {
624
+ const columnCount = grid[0].length;
625
+ const starts = rowStarts(lines, grid);
626
+ const rows = [];
627
+ let row = [];
628
+ const flush = () => {
629
+ if (row.length === 0)
630
+ return;
631
+ const cells = Array.from({ length: columnCount }, (_, column) => cellText(row.map((line) => line[column]), rightToLeft));
632
+ if (rightToLeft)
633
+ cells.reverse();
634
+ rows.push(`| ${cells.join(" | ")} |`);
635
+ row = [];
636
+ };
637
+ grid.forEach((line, index) => {
638
+ if (starts[index])
639
+ flush();
640
+ row.push(line);
641
+ });
642
+ flush();
643
+ return { indexes: grid.flatMap((line) => line.flatMap((cell) => cell.map((piece) => piece.index))), rows };
644
+ }
645
+ // ---------- The search ----------
646
+ function findTables(pieces, depth = 0) {
647
+ return pieces.length < 5 ? [] : tablesInLines(toLines(pieces, PIECE_GAP), depth);
648
+ }
649
+ function tablesInLines(lines, depth) {
650
+ const tables = [];
651
+ const taken = new Set();
652
+ let start = 0;
653
+ while (start < lines.length) {
654
+ if (lines[start].segments.length < 2) {
655
+ start++;
656
+ continue;
657
+ }
658
+ let end = growRegion(lines, start);
659
+ let region = [];
660
+ let rightToLeft = false;
661
+ let grid = [];
662
+ let clashes = [];
663
+ let spanning = 0;
664
+ const look = (first, last) => {
665
+ end = start + last;
666
+ start += first;
667
+ region = lines.slice(start, end + 1);
668
+ rightToLeft = isRightToLeft(region);
669
+ ({ grid, clashes, spanning } = toGrid(region, refineColumns(region), rightToLeft));
670
+ };
671
+ look(0, end - start);
672
+ if (clashes.some(Boolean)) {
673
+ // Lines laid out on other columns (another table right above or below): keep the longest
674
+ // stretch that agrees, and look at what comes before it on its own.
675
+ const [first, last] = longestClearRun(clashes);
676
+ if (first > 0 && depth < 4)
677
+ tables.push(...tablesInLines(region.slice(0, first), depth + 1));
678
+ look(first, last);
679
+ }
680
+ const second = region.length > 1 ? stackedTableStart(grid) : undefined;
681
+ if (second !== undefined)
682
+ look(0, second - 1);
683
+ if (region.length < 2) {
684
+ start++;
685
+ continue;
686
+ }
687
+ grid = absorbLoneColumns(grid, rightToLeft);
688
+ const prose = proseColumns(grid, rightToLeft);
689
+ if (prose.length > 0) {
690
+ // Set the page columns aside and look again at what is left on these lines.
691
+ if (depth < 4) {
692
+ const rest = grid.flatMap((row) => row.flatMap((cell, column) => (prose.includes(column) ? [] : cell)));
693
+ tables.push(...findTables(rest.sort((left, right) => left.index - right.index), depth + 1));
694
+ }
695
+ start = end + 1;
696
+ continue;
697
+ }
698
+ // A note or a heading may run across the columns of a table; running text does on most lines.
699
+ if (spanning > Math.max(1, Math.floor(region.length / 5)) || !looksLikeTable(grid, region)) {
700
+ start++;
701
+ continue;
702
+ }
703
+ // Heading lines right above, whose cells sit so close together that each line read as one
704
+ // piece of text: taken in when every part of them lies in one column of the table.
705
+ const columns = refineColumns(region);
706
+ const covered = new Set();
707
+ let headingLines = 0;
708
+ for (let above = start - 1; above >= 0 && start - above <= 3; above--) {
709
+ const line = lines[above];
710
+ const below = lines[above + 1];
711
+ const step = (below.y - line.y) / Math.max(below.size, line.size);
712
+ if (taken.has(line) || step > (above === start - 1 ? ROW_STEP : WRAPPED_STEP))
713
+ break;
714
+ const under = line.segments.flatMap((segment) => partsOf(segment, line.size)).map((part) => columnsUnder(columns, part));
715
+ // "2025" above "H1" and "H2" spans two columns; a caption is one piece across most of them.
716
+ if (!under.every((found) => found.length >= 1) || (under.length === 1 && under[0].length > 1))
717
+ break;
718
+ for (const found of under)
719
+ for (const column of found)
720
+ covered.add(column);
721
+ headingLines++;
722
+ }
723
+ if (headingLines > 0 && covered.size >= Math.max(2, Math.ceil(columns.length / 2))) {
724
+ look(-headingLines, end - start);
725
+ grid = absorbLoneColumns(grid, rightToLeft);
726
+ }
727
+ for (const line of region)
728
+ taken.add(line);
729
+ tables.push(toTable(region, grid, rightToLeft));
730
+ start = end + 1;
731
+ }
732
+ return tables;
733
+ }
734
+ // ---------- The page ----------
735
+ /**
736
+ * The text of one PDF page, with tables written as `| cell | cell |` rows.
737
+ *
738
+ * @param items `page.getTextContent().items` from pdf.js.
739
+ * @param viewportTransform `page.getViewport({ scale: 1 }).transform`, which applies the page's
740
+ * rotation. Without it, the page is assumed to be upright.
741
+ */
742
+ export function layoutPageText(items, viewportTransform = FLIP_Y) {
743
+ const tableOf = new Map();
744
+ const pieceOf = new Map();
745
+ for (const group of toPieces(items, viewportTransform)) {
746
+ for (const piece of group)
747
+ pieceOf.set(piece.index, piece);
748
+ for (const block of toBlocks(group)) {
749
+ for (const table of findTables(block))
750
+ for (const index of table.indexes)
751
+ tableOf.set(index, table);
752
+ }
753
+ }
754
+ let text = "";
755
+ const written = new Set();
756
+ let insideTable = false;
757
+ /** The text piece written last, while nothing (no space, no line end) has followed it. */
758
+ let last;
759
+ items.forEach((item, index) => {
760
+ if (typeof item.str !== "string")
761
+ return;
762
+ const table = tableOf.get(index);
763
+ if (table) {
764
+ if (!written.has(table)) {
765
+ written.add(table);
766
+ if (text && !text.endsWith("\n"))
767
+ text += "\n";
768
+ text += `${table.rows.join("\n")}\n`;
769
+ }
770
+ insideTable = true;
771
+ last = undefined;
772
+ return;
773
+ }
774
+ // Spaces and line ends between cells were replaced by the rows above.
775
+ if (insideTable && !item.str.trim())
776
+ return;
777
+ insideTable = false;
778
+ const piece = pieceOf.get(index);
779
+ // pdf.js adds the space between two pieces only when the second is to the right of the first.
780
+ // Right-to-left text runs the other way, so its words would be glued together.
781
+ if (piece && last && last.group === piece.group && Math.abs(piece.y - last.y) <= BASELINE_TOLERANCE * Math.max(piece.size, last.size)
782
+ && last.x0 - piece.x1 > VISIBLE_GAP * Math.max(piece.size, last.size) && !/\s$/.test(text) && !/^\s/.test(item.str)) {
783
+ text += " ";
784
+ }
785
+ text += item.str + (item.hasEOL ? "\n" : "");
786
+ last = piece && !item.hasEOL && item.str.trim() ? piece : undefined;
787
+ });
788
+ return text;
789
+ }
790
+ //# sourceMappingURL=pdf-layout.js.map