@procedures/ocr 0.0.0-bootstrap.0 → 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.
- package/CHANGELOG.md +17 -0
- package/LICENSE +21 -0
- package/README.md +93 -1
- package/dist/bbox.d.ts +23 -0
- package/dist/bbox.d.ts.map +1 -0
- package/dist/bbox.js +76 -0
- package/dist/bbox.js.map +1 -0
- package/dist/engine.d.ts +40 -0
- package/dist/engine.d.ts.map +1 -0
- package/dist/engine.js +36 -0
- package/dist/engine.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/module.d.ts +33 -0
- package/dist/module.d.ts.map +1 -0
- package/dist/module.js +84 -0
- package/dist/module.js.map +1 -0
- package/dist/parse.d.ts +8 -0
- package/dist/parse.d.ts.map +1 -0
- package/dist/parse.js +8 -0
- package/dist/parse.js.map +1 -0
- package/dist/procedures/ocr/image.d.ts +14 -0
- package/dist/procedures/ocr/image.d.ts.map +1 -0
- package/dist/procedures/ocr/image.js +19 -0
- package/dist/procedures/ocr/image.js.map +1 -0
- package/dist/procedures/ocr/index.d.ts +3 -0
- package/dist/procedures/ocr/index.d.ts.map +1 -0
- package/dist/procedures/ocr/index.js +3 -0
- package/dist/procedures/ocr/index.js.map +1 -0
- package/dist/procedures/ocr/page.d.ts +23 -0
- package/dist/procedures/ocr/page.d.ts.map +1 -0
- package/dist/procedures/ocr/page.js +74 -0
- package/dist/procedures/ocr/page.js.map +1 -0
- package/dist/programs.d.ts +66 -0
- package/dist/programs.d.ts.map +1 -0
- package/dist/programs.js +107 -0
- package/dist/programs.js.map +1 -0
- package/dist/register.d.ts +6 -0
- package/dist/register.d.ts.map +1 -0
- package/dist/register.js +8 -0
- package/dist/register.js.map +1 -0
- package/dist/run.d.ts +32 -0
- package/dist/run.d.ts.map +1 -0
- package/dist/run.js +48 -0
- package/dist/run.js.map +1 -0
- package/dist/text.d.ts +56 -0
- package/dist/text.d.ts.map +1 -0
- package/dist/text.js +77 -0
- package/dist/text.js.map +1 -0
- package/dist/tsv.d.ts +26 -0
- package/dist/tsv.d.ts.map +1 -0
- package/dist/tsv.js +91 -0
- package/dist/tsv.js.map +1 -0
- package/dist/types.d.ts +44 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +64 -0
- package/dist/types.js.map +1 -0
- package/package.json +87 -5
- package/src/bbox.ts +76 -0
- package/src/engine.ts +59 -0
- package/src/index.ts +10 -0
- package/src/module.ts +103 -0
- package/src/parse.ts +8 -0
- package/src/procedures/ocr/image.ts +22 -0
- package/src/procedures/ocr/index.ts +2 -0
- package/src/procedures/ocr/page.ts +80 -0
- package/src/programs.ts +142 -0
- package/src/register.ts +10 -0
- package/src/run.ts +72 -0
- package/src/text.ts +120 -0
- package/src/tsv.ts +101 -0
- package/src/types.ts +122 -0
package/dist/tsv.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
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
|
+
import { makeLine, makeText, unionBox } from "./text.js";
|
|
11
|
+
/** The columns of the TSV of tesseract, in order. */
|
|
12
|
+
export const TESSERACT_TSV_COLUMNS = [
|
|
13
|
+
"level",
|
|
14
|
+
"page_num",
|
|
15
|
+
"block_num",
|
|
16
|
+
"par_num",
|
|
17
|
+
"line_num",
|
|
18
|
+
"word_num",
|
|
19
|
+
"left",
|
|
20
|
+
"top",
|
|
21
|
+
"width",
|
|
22
|
+
"height",
|
|
23
|
+
"conf",
|
|
24
|
+
"text",
|
|
25
|
+
];
|
|
26
|
+
const PAGE_LEVEL = 1;
|
|
27
|
+
const LINE_LEVEL = 4;
|
|
28
|
+
const WORD_LEVEL = 5;
|
|
29
|
+
/** This function parses one row, or gives undefined for a row that is not a valid row of the TSV. */
|
|
30
|
+
function parseRow(fields) {
|
|
31
|
+
if (fields.length < 11)
|
|
32
|
+
return undefined;
|
|
33
|
+
const numbers = fields.slice(0, 11).map(Number);
|
|
34
|
+
if (numbers.some((value) => !Number.isFinite(value)))
|
|
35
|
+
return undefined;
|
|
36
|
+
const [level, page, block, paragraph, line, , left, top, width, height, conf] = numbers;
|
|
37
|
+
return {
|
|
38
|
+
level,
|
|
39
|
+
line: `${page}/${block}/${paragraph}/${line}`,
|
|
40
|
+
box: { x: left, y: top, w: width, h: height },
|
|
41
|
+
conf,
|
|
42
|
+
// The text is the last column. A text with a tab in it is not possible, but the parse keeps it.
|
|
43
|
+
text: fields.slice(11).join("\t").trim(),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** This function changes a confidence of tesseract (0 to 100, or -1 for no value) to a value from 0 to 1. */
|
|
47
|
+
export function tesseractConfidence(conf) {
|
|
48
|
+
if (!(conf > 0))
|
|
49
|
+
return 0;
|
|
50
|
+
return Math.min(conf, 100) / 100;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* This function parses the TSV output of tesseract. It gives the lines of words in the order of
|
|
54
|
+
* the output, with the boxes in the pixels of the image.
|
|
55
|
+
*
|
|
56
|
+
* - The parse ignores the header row, an empty row and a row that is not valid.
|
|
57
|
+
* - A word with no text is not in the result. A line with no word is not in the result.
|
|
58
|
+
* - The box of a line is the box of its row of level 4, else the union of the boxes of its words.
|
|
59
|
+
* - The size is the size of the first row of level 1, else the union of all boxes.
|
|
60
|
+
* - With more than one page (a TIFF file with pages), the lines of all pages are in one result.
|
|
61
|
+
*/
|
|
62
|
+
export function parseTesseractTsv(tsv) {
|
|
63
|
+
const rows = [];
|
|
64
|
+
for (const raw of tsv.split(/\r?\n/)) {
|
|
65
|
+
if (raw.trim().length === 0)
|
|
66
|
+
continue;
|
|
67
|
+
const row = parseRow(raw.split("\t"));
|
|
68
|
+
if (row !== undefined)
|
|
69
|
+
rows.push(row);
|
|
70
|
+
}
|
|
71
|
+
const lineBoxes = new Map();
|
|
72
|
+
const lineWords = new Map();
|
|
73
|
+
let page;
|
|
74
|
+
for (const row of rows) {
|
|
75
|
+
if (row.level === PAGE_LEVEL) {
|
|
76
|
+
page ??= row.box;
|
|
77
|
+
}
|
|
78
|
+
else if (row.level === LINE_LEVEL) {
|
|
79
|
+
lineBoxes.set(row.line, row.box);
|
|
80
|
+
}
|
|
81
|
+
else if (row.level === WORD_LEVEL && row.text.length > 0) {
|
|
82
|
+
const words = lineWords.get(row.line) ?? [];
|
|
83
|
+
words.push({ text: row.text, confidence: tesseractConfidence(row.conf), box: row.box });
|
|
84
|
+
lineWords.set(row.line, words);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const lines = [...lineWords].map(([key, words]) => makeLine(words, lineBoxes.get(key)));
|
|
88
|
+
const size = page ?? unionBox(rows.map((row) => row.box));
|
|
89
|
+
return makeText(lines, "px", size.x + size.w, size.y + size.h);
|
|
90
|
+
}
|
|
91
|
+
//# sourceMappingURL=tsv.js.map
|
package/dist/tsv.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tsv.js","sourceRoot":"","sources":["../src/tsv.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAyC,MAAM,WAAW,CAAC;AAEhG,qDAAqD;AACrD,MAAM,CAAC,MAAM,qBAAqB,GAAsB;IACtD,OAAO;IACP,UAAU;IACV,WAAW;IACX,SAAS;IACT,UAAU;IACV,UAAU;IACV,MAAM;IACN,KAAK;IACL,O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E,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;YACxF,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;IAED,MAAM,KAAK,GAAG,CAAC,GAAG,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IACxF,MAAM,IAAI,GAAG,IAAI,IAAI,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;IAC1D,OAAO,QAAQ,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AACjE,CAAC"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The input and the output of the procedures of this package.
|
|
3
|
+
*/
|
|
4
|
+
import * as z from "zod";
|
|
5
|
+
import type { OcrText } from "./text.js";
|
|
6
|
+
/** How `ocr.page` gets the text: `auto` uses OCR only for a page with no text layer. */
|
|
7
|
+
export type OcrPageMode = "auto" | "text" | "ocr";
|
|
8
|
+
/** The input of `ocr.page`. */
|
|
9
|
+
export interface OcrPageInput {
|
|
10
|
+
file: string;
|
|
11
|
+
page?: number | undefined;
|
|
12
|
+
mode?: OcrPageMode | undefined;
|
|
13
|
+
language?: string | undefined;
|
|
14
|
+
psm?: number | undefined;
|
|
15
|
+
dpi?: number | undefined;
|
|
16
|
+
timeout?: number | undefined;
|
|
17
|
+
}
|
|
18
|
+
export declare const OcrPageInputSchema: z.ZodType<OcrPageInput>;
|
|
19
|
+
/** The output of `ocr.page`. The boxes are in PDF points. */
|
|
20
|
+
export interface OcrPageOutput extends OcrText {
|
|
21
|
+
/** The number of the page. */
|
|
22
|
+
readonly page: number;
|
|
23
|
+
/** Where the text comes from: the text layer of the page, or OCR of an image of the page. */
|
|
24
|
+
readonly source: "text-layer" | "ocr";
|
|
25
|
+
/** The OCR engine, when the source is `ocr`. */
|
|
26
|
+
readonly engine?: string | undefined;
|
|
27
|
+
}
|
|
28
|
+
export declare const OcrPageOutputSchema: z.ZodType<OcrPageOutput>;
|
|
29
|
+
/** The input of `ocr.image`. */
|
|
30
|
+
export interface OcrImageInput {
|
|
31
|
+
file: string;
|
|
32
|
+
language?: string | undefined;
|
|
33
|
+
psm?: number | undefined;
|
|
34
|
+
dpi?: number | undefined;
|
|
35
|
+
timeout?: number | undefined;
|
|
36
|
+
}
|
|
37
|
+
export declare const OcrImageInputSchema: z.ZodType<OcrImageInput>;
|
|
38
|
+
/** The output of `ocr.image`. The boxes are in the pixels of the image. */
|
|
39
|
+
export interface OcrImageOutput extends OcrText {
|
|
40
|
+
/** The OCR engine. */
|
|
41
|
+
readonly engine: string;
|
|
42
|
+
}
|
|
43
|
+
export declare const OcrImageOutputSchema: z.ZodType<OcrImageOutput>;
|
|
44
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;AAEzB,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AA6CzC,wFAAwF;AACxF,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,MAAM,GAAG,KAAK,CAAC;AAElD,+BAA+B;AAC/B,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,IAAI,CAAC,EAAE,WAAW,GAAG,SAA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|
+
* The input and the output of the procedures of this package.
|
|
3
|
+
*/
|
|
4
|
+
import * as z from "zod";
|
|
5
|
+
import { LANGUAGE_PATTERN } from "./engine.js";
|
|
6
|
+
// =============================================================================
|
|
7
|
+
// The shared parts
|
|
8
|
+
// =============================================================================
|
|
9
|
+
const BoxSchema = z.object({
|
|
10
|
+
x: z.number().describe("The left side of the box"),
|
|
11
|
+
y: z.number().describe("The top side of the box (the y axis points down)"),
|
|
12
|
+
w: z.number().describe("The width of the box"),
|
|
13
|
+
h: z.number().describe("The height of the box"),
|
|
14
|
+
});
|
|
15
|
+
const WordSchema = z.object({
|
|
16
|
+
text: z.string().describe("The text of the word"),
|
|
17
|
+
confidence: z.number().min(0).max(1).describe("The confidence, from 0 to 1"),
|
|
18
|
+
box: BoxSchema,
|
|
19
|
+
});
|
|
20
|
+
const LineSchema = z.object({
|
|
21
|
+
text: z.string().describe("The words of the line, with one space between each two words"),
|
|
22
|
+
confidence: z.number().min(0).max(1).describe("The mean confidence of the words, from 0 to 1"),
|
|
23
|
+
box: BoxSchema,
|
|
24
|
+
words: z.array(WordSchema),
|
|
25
|
+
});
|
|
26
|
+
const textFields = {
|
|
27
|
+
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"),
|
|
28
|
+
width: z.number().describe("The width of the page or of the image"),
|
|
29
|
+
height: z.number().describe("The height of the page or of the image"),
|
|
30
|
+
text: z.string().describe("The text of the lines, with one line end between each two lines"),
|
|
31
|
+
confidence: z.number().min(0).max(1).describe("The mean confidence of all words, from 0 to 1"),
|
|
32
|
+
lines: z.array(LineSchema),
|
|
33
|
+
};
|
|
34
|
+
const engineFields = {
|
|
35
|
+
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)"),
|
|
36
|
+
psm: z.number().int().min(0).max(13).optional().describe("The page segmentation mode of tesseract, from 0 to 13"),
|
|
37
|
+
timeout: z.number().int().positive().optional().describe("The time limit of each program, in milliseconds (default: 120000)"),
|
|
38
|
+
};
|
|
39
|
+
export const OcrPageInputSchema = z.object({
|
|
40
|
+
file: z.string().min(1).describe("The path of the PDF file"),
|
|
41
|
+
page: z.number().int().min(1).optional().describe("The number of the page, from 1 (default: 1)"),
|
|
42
|
+
mode: z
|
|
43
|
+
.enum(["auto", "text", "ocr"])
|
|
44
|
+
.optional()
|
|
45
|
+
.describe("auto: the text layer, else OCR. text: only the text layer. ocr: always OCR (default: auto)"),
|
|
46
|
+
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)"),
|
|
47
|
+
...engineFields,
|
|
48
|
+
});
|
|
49
|
+
export const OcrPageOutputSchema = z.object({
|
|
50
|
+
page: z.number().describe("The number of the page"),
|
|
51
|
+
source: z.enum(["text-layer", "ocr"]).describe("Where the text comes from: the text layer, or OCR of an image of the page"),
|
|
52
|
+
engine: z.string().optional().describe("The OCR engine, when the source is ocr"),
|
|
53
|
+
...textFields,
|
|
54
|
+
});
|
|
55
|
+
export const OcrImageInputSchema = z.object({
|
|
56
|
+
file: z.string().min(1).describe("The path of the image file, for example a PNG, JPEG or TIFF file"),
|
|
57
|
+
dpi: z.number().int().min(1).max(4800).optional().describe("The resolution of the image, when the file does not tell it"),
|
|
58
|
+
...engineFields,
|
|
59
|
+
});
|
|
60
|
+
export const OcrImageOutputSchema = z.object({
|
|
61
|
+
engine: z.string().describe("The OCR engine"),
|
|
62
|
+
...textFields,
|
|
63
|
+
});
|
|
64
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;AACzB,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAG/C,gFAAgF;AAChF,mBAAmB;AACnB,gFAAgF;AAEhF,MAAM,SAAS,GA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@@ -1,13 +1,95 @@
|
|
|
1
1
|
{
|
|
2
|
+
"$schema": "https://json.schemastore.org/package",
|
|
2
3
|
"name": "@procedures/ocr",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
4
|
+
"version": "0.68.6",
|
|
5
|
+
"description": "The text of a PDF page or an image, with the text, the confidence and the box of each line and word: the text layer of the page first (pdftotext), then OCR with a local engine (tesseract).",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"ocr",
|
|
8
|
+
"tesseract",
|
|
9
|
+
"pdftotext",
|
|
10
|
+
"poppler",
|
|
11
|
+
"pdf",
|
|
12
|
+
"text",
|
|
13
|
+
"procedures"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://mark1russell7.github.io/client/",
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://github.com/mark1russell7/client/issues"
|
|
18
|
+
},
|
|
5
19
|
"repository": {
|
|
6
20
|
"type": "git",
|
|
7
|
-
"url": "git+https://github.com/mark1russell7/client.git"
|
|
21
|
+
"url": "git+https://github.com/mark1russell7/client.git",
|
|
22
|
+
"directory": "packages/ocr"
|
|
8
23
|
},
|
|
9
24
|
"license": "MIT",
|
|
25
|
+
"author": "Mark Russell (https://github.com/mark1russell7)",
|
|
26
|
+
"type": "module",
|
|
27
|
+
"main": "./dist/index.js",
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"import": "./dist/index.js",
|
|
33
|
+
"default": "./dist/index.js"
|
|
34
|
+
},
|
|
35
|
+
"./module": {
|
|
36
|
+
"types": "./dist/module.d.ts",
|
|
37
|
+
"import": "./dist/module.js",
|
|
38
|
+
"default": "./dist/module.js"
|
|
39
|
+
},
|
|
40
|
+
"./register": {
|
|
41
|
+
"types": "./dist/register.d.ts",
|
|
42
|
+
"import": "./dist/register.js",
|
|
43
|
+
"default": "./dist/register.js"
|
|
44
|
+
},
|
|
45
|
+
"./parse": {
|
|
46
|
+
"types": "./dist/parse.d.ts",
|
|
47
|
+
"import": "./dist/parse.js",
|
|
48
|
+
"default": "./dist/parse.js"
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
"files": [
|
|
52
|
+
"dist",
|
|
53
|
+
"!dist/.tsbuildinfo",
|
|
54
|
+
"src",
|
|
55
|
+
"!src/**/*.test.ts",
|
|
56
|
+
"!src/**/*.test.tsx",
|
|
57
|
+
"!src/**/__tests__",
|
|
58
|
+
"CHANGELOG.md"
|
|
59
|
+
],
|
|
60
|
+
"sideEffects": [
|
|
61
|
+
"./dist/register.js"
|
|
62
|
+
],
|
|
10
63
|
"publishConfig": {
|
|
11
|
-
"access": "public"
|
|
64
|
+
"access": "public",
|
|
65
|
+
"provenance": true
|
|
66
|
+
},
|
|
67
|
+
"devDependencies": {
|
|
68
|
+
"typescript": "^7.0.2",
|
|
69
|
+
"@types/node": "^22.0.0",
|
|
70
|
+
"@mark1russell7/cue": "^2.1.0",
|
|
71
|
+
"vitest": "^5.0.3"
|
|
72
|
+
},
|
|
73
|
+
"engines": {
|
|
74
|
+
"node": ">=22"
|
|
75
|
+
},
|
|
76
|
+
"client": {
|
|
77
|
+
"procedures": "./dist/register.js",
|
|
78
|
+
"browser": [
|
|
79
|
+
"./parse"
|
|
80
|
+
]
|
|
81
|
+
},
|
|
82
|
+
"dependencies": {
|
|
83
|
+
"@mark1russell7/layout-contract": "^0.11.1",
|
|
84
|
+
"@procedures/client": "0.68.6",
|
|
85
|
+
"@procedures/shell": "0.68.6",
|
|
86
|
+
"zod": "^4.6.5"
|
|
87
|
+
},
|
|
88
|
+
"scripts": {
|
|
89
|
+
"build": "tsc -b",
|
|
90
|
+
"typecheck": "tsc --noEmit && tsc -p tsconfig.test.json",
|
|
91
|
+
"clean": "rm -rf dist .tsbuildinfo",
|
|
92
|
+
"test": "vitest run",
|
|
93
|
+
"test:watch": "vitest"
|
|
12
94
|
}
|
|
13
|
-
}
|
|
95
|
+
}
|
package/src/bbox.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The parse of the text layer of a PDF page, in the XHTML output of `pdftotext -bbox-layout` of
|
|
3
|
+
* Poppler. This file starts no process and reads no file.
|
|
4
|
+
*
|
|
5
|
+
* The output has a `page` element with the size of the page, then `flow`, `block`, `line` and
|
|
6
|
+
* `word` elements. Each `line` and each `word` has its box as `xMin`, `yMin`, `xMax` and `yMax`, in
|
|
7
|
+
* PDF points from the top-left corner of the page.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { makeLine, makeText, type OcrLine, type OcrText, type OcrWord, type Rect } from "./text.js";
|
|
11
|
+
|
|
12
|
+
const ENTITIES: Readonly<Record<string, string>> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
|
|
13
|
+
|
|
14
|
+
/** This function decodes the entities of an XML text: the five named entities and the number entities. */
|
|
15
|
+
export function decodeXmlText(text: string): string {
|
|
16
|
+
return text.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-z]+);/g, (entity: string, name: string) => {
|
|
17
|
+
if (name.startsWith("#x")) return safeCodePoint(Number.parseInt(name.slice(2), 16), entity);
|
|
18
|
+
if (name.startsWith("#")) return safeCodePoint(Number.parseInt(name.slice(1), 10), entity);
|
|
19
|
+
return ENTITIES[name] ?? entity;
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function safeCodePoint(code: number, entity: string): string {
|
|
24
|
+
return code >= 0 && code <= 0x10ffff ? String.fromCodePoint(code) : entity;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* This function gives the attributes of the start tag of an element, by name. Each attribute starts
|
|
29
|
+
* after a white space, so a match starts only at a white space. Thus the time is linear in the
|
|
30
|
+
* length of the tag, also for a long run of name characters with no `=`.
|
|
31
|
+
*/
|
|
32
|
+
function attributes(tag: string): Map<string, string> {
|
|
33
|
+
const result = new Map<string, string>();
|
|
34
|
+
for (const match of tag.matchAll(/\s([A-Za-z_:][\w:.-]*)="([^"]*)"/g)) result.set(match[1]!, match[2]!);
|
|
35
|
+
return result;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** This function gives the box of an element from its `xMin`, `yMin`, `xMax` and `yMax`, or undefined. */
|
|
39
|
+
function boxOf(tag: string): Rect | undefined {
|
|
40
|
+
const values = attributes(tag);
|
|
41
|
+
const [xMin, yMin, xMax, yMax] = ["xMin", "yMin", "xMax", "yMax"].map((name) => Number(values.get(name)));
|
|
42
|
+
if (![xMin, yMin, xMax, yMax].every((value) => Number.isFinite(value))) return undefined;
|
|
43
|
+
return { x: xMin!, y: yMin!, w: Math.max(0, xMax! - xMin!), h: Math.max(0, yMax! - yMin!) };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* This function parses the output of `pdftotext -bbox-layout` for one page. Each word of the text
|
|
48
|
+
* layer has the confidence 1. The boxes are in PDF points.
|
|
49
|
+
*
|
|
50
|
+
* - The function reads the first `page` element. Give the output of one page (`-f N -l N`).
|
|
51
|
+
* - A word with no text, or with no valid box, is not in the result. A line with no word is not in the result.
|
|
52
|
+
* - A page with no text layer gives no line, and the size of the page.
|
|
53
|
+
*
|
|
54
|
+
* It throws when the output has no `page` element.
|
|
55
|
+
*/
|
|
56
|
+
export function parsePdftotextBbox(xhtml: string): OcrText {
|
|
57
|
+
const pageStart = /<page\b[^>]*>/.exec(xhtml);
|
|
58
|
+
if (pageStart === null) throw new Error("The output of pdftotext -bbox-layout has no page element");
|
|
59
|
+
const size = attributes(pageStart[0]);
|
|
60
|
+
const width = Number(size.get("width"));
|
|
61
|
+
const height = Number(size.get("height"));
|
|
62
|
+
const pageEnd = xhtml.indexOf("</page>", pageStart.index);
|
|
63
|
+
const body = xhtml.slice(pageStart.index + pageStart[0].length, pageEnd === -1 ? undefined : pageEnd);
|
|
64
|
+
|
|
65
|
+
const lines: OcrLine[] = [];
|
|
66
|
+
for (const line of body.matchAll(/<line\b([^>]*)>([\s\S]*?)<\/line>/g)) {
|
|
67
|
+
const words: OcrWord[] = [];
|
|
68
|
+
for (const word of line[2]!.matchAll(/<word\b([^>]*)>([\s\S]*?)<\/word>/g)) {
|
|
69
|
+
const text = decodeXmlText(word[2]!).trim();
|
|
70
|
+
const box = boxOf(word[1]!);
|
|
71
|
+
if (text.length > 0 && box !== undefined) words.push({ text, confidence: 1, box });
|
|
72
|
+
}
|
|
73
|
+
if (words.length > 0) lines.push(makeLine(words, boxOf(line[1]!)));
|
|
74
|
+
}
|
|
75
|
+
return makeText(lines, "pt", Number.isFinite(width) ? width : 0, Number.isFinite(height) ? height : 0);
|
|
76
|
+
}
|
package/src/engine.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The adapter of an OCR engine: the program, the argv for one image and the parse of the output.
|
|
3
|
+
* The adapter starts no process: the procedures start the program through `shell.run`. Tesseract
|
|
4
|
+
* is the first engine. Another engine is one more adapter.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { TESSERACT, type ProgramSpec } from "./programs.js";
|
|
8
|
+
import type { OcrText } from "./text.js";
|
|
9
|
+
import { parseTesseractTsv } from "./tsv.js";
|
|
10
|
+
|
|
11
|
+
/** The options of one recognition. */
|
|
12
|
+
export interface OcrEngineOptions {
|
|
13
|
+
/** The language of the text, for example `eng`, or `eng+deu` for two languages (default: `eng`). */
|
|
14
|
+
readonly language?: string | undefined;
|
|
15
|
+
/** The page segmentation mode of the engine. For tesseract, a value from 0 to 13. */
|
|
16
|
+
readonly psm?: number | undefined;
|
|
17
|
+
/** The resolution of the image, in dots per inch, when the image file does not tell it. */
|
|
18
|
+
readonly dpi?: number | undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** An OCR engine. */
|
|
22
|
+
export interface OcrEngine {
|
|
23
|
+
/** The name of the engine in the result, for example `tesseract`. */
|
|
24
|
+
readonly name: string;
|
|
25
|
+
/** The program of the engine, for the search on the host. */
|
|
26
|
+
readonly program: ProgramSpec;
|
|
27
|
+
/** This function gives the argv of the program for one image. `image` is an absolute path. */
|
|
28
|
+
argv(image: string, options: OcrEngineOptions): string[];
|
|
29
|
+
/** This function parses the standard output of the program. The boxes are in the pixels of the image. */
|
|
30
|
+
parse(stdout: string): OcrText;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The default language of the recognition. */
|
|
34
|
+
export const DEFAULT_LANGUAGE = "eng";
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The form of a language value: names of letters, digits, `_` and `/` (for example `script/Latin`),
|
|
38
|
+
* joined with `+`. A value cannot start with `-`, so the program cannot read it as a flag.
|
|
39
|
+
*/
|
|
40
|
+
export const LANGUAGE_PATTERN: RegExp = /^[A-Za-z0-9_][A-Za-z0-9_/]*(\+[A-Za-z0-9_][A-Za-z0-9_/]*)*$/;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The adapter of tesseract 4 or later. The argv is `<image> stdout -l <language> [--psm N]
|
|
44
|
+
* [--dpi N] tsv`: tesseract writes the TSV of the image to the standard output.
|
|
45
|
+
*/
|
|
46
|
+
export const tesseractEngine: OcrEngine = {
|
|
47
|
+
name: "tesseract",
|
|
48
|
+
program: TESSERACT,
|
|
49
|
+
argv(image, options) {
|
|
50
|
+
const language = options.language ?? DEFAULT_LANGUAGE;
|
|
51
|
+
if (!LANGUAGE_PATTERN.test(language)) throw new Error(`The language ${JSON.stringify(language)} is not a valid language name of tesseract`);
|
|
52
|
+
const argv = [image, "stdout", "-l", language];
|
|
53
|
+
if (options.psm !== undefined) argv.push("--psm", String(options.psm));
|
|
54
|
+
if (options.dpi !== undefined) argv.push("--dpi", String(options.dpi));
|
|
55
|
+
argv.push("tsv");
|
|
56
|
+
return argv;
|
|
57
|
+
},
|
|
58
|
+
parse: parseTesseractTsv,
|
|
59
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// The root registers nothing: import "<package>/register", or give the module to createRegistry()
|
|
2
|
+
export * from "./module.js";
|
|
3
|
+
export * from "./types.js";
|
|
4
|
+
// The records and the parsers, with no process (also on the browser entry ./parse)
|
|
5
|
+
export * from "./parse.js";
|
|
6
|
+
// The adapter of an OCR engine, the search for the programs and the run through shell.run
|
|
7
|
+
export * from "./engine.js";
|
|
8
|
+
export * from "./programs.js";
|
|
9
|
+
export { createOcrRunner, DEFAULT_TIMEOUT_MS, type OcrHostOptions, type OcrRunner } from "./run.js";
|
|
10
|
+
export { DEFAULT_DPI, ocrImage, ocrPage, pdftoppmArgs, pdftotextArgs } from "./procedures/ocr/index.js";
|
package/src/module.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The procedures of @procedures/ocr as data. An import of this file registers nothing. The module
|
|
3
|
+
* of `@procedures/shell` is necessary for this module: each procedure starts its programs through
|
|
4
|
+
* `shell.run`.
|
|
5
|
+
*
|
|
6
|
+
* Scaffold a procedure with: mark procedure new <name> --path packages/ocr
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
createProcedure,
|
|
11
|
+
defineModule,
|
|
12
|
+
definePackage,
|
|
13
|
+
type AnyProcedure,
|
|
14
|
+
type Effects,
|
|
15
|
+
type FsRootRules,
|
|
16
|
+
type PackageDefinition,
|
|
17
|
+
type ProcedureContext,
|
|
18
|
+
type ProcedureModule,
|
|
19
|
+
} from "@procedures/client";
|
|
20
|
+
import shellModule from "@procedures/shell/module";
|
|
21
|
+
import { ocrImage } from "./procedures/ocr/image.js";
|
|
22
|
+
import { ocrPage } from "./procedures/ocr/page.js";
|
|
23
|
+
import { createOcrRunner, type OcrHostOptions } from "./run.js";
|
|
24
|
+
import { OcrImageInputSchema, OcrImageOutputSchema, OcrPageInputSchema, OcrPageOutputSchema, type OcrImageInput, type OcrImageOutput, type OcrPageInput, type OcrPageOutput } from "./types.js";
|
|
25
|
+
|
|
26
|
+
/** The rule of the procedures under a root of the files: the file of the input is in the root. */
|
|
27
|
+
const FILE_IN_A_ROOT: FsRootRules = { paths: ["file"] };
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The effects of `ocr.page`. The programs read the PDF file. `pdftoppm` writes an image to a new
|
|
31
|
+
* temporary folder, and the procedure removes the folder. `shell.run` reads and writes "process".
|
|
32
|
+
*/
|
|
33
|
+
const PAGE_EFFECTS: Effects = { reads: ["fs", "process"], writes: ["fs", "process"] };
|
|
34
|
+
|
|
35
|
+
/** The effects of `ocr.image`. The engine reads the image file and writes only to its standard output. */
|
|
36
|
+
const IMAGE_EFFECTS: Effects = { reads: ["fs", "process"], writes: ["process"] };
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* This function gives the procedures of this package with the settings of the host. The settings
|
|
40
|
+
* are the path of each program, the OCR engine and the folder of the temporary folders.
|
|
41
|
+
*/
|
|
42
|
+
export function createOcrProcedures(options: OcrHostOptions = {}): AnyProcedure[] {
|
|
43
|
+
const runner = createOcrRunner(options);
|
|
44
|
+
const page: AnyProcedure = createProcedure()
|
|
45
|
+
.path(["ocr", "page"])
|
|
46
|
+
.input(OcrPageInputSchema)
|
|
47
|
+
.output(OcrPageOutputSchema)
|
|
48
|
+
.meta({
|
|
49
|
+
description: "Give the text of a PDF page with the box of each line and word: the text layer first, then OCR for a page with no text layer",
|
|
50
|
+
args: ["file"],
|
|
51
|
+
shorts: { page: "p", language: "l", mode: "m", timeout: "t" },
|
|
52
|
+
output: "json",
|
|
53
|
+
calls: ["shell.run"],
|
|
54
|
+
effects: PAGE_EFFECTS,
|
|
55
|
+
fsRoot: FILE_IN_A_ROOT,
|
|
56
|
+
})
|
|
57
|
+
.handler(async (input: OcrPageInput, ctx: ProcedureContext): Promise<OcrPageOutput> => ocrPage(input, ctx, runner))
|
|
58
|
+
.build();
|
|
59
|
+
const image: AnyProcedure = createProcedure()
|
|
60
|
+
.path(["ocr", "image"])
|
|
61
|
+
.input(OcrImageInputSchema)
|
|
62
|
+
.output(OcrImageOutputSchema)
|
|
63
|
+
.meta({
|
|
64
|
+
description: "Read the text of an image with a local OCR engine (tesseract), with the confidence and the box of each line and word",
|
|
65
|
+
args: ["file"],
|
|
66
|
+
shorts: { language: "l", timeout: "t" },
|
|
67
|
+
output: "json",
|
|
68
|
+
calls: ["shell.run"],
|
|
69
|
+
effects: IMAGE_EFFECTS,
|
|
70
|
+
fsRoot: FILE_IN_A_ROOT,
|
|
71
|
+
})
|
|
72
|
+
.handler(async (input: OcrImageInput, ctx: ProcedureContext): Promise<OcrImageOutput> => ocrImage(input, ctx, runner))
|
|
73
|
+
.build();
|
|
74
|
+
return [page, image];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The procedures with the default settings: the search finds each program at each call. */
|
|
78
|
+
export const ocrProcedures: AnyProcedure[] = createOcrProcedures();
|
|
79
|
+
|
|
80
|
+
const ocrPackage: PackageDefinition = definePackage("@procedures/ocr", ocrProcedures, [shellModule]);
|
|
81
|
+
|
|
82
|
+
export const ocrModule: ProcedureModule = ocrPackage.module;
|
|
83
|
+
|
|
84
|
+
export default ocrModule;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* This function gives the module with the settings of the host. Without options, it gives
|
|
88
|
+
* `ocrModule`.
|
|
89
|
+
*
|
|
90
|
+
* ```ts
|
|
91
|
+
* createRegistry(createOcrModule({ executables: { tesseract: "/opt/tesseract/bin/tesseract" } }));
|
|
92
|
+
* ```
|
|
93
|
+
*/
|
|
94
|
+
export function createOcrModule(options: OcrHostOptions = {}): ProcedureModule {
|
|
95
|
+
if (Object.values(options).every((value) => value === undefined)) return ocrModule;
|
|
96
|
+
return defineModule("@procedures/ocr", createOcrProcedures(options), [shellModule]);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* This function registers the procedures of @procedures/ocr in a registry. The default is the
|
|
101
|
+
* global registry.
|
|
102
|
+
*/
|
|
103
|
+
export const registerOcrProcedures: PackageDefinition["register"] = ocrPackage.register;
|
package/src/parse.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The entry `@procedures/ocr/parse`: the records and the parsers of this package. It starts no
|
|
3
|
+
* process, reads no file and imports no Node module, so a browser can also load it.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export * from "./text.js";
|
|
7
|
+
export * from "./tsv.js";
|
|
8
|
+
export * from "./bbox.js";
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ocr.image procedure
|
|
3
|
+
*
|
|
4
|
+
* This procedure reads the text of an image with the OCR engine of the host (tesseract first).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { resolve } from "node:path";
|
|
8
|
+
import type { ProcedureContext } from "@procedures/client";
|
|
9
|
+
import { createOcrRunner, DEFAULT_TIMEOUT_MS, type OcrRunner } from "../../run.js";
|
|
10
|
+
import type { OcrImageInput, OcrImageOutput } from "../../types.js";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* This function reads the text of the image file of the input. It gives each line and each word
|
|
14
|
+
* with its text, its confidence and its box, in the pixels of the image.
|
|
15
|
+
*/
|
|
16
|
+
export async function ocrImage(input: OcrImageInput, ctx: Pick<ProcedureContext, "client">, runner: OcrRunner = createOcrRunner()): Promise<OcrImageOutput> {
|
|
17
|
+
const { engine } = runner;
|
|
18
|
+
// An absolute path does not start with "-", so the engine cannot read it as a flag
|
|
19
|
+
const argv = engine.argv(resolve(input.file), { language: input.language, psm: input.psm, dpi: input.dpi });
|
|
20
|
+
const stdout = await runner.run(engine.program, argv, input.timeout ?? DEFAULT_TIMEOUT_MS, ctx);
|
|
21
|
+
return { engine: engine.name, ...engine.parse(stdout) };
|
|
22
|
+
}
|