@procedures/ocr 0.0.0-stage → 0.68.6

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 (74) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/LICENSE +21 -0
  3. package/README.md +94 -2
  4. package/dist/bbox.d.ts +23 -0
  5. package/dist/bbox.d.ts.map +1 -0
  6. package/dist/bbox.js +76 -0
  7. package/dist/bbox.js.map +1 -0
  8. package/dist/engine.d.ts +40 -0
  9. package/dist/engine.d.ts.map +1 -0
  10. package/dist/engine.js +36 -0
  11. package/dist/engine.js.map +1 -0
  12. package/dist/index.d.ts +8 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +11 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/module.d.ts +33 -0
  17. package/dist/module.d.ts.map +1 -0
  18. package/dist/module.js +84 -0
  19. package/dist/module.js.map +1 -0
  20. package/dist/parse.d.ts +8 -0
  21. package/dist/parse.d.ts.map +1 -0
  22. package/dist/parse.js +8 -0
  23. package/dist/parse.js.map +1 -0
  24. package/dist/procedures/ocr/image.d.ts +14 -0
  25. package/dist/procedures/ocr/image.d.ts.map +1 -0
  26. package/dist/procedures/ocr/image.js +19 -0
  27. package/dist/procedures/ocr/image.js.map +1 -0
  28. package/dist/procedures/ocr/index.d.ts +3 -0
  29. package/dist/procedures/ocr/index.d.ts.map +1 -0
  30. package/dist/procedures/ocr/index.js +3 -0
  31. package/dist/procedures/ocr/index.js.map +1 -0
  32. package/dist/procedures/ocr/page.d.ts +23 -0
  33. package/dist/procedures/ocr/page.d.ts.map +1 -0
  34. package/dist/procedures/ocr/page.js +74 -0
  35. package/dist/procedures/ocr/page.js.map +1 -0
  36. package/dist/programs.d.ts +66 -0
  37. package/dist/programs.d.ts.map +1 -0
  38. package/dist/programs.js +107 -0
  39. package/dist/programs.js.map +1 -0
  40. package/dist/register.d.ts +6 -0
  41. package/dist/register.d.ts.map +1 -0
  42. package/dist/register.js +8 -0
  43. package/dist/register.js.map +1 -0
  44. package/dist/run.d.ts +32 -0
  45. package/dist/run.d.ts.map +1 -0
  46. package/dist/run.js +48 -0
  47. package/dist/run.js.map +1 -0
  48. package/dist/text.d.ts +56 -0
  49. package/dist/text.d.ts.map +1 -0
  50. package/dist/text.js +77 -0
  51. package/dist/text.js.map +1 -0
  52. package/dist/tsv.d.ts +26 -0
  53. package/dist/tsv.d.ts.map +1 -0
  54. package/dist/tsv.js +91 -0
  55. package/dist/tsv.js.map +1 -0
  56. package/dist/types.d.ts +44 -0
  57. package/dist/types.d.ts.map +1 -0
  58. package/dist/types.js +64 -0
  59. package/dist/types.js.map +1 -0
  60. package/package.json +92 -3
  61. package/src/bbox.ts +76 -0
  62. package/src/engine.ts +59 -0
  63. package/src/index.ts +10 -0
  64. package/src/module.ts +103 -0
  65. package/src/parse.ts +8 -0
  66. package/src/procedures/ocr/image.ts +22 -0
  67. package/src/procedures/ocr/index.ts +2 -0
  68. package/src/procedures/ocr/page.ts +80 -0
  69. package/src/programs.ts +142 -0
  70. package/src/register.ts +10 -0
  71. package/src/run.ts +72 -0
  72. package/src/text.ts +120 -0
  73. package/src/tsv.ts +101 -0
  74. package/src/types.ts +122 -0
@@ -0,0 +1,80 @@
1
+ /**
2
+ * ocr.page procedure
3
+ *
4
+ * This procedure gives the text of a PDF page. It reads the text layer of the page first, with
5
+ * `pdftotext`. Only for a page with no text layer, it makes an image of the page with `pdftoppm`
6
+ * and reads the image with the OCR engine.
7
+ */
8
+
9
+ import { existsSync, mkdtempSync, rmSync } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join, resolve } from "node:path";
12
+ import type { ProcedureContext } from "@procedures/client";
13
+ import { parsePdftotextBbox } from "../../bbox.js";
14
+ import { PDFTOPPM, PDFTOTEXT } from "../../programs.js";
15
+ import { createOcrRunner, DEFAULT_TIMEOUT_MS, type OcrRunner } from "../../run.js";
16
+ import { scaleText } from "../../text.js";
17
+ import type { OcrPageInput, OcrPageOutput } from "../../types.js";
18
+
19
+ /** The default resolution of the image of a page for OCR, in dots per inch. */
20
+ export const DEFAULT_DPI = 300;
21
+
22
+ /** The PDF points in one inch. */
23
+ const POINTS_PER_INCH = 72;
24
+
25
+ /** This function gives the argv of `pdftotext` for the text layer of one page, with the boxes. */
26
+ export function pdftotextArgs(file: string, page: number): string[] {
27
+ return ["-f", String(page), "-l", String(page), "-bbox-layout", "-enc", "UTF-8", file, "-"];
28
+ }
29
+
30
+ /** This function gives the argv of `pdftoppm` for a PNG image of one page. The image is `<prefix>.png`. */
31
+ export function pdftoppmArgs(file: string, page: number, dpi: number, prefix: string): string[] {
32
+ return ["-f", String(page), "-l", String(page), "-r", String(dpi), "-png", "-singlefile", file, prefix];
33
+ }
34
+
35
+ /**
36
+ * This function gives the text of one page of the PDF file of the input. The boxes are in PDF
37
+ * points. In the mode `auto`, a page with a word in its text layer gives the text layer. A page
38
+ * with no word gives the text of OCR.
39
+ */
40
+ export async function ocrPage(input: OcrPageInput, ctx: Pick<ProcedureContext, "client">, runner: OcrRunner = createOcrRunner()): Promise<OcrPageOutput> {
41
+ // An absolute path does not start with "-", so a program cannot read it as a flag
42
+ const file = resolve(input.file);
43
+ const page = input.page ?? 1;
44
+ const mode = input.mode ?? "auto";
45
+ const timeout = input.timeout ?? DEFAULT_TIMEOUT_MS;
46
+
47
+ // The text layer also gives the size of the page in points, so it runs in each mode
48
+ const layer = parsePdftotextBbox(await runner.run(PDFTOTEXT, pdftotextArgs(file, page), timeout, ctx));
49
+ if (mode === "text" || (mode === "auto" && layer.lines.length > 0)) return { page, source: "text-layer", ...layer };
50
+
51
+ const dpi = input.dpi ?? DEFAULT_DPI;
52
+ const { engine } = runner;
53
+ const folder = mkdtempSync(join(runner.tempFolder ?? tmpdir(), "procedures-ocr-"));
54
+ try {
55
+ const prefix = join(folder, "page");
56
+ await runner.run(PDFTOPPM, pdftoppmArgs(file, page, dpi, prefix), timeout, ctx);
57
+ const image = `${prefix}.png`;
58
+ if (!existsSync(image)) throw new Error(`pdftoppm made no image of page ${page}`);
59
+ const argv = engine.argv(image, { language: input.language, psm: input.psm, dpi });
60
+ const pixels = engine.parse(await runner.run(engine.program, argv, timeout, ctx));
61
+ const points = scaleText(pixels, POINTS_PER_INCH / dpi, "pt");
62
+ // The size of the page comes from the text layer, when it has one
63
+ const size = layer.width > 0 && layer.height > 0 ? { width: layer.width, height: layer.height } : {};
64
+ return { page, source: "ocr", engine: engine.name, ...points, ...size };
65
+ } finally {
66
+ removeFolder(folder);
67
+ }
68
+ }
69
+
70
+ /**
71
+ * This function removes the temporary folder. A removal that fails leaves the folder and does not
72
+ * throw, so it does not hide the result or the error of the call.
73
+ */
74
+ function removeFolder(folder: string): void {
75
+ try {
76
+ rmSync(folder, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
77
+ } catch {
78
+ // The folder stays in the temporary folder of the system
79
+ }
80
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * The search for the programs of this package on the host: `tesseract` (the OCR engine), and
3
+ * `pdftotext` and `pdftoppm` of Poppler. The package does not download a program. When the search
4
+ * finds no program, `requireProgram` throws an `OcrToolMissingError`.
5
+ */
6
+
7
+ import { existsSync } from "node:fs";
8
+ import { posix, win32 } from "node:path";
9
+
10
+ /** The environment of the search. */
11
+ export type ProgramEnv = Readonly<Record<string, string | undefined>>;
12
+
13
+ /** The description of a program for the search. */
14
+ export interface ProgramSpec {
15
+ /** The name of the program, without `.exe`, for example `tesseract`. */
16
+ readonly name: string;
17
+ /** The environment variables that give the path of the program, in order. */
18
+ readonly env: readonly string[];
19
+ /** The environment variables that give the folder of the program, in order. */
20
+ readonly folderEnv?: readonly string[] | undefined;
21
+ /** This function gives the install paths of the program on an operating system, in order. */
22
+ readonly installed: (platform: NodeJS.Platform, env: ProgramEnv) => readonly string[];
23
+ /** The text that tells how to install the program, for the error. */
24
+ readonly install: string;
25
+ }
26
+
27
+ /** The options of the search. Each one has a default from the host. */
28
+ export interface FindProgramOptions {
29
+ /** The environment (default: `process.env`). */
30
+ readonly env?: ProgramEnv | undefined;
31
+ /** The operating system (default: `process.platform`). */
32
+ readonly platform?: NodeJS.Platform | undefined;
33
+ /** The function that tells if a file exists (default: `existsSync`). */
34
+ readonly exists?: ((path: string) => boolean) | undefined;
35
+ }
36
+
37
+ /** The folders of Homebrew on macOS. An app that starts from the Finder does not have them on the `PATH`. */
38
+ const HOMEBREW_FOLDERS: readonly string[] = ["/opt/homebrew/bin", "/usr/local/bin"];
39
+
40
+ function programFiles(env: ProgramEnv): string[] {
41
+ return [env["ProgramFiles"] ?? env["PROGRAMFILES"] ?? "C:\\Program Files", env["ProgramFiles(x86)"] ?? env["PROGRAMFILES(X86)"] ?? "C:\\Program Files (x86)"];
42
+ }
43
+
44
+ /** The OCR engine tesseract. The installer for Windows puts it in `Tesseract-OCR`, and not on the `PATH`. */
45
+ export const TESSERACT: ProgramSpec = {
46
+ name: "tesseract",
47
+ env: ["TESSERACT_EXE"],
48
+ installed: (platform, env) => {
49
+ if (platform === "win32") {
50
+ const local = env["LOCALAPPDATA"];
51
+ return [
52
+ ...programFiles(env).map((folder) => win32.join(folder, "Tesseract-OCR", "tesseract.exe")),
53
+ ...(local !== undefined ? [win32.join(local, "Programs", "Tesseract-OCR", "tesseract.exe")] : []),
54
+ ];
55
+ }
56
+ return platform === "darwin" ? HOMEBREW_FOLDERS.map((folder) => posix.join(folder, "tesseract")) : [];
57
+ },
58
+ install: "the package tesseract-ocr on Linux, brew install tesseract on macOS, or the Tesseract installer on Windows",
59
+ };
60
+
61
+ function poppler(name: string, env: string): ProgramSpec {
62
+ return {
63
+ name,
64
+ env: [env],
65
+ folderEnv: ["POPPLER_PATH"],
66
+ installed: (platform, environment) => {
67
+ if (platform === "win32") return programFiles(environment).map((folder) => win32.join(folder, "poppler", "Library", "bin", `${name}.exe`));
68
+ return platform === "darwin" ? HOMEBREW_FOLDERS.map((folder) => posix.join(folder, name)) : [];
69
+ },
70
+ install: "the package poppler-utils on Linux, brew install poppler on macOS, or a Poppler build on Windows",
71
+ };
72
+ }
73
+
74
+ /** The program of Poppler that gives the text layer of a PDF page. */
75
+ export const PDFTOTEXT: ProgramSpec = poppler("pdftotext", "PDFTOTEXT_EXE");
76
+
77
+ /** The program of Poppler that makes an image of a PDF page. */
78
+ export const PDFTOPPM: ProgramSpec = poppler("pdftoppm", "PDFTOPPM_EXE");
79
+
80
+ /** The programs of this package. */
81
+ export const OCR_PROGRAMS: readonly ProgramSpec[] = [TESSERACT, PDFTOTEXT, PDFTOPPM];
82
+
83
+ /** The error when a program of this package is not on the host. */
84
+ export class OcrToolMissingError extends Error {
85
+ /** The code of the error, for a check without `instanceof`. */
86
+ readonly code = "OCR_TOOL_MISSING" as const;
87
+ /** The name of the program, for example `tesseract`. */
88
+ readonly tool: string;
89
+ /** The paths that the search examined, in order. */
90
+ readonly searched: readonly string[];
91
+
92
+ override readonly name: string = "OcrToolMissingError";
93
+ constructor(spec: ProgramSpec, searched: readonly string[], cause?: string) {
94
+ const variables = [...spec.env, ...(spec.folderEnv ?? [])].join(" or ");
95
+ const reason = cause === undefined ? `The search examined ${searched.length} paths.` : `It did not start: ${cause}.`;
96
+ super(`The program ${spec.name} is not on this host. ${reason} Install ${spec.install}, or set ${variables}.`);
97
+ this.tool = spec.name;
98
+ this.searched = searched;
99
+ }
100
+ }
101
+
102
+ /** This function gives the folders of the `PATH`, in order. */
103
+ function pathFolders(env: ProgramEnv, windows: boolean): string[] {
104
+ const value = windows ? (env["Path"] ?? env["PATH"]) : env["PATH"];
105
+ if (value === undefined) return [];
106
+ return value.split(windows ? ";" : ":").filter((folder) => folder.length > 0);
107
+ }
108
+
109
+ /**
110
+ * This function gives the paths that the search examines for a program, in order. The order is
111
+ * the folders of the `folderEnv` variables, the install paths, then the folders of the `PATH`.
112
+ */
113
+ export function programCandidates(spec: ProgramSpec, platform: NodeJS.Platform, env: ProgramEnv): string[] {
114
+ const windows = platform === "win32";
115
+ const path = windows ? win32 : posix;
116
+ const file = windows ? `${spec.name}.exe` : spec.name;
117
+ const folders = (spec.folderEnv ?? []).map((name) => env[name]).filter((value): value is string => value !== undefined && value.length > 0);
118
+ return [...folders.map((folder) => path.join(folder, file)), ...spec.installed(platform, env), ...pathFolders(env, windows).map((folder) => path.join(folder, file))];
119
+ }
120
+
121
+ /**
122
+ * This function finds a program. The order is `executable`, then the `env` variables of the spec,
123
+ * then `programCandidates`. It gives `undefined` when it finds none. It does not examine the
124
+ * value of `executable` or of an `env` variable.
125
+ */
126
+ export function findProgram(spec: ProgramSpec, options: FindProgramOptions & { readonly executable?: string | undefined } = {}): string | undefined {
127
+ if (options.executable !== undefined && options.executable.length > 0) return options.executable;
128
+ const env = options.env ?? process.env;
129
+ for (const name of spec.env) {
130
+ const value = env[name];
131
+ if (value !== undefined && value.length > 0) return value;
132
+ }
133
+ const exists = options.exists ?? existsSync;
134
+ return programCandidates(spec, options.platform ?? process.platform, env).find((candidate) => exists(candidate));
135
+ }
136
+
137
+ /** This function finds a program, as `findProgram` does. It throws an `OcrToolMissingError` when it finds none. */
138
+ export function requireProgram(spec: ProgramSpec, options: FindProgramOptions & { readonly executable?: string | undefined } = {}): string {
139
+ const found = findProgram(spec, options);
140
+ if (found !== undefined) return found;
141
+ throw new OcrToolMissingError(spec, programCandidates(spec, options.platform ?? process.platform, options.env ?? process.env));
142
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * An import of this file registers the procedures of @procedures/ocr in the global registry:
3
+ * `import "@procedures/ocr/register"`. The package root registers nothing.
4
+ */
5
+
6
+ import { registerOcrProcedures } from "./module.js";
7
+
8
+ export * from "./module.js";
9
+
10
+ registerOcrProcedures();
package/src/run.ts ADDED
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The run of the programs of this package. Each program starts as argv through a nested
3
+ * `shell.run` call (`defineCliTool` of `@procedures/shell`). No shell starts. The engine of
4
+ * the host applies its rules to that call, and a cancel stops the program.
5
+ */
6
+
7
+ import type { ProcedureContext } from "@procedures/client";
8
+ import { CliToolError, defineCliTool, type CliTool } from "@procedures/shell/cli";
9
+ import { tesseractEngine, type OcrEngine } from "./engine.js";
10
+ import { OcrToolMissingError, requireProgram, type FindProgramOptions, type ProgramSpec } from "./programs.js";
11
+
12
+ /** The default time limit of one program, in milliseconds. */
13
+ export const DEFAULT_TIMEOUT_MS = 120_000;
14
+
15
+ /** The settings of the host for the procedures of this package. The procedure input cannot change them. */
16
+ export interface OcrHostOptions extends FindProgramOptions {
17
+ /**
18
+ * The path of each program, by name: `tesseract`, `pdftotext` or `pdftoppm`. A program with no
19
+ * path comes from the search of `findProgram`.
20
+ */
21
+ readonly executables?: Readonly<Record<string, string | undefined>> | undefined;
22
+ /** The OCR engine (default: `tesseractEngine`). */
23
+ readonly engine?: OcrEngine | undefined;
24
+ /** The folder of the temporary folders (default: the temporary folder of the system). */
25
+ readonly tempFolder?: string | undefined;
26
+ }
27
+
28
+ /** The programs of one host, ready to start. */
29
+ export interface OcrRunner {
30
+ readonly engine: OcrEngine;
31
+ readonly tempFolder: string | undefined;
32
+ /** This function starts a program and gives its standard output. */
33
+ run(spec: ProgramSpec, args: readonly string[], timeout: number, ctx: Pick<ProcedureContext, "client">): Promise<string>;
34
+ }
35
+
36
+ /**
37
+ * True when the output of `shell.run` tells that the program is not there. `shell.run` gives exit
38
+ * code 1 and the error of the start as the standard error, for example `spawn tesseract ENOENT`.
39
+ */
40
+ function notFound(result: { exitCode: number; stdout: string; stderr: string }): boolean {
41
+ return result.exitCode === 1 && result.stdout === "" && /^spawn .+ ENOENT$/.test(result.stderr.trim());
42
+ }
43
+
44
+ /** This function gives the runner of the programs with the settings of the host. */
45
+ export function createOcrRunner(options: OcrHostOptions = {}): OcrRunner {
46
+ const engine = options.engine ?? tesseractEngine;
47
+ const find: FindProgramOptions = { env: options.env, platform: options.platform, exists: options.exists };
48
+ const tools = new Map<string, CliTool>();
49
+ const toolOf = (spec: ProgramSpec): CliTool => {
50
+ let tool = tools.get(spec.name);
51
+ if (tool === undefined) {
52
+ tool = defineCliTool({ name: spec.name, resolve: () => requireProgram(spec, { ...find, executable: options.executables?.[spec.name] }) });
53
+ tools.set(spec.name, tool);
54
+ }
55
+ return tool;
56
+ };
57
+ return {
58
+ engine,
59
+ tempFolder: options.tempFolder,
60
+ async run(spec, args, timeout, ctx) {
61
+ const tool = toolOf(spec);
62
+ const input = tool.shellInput(args, { timeout });
63
+ const result = await tool.call(args, { timeout }, ctx);
64
+ if (notFound(result)) throw new OcrToolMissingError(spec, [input.command], result.stderr.trim());
65
+ if (result.exitCode !== 0) {
66
+ const text = result.stderr.trim() || result.stdout.trim();
67
+ throw new CliToolError(`${spec.name} failed (exit code ${result.exitCode}): ${text}`.trim(), result.exitCode, result.stderr);
68
+ }
69
+ return result.stdout;
70
+ },
71
+ };
72
+ }
package/src/text.ts ADDED
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The records of a recognized text: each word and each line with its text, its confidence and its
3
+ * box. The box is the `Rect` record of `@mark1russell7/layout-contract`: the top-left corner and the
4
+ * size, with the y axis down. This file starts no process and reads no file.
5
+ */
6
+
7
+ import type { Rect } from "@mark1russell7/layout-contract";
8
+
9
+ export type { Rect };
10
+
11
+ /** The unit of the boxes: `px` is a pixel of the image, `pt` is a point of the PDF page (1/72 inch). */
12
+ export type OcrUnit = "px" | "pt";
13
+
14
+ /** One word: its text, its confidence from 0 to 1 and its box. */
15
+ export interface OcrWord {
16
+ readonly text: string;
17
+ /** The confidence of the engine, from 0 to 1. A word of a text layer has the confidence 1. */
18
+ readonly confidence: number;
19
+ readonly box: Rect;
20
+ }
21
+
22
+ /** One line: its text, its confidence, its box and its words, in the order of the line. */
23
+ export interface OcrLine {
24
+ /** The words of the line, with one space between each two words. */
25
+ readonly text: string;
26
+ /** The mean confidence of the words of the line, from 0 to 1. */
27
+ readonly confidence: number;
28
+ readonly box: Rect;
29
+ readonly words: readonly OcrWord[];
30
+ }
31
+
32
+ /** The text of a page or of an image, as lines of words with their boxes. */
33
+ export interface OcrText {
34
+ /** The unit of each box, and of `width` and `height`. */
35
+ readonly unit: OcrUnit;
36
+ /** The width of the page or of the image. */
37
+ readonly width: number;
38
+ /** The height of the page or of the image. */
39
+ readonly height: number;
40
+ /** The text of the lines, with one line end between each two lines. */
41
+ readonly text: string;
42
+ /** The mean confidence of all words, from 0 to 1. A text with no word has the confidence 0. */
43
+ readonly confidence: number;
44
+ readonly lines: readonly OcrLine[];
45
+ }
46
+
47
+ /** This function gives the smallest box that contains each box of the list. An empty list gives the box 0, 0, 0, 0. */
48
+ export function unionBox(boxes: readonly Rect[]): Rect {
49
+ if (boxes.length === 0) return { x: 0, y: 0, w: 0, h: 0 };
50
+ let left = Infinity;
51
+ let top = Infinity;
52
+ let right = -Infinity;
53
+ let bottom = -Infinity;
54
+ for (const box of boxes) {
55
+ left = Math.min(left, box.x);
56
+ top = Math.min(top, box.y);
57
+ right = Math.max(right, box.x + box.w);
58
+ bottom = Math.max(bottom, box.y + box.h);
59
+ }
60
+ return { x: left, y: top, w: right - left, h: bottom - top };
61
+ }
62
+
63
+ /** This function gives the mean confidence of the words, or 0 for an empty list. */
64
+ export function meanConfidence(words: readonly OcrWord[]): number {
65
+ if (words.length === 0) return 0;
66
+ return words.reduce((sum, word) => sum + word.confidence, 0) / words.length;
67
+ }
68
+
69
+ /**
70
+ * This function makes a line from its words. The box of the line is `box`, else the union of the
71
+ * boxes of the words.
72
+ */
73
+ export function makeLine(words: readonly OcrWord[], box?: Rect): OcrLine {
74
+ return {
75
+ text: words.map((word) => word.text).join(" "),
76
+ confidence: meanConfidence(words),
77
+ box: box ?? unionBox(words.map((word) => word.box)),
78
+ words,
79
+ };
80
+ }
81
+
82
+ /** This function makes the text of a page or of an image from its lines. */
83
+ export function makeText(lines: readonly OcrLine[], unit: OcrUnit, width: number, height: number): OcrText {
84
+ return {
85
+ unit,
86
+ width,
87
+ height,
88
+ text: lines.map((line) => line.text).join("\n"),
89
+ confidence: meanConfidence(lines.flatMap((line) => line.words)),
90
+ lines,
91
+ };
92
+ }
93
+
94
+ /** This function rounds a value to 3 decimals, so a scale gives no long fractions. */
95
+ function round3(value: number): number {
96
+ return Math.round(value * 1000) / 1000;
97
+ }
98
+
99
+ function scaleBox(box: Rect, factor: number): Rect {
100
+ return { x: round3(box.x * factor), y: round3(box.y * factor), w: round3(box.w * factor), h: round3(box.h * factor) };
101
+ }
102
+
103
+ /**
104
+ * This function multiplies each box, the width and the height by `factor`, and sets the unit. For
105
+ * example, the factor `72 / 300` changes the pixels of an image at 300 dots per inch to PDF points.
106
+ */
107
+ export function scaleText(text: OcrText, factor: number, unit: OcrUnit): OcrText {
108
+ if (!(factor > 0) || !Number.isFinite(factor)) throw new RangeError(`The scale factor must be a positive number, not ${factor}`);
109
+ return {
110
+ ...text,
111
+ unit,
112
+ width: round3(text.width * factor),
113
+ height: round3(text.height * factor),
114
+ lines: text.lines.map((line) => ({
115
+ ...line,
116
+ box: scaleBox(line.box, factor),
117
+ words: line.words.map((word) => ({ ...word, box: scaleBox(word.box, factor) })),
118
+ })),
119
+ };
120
+ }
package/src/tsv.ts ADDED
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The parse of the TSV output of tesseract (`tesseract <image> stdout tsv`). This file starts no
3
+ * process and reads no file.
4
+ *
5
+ * Each row of the TSV has 12 columns: `level`, `page_num`, `block_num`, `par_num`, `line_num`,
6
+ * `word_num`, `left`, `top`, `width`, `height`, `conf` and `text`. The level is 1 for the page, 2 for
7
+ * a block, 3 for a paragraph, 4 for a line and 5 for a word. Only a word has a confidence: the other
8
+ * rows have the confidence -1.
9
+ */
10
+
11
+ import { makeLine, makeText, unionBox, type OcrText, type OcrWord, type Rect } from "./text.js";
12
+
13
+ /** The columns of the TSV of tesseract, in order. */
14
+ export const TESSERACT_TSV_COLUMNS: readonly string[] = [
15
+ "level",
16
+ "page_num",
17
+ "block_num",
18
+ "par_num",
19
+ "line_num",
20
+ "word_num",
21
+ "left",
22
+ "top",
23
+ "width",
24
+ "height",
25
+ "conf",
26
+ "text",
27
+ ];
28
+
29
+ const PAGE_LEVEL = 1;
30
+ const LINE_LEVEL = 4;
31
+ const WORD_LEVEL = 5;
32
+
33
+ /** One row of the TSV, with the numbers parsed. */
34
+ interface Row {
35
+ readonly level: number;
36
+ /** The key of the line of the row: the page, the block, the paragraph and the line. */
37
+ readonly line: string;
38
+ readonly box: Rect;
39
+ readonly conf: number;
40
+ readonly text: string;
41
+ }
42
+
43
+ /** This function parses one row, or gives undefined for a row that is not a valid row of the TSV. */
44
+ function parseRow(fields: readonly string[]): Row | undefined {
45
+ if (fields.length < 11) return undefined;
46
+ const numbers = fields.slice(0, 11).map(Number);
47
+ if (numbers.some((value) => !Number.isFinite(value))) return undefined;
48
+ const [level, page, block, paragraph, line, , left, top, width, height, conf] = numbers as [number, number, number, number, number, number, number, number, number, number, number];
49
+ return {
50
+ level,
51
+ line: `${page}/${block}/${paragraph}/${line}`,
52
+ box: { x: left, y: top, w: width, h: height },
53
+ conf,
54
+ // The text is the last column. A text with a tab in it is not possible, but the parse keeps it.
55
+ text: fields.slice(11).join("\t").trim(),
56
+ };
57
+ }
58
+
59
+ /** This function changes a confidence of tesseract (0 to 100, or -1 for no value) to a value from 0 to 1. */
60
+ export function tesseractConfidence(conf: number): number {
61
+ if (!(conf > 0)) return 0;
62
+ return Math.min(conf, 100) / 100;
63
+ }
64
+
65
+ /**
66
+ * This function parses the TSV output of tesseract. It gives the lines of words in the order of
67
+ * the output, with the boxes in the pixels of the image.
68
+ *
69
+ * - The parse ignores the header row, an empty row and a row that is not valid.
70
+ * - A word with no text is not in the result. A line with no word is not in the result.
71
+ * - The box of a line is the box of its row of level 4, else the union of the boxes of its words.
72
+ * - The size is the size of the first row of level 1, else the union of all boxes.
73
+ * - With more than one page (a TIFF file with pages), the lines of all pages are in one result.
74
+ */
75
+ export function parseTesseractTsv(tsv: string): OcrText {
76
+ const rows: Row[] = [];
77
+ for (const raw of tsv.split(/\r?\n/)) {
78
+ if (raw.trim().length === 0) continue;
79
+ const row = parseRow(raw.split("\t"));
80
+ if (row !== undefined) rows.push(row);
81
+ }
82
+
83
+ const lineBoxes = new Map<string, Rect>();
84
+ const lineWords = new Map<string, OcrWord[]>();
85
+ let page: Rect | undefined;
86
+ for (const row of rows) {
87
+ if (row.level === PAGE_LEVEL) {
88
+ page ??= row.box;
89
+ } else if (row.level === LINE_LEVEL) {
90
+ lineBoxes.set(row.line, row.box);
91
+ } else if (row.level === WORD_LEVEL && row.text.length > 0) {
92
+ const words = lineWords.get(row.line) ?? [];
93
+ words.push({ text: row.text, confidence: tesseractConfidence(row.conf), box: row.box });
94
+ lineWords.set(row.line, words);
95
+ }
96
+ }
97
+
98
+ const lines = [...lineWords].map(([key, words]) => makeLine(words, lineBoxes.get(key)));
99
+ const size = page ?? unionBox(rows.map((row) => row.box));
100
+ return makeText(lines, "px", size.x + size.w, size.y + size.h);
101
+ }
package/src/types.ts ADDED
@@ -0,0 +1,122 @@
1
+ /**
2
+ * The input and the output of the procedures of this package.
3
+ */
4
+
5
+ import * as z from "zod";
6
+ import { LANGUAGE_PATTERN } from "./engine.js";
7
+ import type { OcrText } from "./text.js";
8
+
9
+ // =============================================================================
10
+ // The shared parts
11
+ // =============================================================================
12
+
13
+ const BoxSchema = z.object({
14
+ x: z.number().describe("The left side of the box"),
15
+ y: z.number().describe("The top side of the box (the y axis points down)"),
16
+ w: z.number().describe("The width of the box"),
17
+ h: z.number().describe("The height of the box"),
18
+ });
19
+
20
+ const WordSchema = z.object({
21
+ text: z.string().describe("The text of the word"),
22
+ confidence: z.number().min(0).max(1).describe("The confidence, from 0 to 1"),
23
+ box: BoxSchema,
24
+ });
25
+
26
+ const LineSchema = z.object({
27
+ text: z.string().describe("The words of the line, with one space between each two words"),
28
+ confidence: z.number().min(0).max(1).describe("The mean confidence of the words, from 0 to 1"),
29
+ box: BoxSchema,
30
+ words: z.array(WordSchema),
31
+ });
32
+
33
+ const textFields = {
34
+ unit: z.enum(["px", "pt"]).describe("The unit of the boxes: px is a pixel of the image, pt is a point of the PDF page"),
35
+ width: z.number().describe("The width of the page or of the image"),
36
+ height: z.number().describe("The height of the page or of the image"),
37
+ text: z.string().describe("The text of the lines, with one line end between each two lines"),
38
+ confidence: z.number().min(0).max(1).describe("The mean confidence of all words, from 0 to 1"),
39
+ lines: z.array(LineSchema),
40
+ };
41
+
42
+ const engineFields = {
43
+ language: z.string().regex(LANGUAGE_PATTERN, "a language name of the engine, for example eng or eng+deu").optional().describe("The language of the text (default: eng)"),
44
+ psm: z.number().int().min(0).max(13).optional().describe("The page segmentation mode of tesseract, from 0 to 13"),
45
+ timeout: z.number().int().positive().optional().describe("The time limit of each program, in milliseconds (default: 120000)"),
46
+ };
47
+
48
+ // =============================================================================
49
+ // ocr.page: the text of a PDF page
50
+ // =============================================================================
51
+
52
+ /** How `ocr.page` gets the text: `auto` uses OCR only for a page with no text layer. */
53
+ export type OcrPageMode = "auto" | "text" | "ocr";
54
+
55
+ /** The input of `ocr.page`. */
56
+ export interface OcrPageInput {
57
+ file: string;
58
+ page?: number | undefined;
59
+ mode?: OcrPageMode | undefined;
60
+ language?: string | undefined;
61
+ psm?: number | undefined;
62
+ dpi?: number | undefined;
63
+ timeout?: number | undefined;
64
+ }
65
+
66
+ export const OcrPageInputSchema: z.ZodType<OcrPageInput> = z.object({
67
+ file: z.string().min(1).describe("The path of the PDF file"),
68
+ page: z.number().int().min(1).optional().describe("The number of the page, from 1 (default: 1)"),
69
+ mode: z
70
+ .enum(["auto", "text", "ocr"])
71
+ .optional()
72
+ .describe("auto: the text layer, else OCR. text: only the text layer. ocr: always OCR (default: auto)"),
73
+ dpi: z.number().int().min(72).max(1200).optional().describe("The resolution of the image of the page for OCR, in dots per inch (default: 300)"),
74
+ ...engineFields,
75
+ });
76
+
77
+ /** The output of `ocr.page`. The boxes are in PDF points. */
78
+ export interface OcrPageOutput extends OcrText {
79
+ /** The number of the page. */
80
+ readonly page: number;
81
+ /** Where the text comes from: the text layer of the page, or OCR of an image of the page. */
82
+ readonly source: "text-layer" | "ocr";
83
+ /** The OCR engine, when the source is `ocr`. */
84
+ readonly engine?: string | undefined;
85
+ }
86
+
87
+ export const OcrPageOutputSchema: z.ZodType<OcrPageOutput> = z.object({
88
+ page: z.number().describe("The number of the page"),
89
+ source: z.enum(["text-layer", "ocr"]).describe("Where the text comes from: the text layer, or OCR of an image of the page"),
90
+ engine: z.string().optional().describe("The OCR engine, when the source is ocr"),
91
+ ...textFields,
92
+ });
93
+
94
+ // =============================================================================
95
+ // ocr.image: the text of an image
96
+ // =============================================================================
97
+
98
+ /** The input of `ocr.image`. */
99
+ export interface OcrImageInput {
100
+ file: string;
101
+ language?: string | undefined;
102
+ psm?: number | undefined;
103
+ dpi?: number | undefined;
104
+ timeout?: number | undefined;
105
+ }
106
+
107
+ export const OcrImageInputSchema: z.ZodType<OcrImageInput> = z.object({
108
+ file: z.string().min(1).describe("The path of the image file, for example a PNG, JPEG or TIFF file"),
109
+ dpi: z.number().int().min(1).max(4800).optional().describe("The resolution of the image, when the file does not tell it"),
110
+ ...engineFields,
111
+ });
112
+
113
+ /** The output of `ocr.image`. The boxes are in the pixels of the image. */
114
+ export interface OcrImageOutput extends OcrText {
115
+ /** The OCR engine. */
116
+ readonly engine: string;
117
+ }
118
+
119
+ export const OcrImageOutputSchema: z.ZodType<OcrImageOutput> = z.object({
120
+ engine: z.string().describe("The OCR engine"),
121
+ ...textFields,
122
+ });