@procedures/ocr 0.68.9 → 0.68.11

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 (52) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +35 -2
  3. package/dist/index.d.ts +1 -1
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +1 -1
  6. package/dist/index.js.map +1 -1
  7. package/dist/module.d.ts.map +1 -1
  8. package/dist/module.js +20 -2
  9. package/dist/module.js.map +1 -1
  10. package/dist/parse.d.ts +2 -0
  11. package/dist/parse.d.ts.map +1 -1
  12. package/dist/parse.js +2 -0
  13. package/dist/parse.js.map +1 -1
  14. package/dist/pdfinfo.d.ts +14 -0
  15. package/dist/pdfinfo.d.ts.map +1 -0
  16. package/dist/pdfinfo.js +20 -0
  17. package/dist/pdfinfo.js.map +1 -0
  18. package/dist/procedures/ocr/index.d.ts +1 -0
  19. package/dist/procedures/ocr/index.d.ts.map +1 -1
  20. package/dist/procedures/ocr/index.js +1 -0
  21. package/dist/procedures/ocr/index.js.map +1 -1
  22. package/dist/procedures/ocr/pageCount.d.ts +20 -0
  23. package/dist/procedures/ocr/pageCount.d.ts.map +1 -0
  24. package/dist/procedures/ocr/pageCount.js +28 -0
  25. package/dist/procedures/ocr/pageCount.js.map +1 -0
  26. package/dist/programs.d.ts +28 -2
  27. package/dist/programs.d.ts.map +1 -1
  28. package/dist/programs.js +30 -5
  29. package/dist/programs.js.map +1 -1
  30. package/dist/run.d.ts +2 -2
  31. package/dist/run.d.ts.map +1 -1
  32. package/dist/run.js +3 -0
  33. package/dist/run.js.map +1 -1
  34. package/dist/table.d.ts +59 -0
  35. package/dist/table.d.ts.map +1 -0
  36. package/dist/table.js +152 -0
  37. package/dist/table.js.map +1 -0
  38. package/dist/types.d.ts +12 -0
  39. package/dist/types.d.ts.map +1 -1
  40. package/dist/types.js +7 -0
  41. package/dist/types.js.map +1 -1
  42. package/package.json +4 -3
  43. package/src/index.ts +1 -1
  44. package/src/module.ts +34 -2
  45. package/src/parse.ts +2 -0
  46. package/src/pdfinfo.ts +19 -0
  47. package/src/procedures/ocr/index.ts +1 -0
  48. package/src/procedures/ocr/pageCount.ts +32 -0
  49. package/src/programs.ts +44 -5
  50. package/src/run.ts +4 -2
  51. package/src/table.ts +188 -0
  52. package/src/types.ts +25 -0
package/src/table.ts ADDED
@@ -0,0 +1,188 @@
1
+ /**
2
+ * The rows and the columns of a table, from the boxes of its words. This file starts no process and
3
+ * reads no file.
4
+ *
5
+ * OCR gives words and lines, not cells. A scan of a table needs its cells, for example to read
6
+ * one column of each row. The method uses only the boxes:
7
+ *
8
+ * 1. Two words are in one row when the vertical centers of their boxes are near.
9
+ * 2. In a row, a wide gap between two words starts a new cell.
10
+ * 3. A column starts at an x position where many rows start a cell.
11
+ * 4. Each word goes to the column that holds the center of its box.
12
+ *
13
+ * The lengths of the options are shares of the median height of the words, so one set of options
14
+ * works for pixels and for points.
15
+ */
16
+
17
+ import { median } from "@mark1russell7/rigor-statistics";
18
+ import { unionBox, type OcrText, type OcrWord, type Rect } from "./text.js";
19
+
20
+ /** The options of `tableOfText`. Each length is a share of the median height of the words. */
21
+ export interface OcrTableOptions {
22
+ /** Two words are in one row when their vertical centers differ by less than this share. The default is 0.7. */
23
+ readonly rowTolerance?: number | undefined;
24
+ /** In a row, a gap of more than this share between two words starts a new cell. The default is 0.75. */
25
+ readonly cellGap?: number | undefined;
26
+ /** Two starts of cells are in one column when they differ by no more than this share. The default is 1. */
27
+ readonly columnTolerance?: number | undefined;
28
+ /** A column needs starts of cells in this share of the rows, from 0 to 1. The default is 0.25. */
29
+ readonly minShare?: number | undefined;
30
+ }
31
+
32
+ /** One cell: its words, their text with one space between words, the mean confidence and the union of the boxes. */
33
+ export interface OcrTableCell {
34
+ readonly text: string;
35
+ readonly confidence: number;
36
+ readonly box: Rect;
37
+ readonly words: readonly OcrWord[];
38
+ }
39
+
40
+ /** One row: the union of the boxes of its words, and one cell for each column. A column with no word in the row has `null`. */
41
+ export interface OcrTableRow {
42
+ readonly box: Rect;
43
+ readonly cells: readonly (OcrTableCell | null)[];
44
+ }
45
+
46
+ /** A table: the left edge of each column, from left to right, and the rows from top to bottom. */
47
+ export interface OcrTable {
48
+ readonly columns: readonly number[];
49
+ readonly rows: readonly OcrTableRow[];
50
+ }
51
+
52
+ /** This function gives the value of an option, or its default. It refuses a value that is not finite or less than 0. */
53
+ function option(name: string, value: number | undefined, fallback: number): number {
54
+ if (value === undefined) return fallback;
55
+ if (!Number.isFinite(value) || value < 0) throw new RangeError(`tableOfText: the option ${name} is ${value}. It is a finite number of 0 or more.`);
56
+ return value;
57
+ }
58
+
59
+ const center = (box: Rect): number => box.x + box.w / 2;
60
+ const middle = (box: Rect): number => box.y + box.h / 2;
61
+
62
+ /** This function groups the words into rows, from top to bottom. Each row has its words from left to right. */
63
+ function groupRows(words: readonly OcrWord[], tolerance: number): OcrWord[][] {
64
+ const sorted = [...words].sort((a, b) => middle(a.box) - middle(b.box) || a.box.x - b.box.x);
65
+ const rows: { mean: number; words: OcrWord[] }[] = [];
66
+ for (const word of sorted) {
67
+ const row = rows[rows.length - 1];
68
+ const value = middle(word.box);
69
+ if (row !== undefined && Math.abs(value - row.mean) < tolerance) {
70
+ row.words.push(word);
71
+ row.mean += (value - row.mean) / row.words.length;
72
+ } else rows.push({ mean: value, words: [word] });
73
+ }
74
+ return rows.map((row) => row.words.sort((a, b) => a.box.x - b.box.x));
75
+ }
76
+
77
+ /** One start of a cell: the left edge and the right edge of the cell, and the index of its row. */
78
+ interface CellStart {
79
+ readonly x: number;
80
+ readonly end: number;
81
+ readonly row: number;
82
+ }
83
+
84
+ /**
85
+ * This function gives the left edge of each column.
86
+ *
87
+ * - Each start of a cell goes to a cluster of starts that are near.
88
+ * - A column of numbers is often right-aligned. Then its starts are far apart, and they make
89
+ * two clusters or more. Two clusters next to each other can be one column.
90
+ * This is true when the median right edges of their cells are near, and no row has a cell in each cluster.
91
+ * Also, the left edge of the two clusters must be to the right of each cell of the column before them.
92
+ * Thus a long cell that starts inside the column before does not move the edge of the next column.
93
+ * - A cluster with starts in less than `minShare` of the rows is not a column.
94
+ */
95
+ function findColumns(rows: readonly OcrWord[][], gap: number, tolerance: number, minShare: number): number[] {
96
+ const starts: CellStart[] = [];
97
+ rows.forEach((words, row) => {
98
+ let first = 0;
99
+ words.forEach((word, index) => {
100
+ const next = words[index + 1];
101
+ if (next === undefined || next.box.x - (word.box.x + word.box.w) > gap) {
102
+ const start = words[first] as OcrWord;
103
+ starts.push({ x: start.box.x, end: word.box.x + word.box.w, row });
104
+ first = index + 1;
105
+ }
106
+ });
107
+ });
108
+ starts.sort((a, b) => a.x - b.x);
109
+ const clusters: CellStart[][] = [];
110
+ for (const start of starts) {
111
+ const cluster = clusters[clusters.length - 1];
112
+ const last = cluster?.[cluster.length - 1];
113
+ if (cluster !== undefined && last !== undefined && start.x - last.x <= tolerance) cluster.push(start);
114
+ else clusters.push([start]);
115
+ }
116
+ const merged: CellStart[][] = [];
117
+ for (const cluster of clusters) {
118
+ const before = merged[merged.length - 1];
119
+ const rowsBefore = new Set(before?.map((start) => start.row));
120
+ const previous = merged[merged.length - 2];
121
+ const aligned =
122
+ before !== undefined &&
123
+ (previous === undefined || Math.min(...before.map((start) => start.x)) >= Math.max(...previous.map((start) => start.end))) &&
124
+ Math.abs(median(before.map((start) => start.end)) - median(cluster.map((start) => start.end))) <= tolerance &&
125
+ cluster.every((start) => !rowsBefore.has(start.row));
126
+ if (aligned) before.push(...cluster);
127
+ else merged.push([...cluster]);
128
+ }
129
+ return merged
130
+ .filter((cluster) => new Set(cluster.map((start) => start.row)).size >= minShare * rows.length)
131
+ .map((cluster) => Math.min(...cluster.map((start) => start.x)));
132
+ }
133
+
134
+ /** This function gives the index of the column that holds the x position: the last column with its left edge at or before it. */
135
+ function columnOf(columns: readonly number[], x: number): number {
136
+ let index = 0;
137
+ columns.forEach((edge, column) => {
138
+ if (edge <= x) index = column;
139
+ });
140
+ return index;
141
+ }
142
+
143
+ /** This function makes a cell from its words, in their order from left to right. */
144
+ function makeCell(words: readonly OcrWord[]): OcrTableCell {
145
+ return {
146
+ text: words.map((word) => word.text).join(" "),
147
+ confidence: words.reduce((sum, word) => sum + word.confidence, 0) / words.length,
148
+ box: unionBox(words.map((word) => word.box)),
149
+ words,
150
+ };
151
+ }
152
+
153
+ /**
154
+ * This function gives the rows and the columns of a table from the boxes of its words. Give the
155
+ * words of one table only: a title or a note above the table becomes a row too.
156
+ *
157
+ * - A row has one cell for each column. A cell is `null` when the row has no word in its column.
158
+ * - A column that holds few starts of cells (less than `minShare` of the rows) is not a column. Its
159
+ * words go to the column at their left.
160
+ * - A word with an empty text is not a word of the table.
161
+ *
162
+ * @param source - A text from the OCR, or its words
163
+ * @param options - The tolerances, as shares of the median height of the words
164
+ * @throws RangeError when an option is not a finite number of 0 or more
165
+ */
166
+ export function tableOfText(source: OcrText | readonly OcrWord[], options: OcrTableOptions = {}): OcrTable {
167
+ const all = "lines" in source ? source.lines.flatMap((line) => line.words) : source;
168
+ const words = all.filter((word) => word.text.trim().length > 0);
169
+ const rowTolerance = option("rowTolerance", options.rowTolerance, 0.7);
170
+ const cellGap = option("cellGap", options.cellGap, 0.75);
171
+ const columnTolerance = option("columnTolerance", options.columnTolerance, 1);
172
+ const minShare = option("minShare", options.minShare, 0.25);
173
+ if (words.length === 0) return { columns: [], rows: [] };
174
+ const heights = words.map((word) => word.box.h).sort((a, b) => a - b);
175
+ const height = heights[Math.floor(heights.length / 2)] as number;
176
+ const rows = groupRows(words, rowTolerance * height);
177
+ const found = findColumns(rows, cellGap * height, columnTolerance * height, minShare);
178
+ // With no column that passes minShare, the table has one column, so that each word stays in a cell
179
+ const columns = found.length > 0 ? found : [Math.min(...words.map((word) => word.box.x))];
180
+ return {
181
+ columns,
182
+ rows: rows.map((row) => {
183
+ const cells: OcrWord[][] = columns.map(() => []);
184
+ for (const word of row) (cells[columnOf(columns, center(word.box))] as OcrWord[]).push(word);
185
+ return { box: unionBox(row.map((word) => word.box)), cells: cells.map((cell) => (cell.length === 0 ? null : makeCell(cell))) };
186
+ }),
187
+ };
188
+ }
package/src/types.ts CHANGED
@@ -106,6 +106,31 @@ export const OcrPageOutputSchema: z.ZodType<OcrPageOutput> = z.object({
106
106
  ...textFields,
107
107
  });
108
108
 
109
+ // =============================================================================
110
+ // ocr.pageCount: the number of pages of a PDF file
111
+ // =============================================================================
112
+
113
+ /** The input of `ocr.pageCount`. */
114
+ export interface OcrPageCountInput {
115
+ file: string;
116
+ timeout?: number | undefined;
117
+ }
118
+
119
+ export const OcrPageCountInputSchema: z.ZodType<OcrPageCountInput> = z.object({
120
+ file: z.string().min(1).describe("The path of the PDF file"),
121
+ timeout: engineFields.timeout,
122
+ });
123
+
124
+ /** The output of `ocr.pageCount`. */
125
+ export interface OcrPageCountOutput {
126
+ /** The number of pages of the file. The pages of `ocr.page` are the numbers from 1 to this number. */
127
+ readonly pages: number;
128
+ }
129
+
130
+ export const OcrPageCountOutputSchema: z.ZodType<OcrPageCountOutput> = z.object({
131
+ pages: z.number().int().min(0).describe("The number of pages of the file. The pages of ocr.page are the numbers from 1 to this number"),
132
+ });
133
+
109
134
  // =============================================================================
110
135
  // ocr.image: the text of an image
111
136
  // =============================================================================