Compare commits

...

19 Commits

Author SHA1 Message Date
Balearica d5c1f78b94 Fixed bug with saving images per #588 2 years ago
Balearica c7c2d73d58 Added debug output option per #681 2 years ago
Balearica 9e12163514 Updated setImage to resolve memory leak per #678 2 years ago
Balearica 32c5c14e53 Fixed unit tests 2 years ago
Balearica 2a6a13305a Wrapped caching in try block per #609 2 years ago
Balearica b952488952 Added interface for setting 'init only' options per #613 2 years ago
Balearica c0298ff1fa Edited loadLanguage to no longer overwrite cache with data from cache per #666 2 years ago
Balearica c41619f680 Updated docs 2 years ago
Balearica fae195f2ae Allowed for Tesseract parameters to be set through recognition options per #665 2 years ago
Balearica c407aeb559 Added OutputFormats option/interface for setting output 2 years ago
Balearica 81bf04c678 Updated download-pdf example for node to use new savePDF option 2 years ago
Balearica 622c841f33 Added savePDF option to recognize per #488; cleaned up code for linter 2 years ago
Balearica 689a15055f Removed unused files 2 years ago
Balearica 4d3dee59b4
Updated types per #606 and #580 (#663) (#664) 2 years ago
Balearica 8fb04f4593 Edited detect to return null when detection fails rather than throwing error per #526 2 years ago
Balearica ca99c35d14 Reworked createWorker to be async and throw errors per #654 2 years ago
Balearica b87afe9d93 Reworked createWorker to be async and throw errors per #654 2 years ago
Balearica 0277db26b1 Updated createWorker to be async 2 years ago
Balearica 3678dbceae Added image preprocessing functions (rotate + save images) 2 years ago
  1. 3
      README.md
  2. 44
      docs/api.md
  3. 41
      docs/examples.md
  4. 40
      docs/faq.md
  5. 4
      docs/local-installation.md
  6. 16
      examples/browser/basic-edge.html
  7. 1
      examples/browser/basic.html
  8. 3
      examples/browser/benchmark.html
  9. 14
      examples/browser/download-pdf.html
  10. 59
      examples/browser/image-processing.html
  11. 4
      examples/node/benchmark.js
  12. 8
      examples/node/download-pdf.js
  13. 7
      examples/node/recognize.js
  14. 26
      examples/node/scheduler.js
  15. 2909
      package-lock.json
  16. 4
      package.json
  17. 6
      src/Tesseract.js
  18. 5
      src/constants/imageType.js
  19. 42
      src/createWorker.js
  20. 61
      src/index.d.ts
  21. 2
      src/utils/circularize.js
  22. 17
      src/worker-script/constants/defaultOutput.js
  23. 209
      src/worker-script/index.js
  24. 56
      src/worker-script/utils/arrayBufferToBase64.js
  25. 51
      src/worker-script/utils/dump.js
  26. 61
      src/worker-script/utils/setImage.js
  27. 6
      tests/FS.test.js
  28. 18
      tests/detect.test.js
  29. 17
      tests/recognize.test.js
  30. 3
      tests/scheduler.test.js

3
README.md

@ -46,12 +46,11 @@ Or more imperative @@ -46,12 +46,11 @@ Or more imperative
```javascript
import { createWorker } from 'tesseract.js';
const worker = createWorker({
const worker = await createWorker({
logger: m => console.log(m)
});
(async () => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const { data: { text } } = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png');

44
docs/api.md

@ -1,7 +1,6 @@ @@ -1,7 +1,6 @@
# API
- [createWorker()](#create-worker)
- [Worker.load](#worker-load)
- [Worker.writeText](#worker-writeText)
- [Worker.readText](#worker-readText)
- [Worker.removeFile](#worker-removeFile)
@ -53,7 +52,7 @@ createWorker is a factory function that creates a tesseract worker, a worker is @@ -53,7 +52,7 @@ createWorker is a factory function that creates a tesseract worker, a worker is
```javascript
const { createWorker } = Tesseract;
const worker = createWorker({
const worker = await createWorker({
langPath: '...',
logger: m => console.log(m),
});
@ -63,7 +62,6 @@ const worker = createWorker({ @@ -63,7 +62,6 @@ const worker = createWorker({
A Worker helps you to do the OCR related tasks, it takes few steps to setup Worker before it is fully functional. The full flow is:
- load
- FS functions // optional
- loadLanguauge
- initialize
@ -82,23 +80,6 @@ Each function is async, so using async/await or Promise is required. When it is @@ -82,23 +80,6 @@ Each function is async, so using async/await or Promise is required. When it is
jobId is generated by Tesseract.js, but you can put your own when calling any of the function above.
<a name="worker-load"></a>
### Worker.load(jobId): Promise
Worker.load() loads tesseract.js-core scripts (download from remote if not presented), it makes Web Worker/Child Process ready for next action.
**Arguments:**
- `jobId` Please see details above
**Examples:**
```javascript
(async () => {
await worker.load();
})();
```
<a name="worker-writeText"></a>
### Worker.writeText(path, text, jobId): Promise
@ -225,7 +206,7 @@ Worker.setParameters() set parameters for Tesseract API (using SetVariable()), i @@ -225,7 +206,7 @@ Worker.setParameters() set parameters for Tesseract API (using SetVariable()), i
- `params` an object with key and value of the parameters
- `jobId` Please see details above
**Supported Paramters:**
**Useful Paramters:**
| name | type | default value | description |
| --------------------------- | ------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------- |
@ -234,11 +215,8 @@ Worker.setParameters() set parameters for Tesseract API (using SetVariable()), i @@ -234,11 +215,8 @@ Worker.setParameters() set parameters for Tesseract API (using SetVariable()), i
| tessedit\_char\_whitelist | string | '' | setting white list characters makes the result only contains these characters, useful the content in image is limited |
| preserve\_interword\_spaces | string | '0' | '0' or '1', keeps the space between words |
| user\_defined\_dpi | string | '' | Define custom dpi, use to fix **Warning: Invalid resolution 0 dpi. Using 70 instead.** |
| tessjs\_create\_hocr | string | '1' | only 2 values, '0' or '1', when the value is '1', tesseract.js includes hocr in the result |
| tessjs\_create\_tsv | string | '1' | only 2 values, '0' or '1', when the value is '1', tesseract.js includes tsv in the result |
| tessjs\_create\_box | string | '0' | only 2 values, '0' or '1', when the value is '1', tesseract.js includes box in the result |
| tessjs\_create\_unlv | string | '0' | only 2 values, '0' or '1', when the value is '1', tesseract.js includes unlv in the result |
| tessjs\_create\_osd | string | '0' | only 2 values, '0' or '1', when the value is '1', tesseract.js includes osd in the result |
This list is incomplete. As Tesseract.js passes parameters to the Tesseract engine, all parameters supported by the underlying version of Tesseract should also be supported by Tesseract.js. (Note that parameters marked as “init only” in Tesseract documentation cannot be set by `setParameters` or `recognize`.)
**Examples:**
@ -262,8 +240,9 @@ Figures out what words are in `image`, where the words are in `image`, etc. @@ -262,8 +240,9 @@ Figures out what words are in `image`, where the words are in `image`, etc.
**Arguments:**
- `image` see [Image Format](./image-format.md) for more details.
- `options` a object of customized options
- `options` an object of customized options
- `rectangle` an object to specify the regions you want to recognized in the image, should contain top, left, width and height, see example below.
- `output` an object specifying which output formats to return (by default `text`, `blocks`, `hocr`, and `tsv` are returned)
- `jobId` Please see details above
**Output:**
@ -273,8 +252,7 @@ Figures out what words are in `image`, where the words are in `image`, etc. @@ -273,8 +252,7 @@ Figures out what words are in `image`, where the words are in `image`, etc.
```javascript
const { createWorker } = Tesseract;
(async () => {
const worker = createWorker();
await worker.load();
const worker = await createWorker();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const { data: { text } } = await worker.recognize(image);
@ -287,8 +265,7 @@ With rectangle @@ -287,8 +265,7 @@ With rectangle
```javascript
const { createWorker } = Tesseract;
(async () => {
const worker = createWorker();
await worker.load();
const worker = await createWorker();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const { data: { text } } = await worker.recognize(image, {
@ -313,8 +290,7 @@ Worker.detect() does OSD (Orientation and Script Detection) to the image instead @@ -313,8 +290,7 @@ Worker.detect() does OSD (Orientation and Script Detection) to the image instead
```javascript
const { createWorker } = Tesseract;
(async () => {
const worker = createWorker();
await worker.load();
const worker = await createWorker();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const { data } = await worker.detect(image);
@ -361,7 +337,7 @@ Scheduler.addWorker() adds a worker into the worker pool inside scheduler, it is @@ -361,7 +337,7 @@ Scheduler.addWorker() adds a worker into the worker pool inside scheduler, it is
```javascript
const { createWorker, createScheduler } = Tesseract;
const scheduler = createScheduler();
const worker = createWorker();
const worker = await createWorker();
scheduler.addWorker(worker);
```

41
docs/examples.md

@ -7,10 +7,9 @@ You can also check [examples](../examples) folder. @@ -7,10 +7,9 @@ You can also check [examples](../examples) folder.
```javascript
const { createWorker } = require('tesseract.js');
const worker = createWorker();
const worker = await createWorker();
(async () => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const { data: { text } } = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png');
@ -24,12 +23,11 @@ const worker = createWorker(); @@ -24,12 +23,11 @@ const worker = createWorker();
```javascript
const { createWorker } = require('tesseract.js');
const worker = createWorker({
const worker = await createWorker({
logger: m => console.log(m), // Add logger here
});
(async () => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const { data: { text } } = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png');
@ -43,10 +41,9 @@ const worker = createWorker({ @@ -43,10 +41,9 @@ const worker = createWorker({
```javascript
const { createWorker } = require('tesseract.js');
const worker = createWorker();
const worker = await createWorker();
(async () => {
await worker.load();
await worker.loadLanguage('eng+chi_tra');
await worker.initialize('eng+chi_tra');
const { data: { text } } = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png');
@ -54,15 +51,14 @@ const worker = createWorker(); @@ -54,15 +51,14 @@ const worker = createWorker();
await worker.terminate();
})();
```
### with whitelist char (^2.0.0-beta.1)
### with whitelist char
```javascript
const { createWorker } = require('tesseract.js');
const worker = createWorker();
const worker = await createWorker();
(async () => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
await worker.setParameters({
@ -74,17 +70,16 @@ const worker = createWorker(); @@ -74,17 +70,16 @@ const worker = createWorker();
})();
```
### with different pageseg mode (^2.0.0-beta.1)
### with different pageseg mode
Check here for more details of pageseg mode: https://github.com/tesseract-ocr/tesseract/blob/4.0.0/src/ccstruct/publictypes.h#L163
```javascript
const { createWorker, PSM } = require('tesseract.js');
const worker = createWorker();
const worker = await createWorker();
(async () => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
await worker.setParameters({
@ -96,7 +91,7 @@ const worker = createWorker(); @@ -96,7 +91,7 @@ const worker = createWorker();
})();
```
### with pdf output (^2.0.0-beta.1)
### with pdf output
Please check **examples** folder for details.
@ -110,11 +105,10 @@ Node: [download-pdf.js](../examples/node/download-pdf.js) @@ -110,11 +105,10 @@ Node: [download-pdf.js](../examples/node/download-pdf.js)
```javascript
const { createWorker } = require('tesseract.js');
const worker = createWorker();
const worker = await createWorker();
const rectangle = { left: 0, top: 0, width: 500, height: 250 };
(async () => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const { data: { text } } = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png', { rectangle });
@ -128,7 +122,7 @@ const rectangle = { left: 0, top: 0, width: 500, height: 250 }; @@ -128,7 +122,7 @@ const rectangle = { left: 0, top: 0, width: 500, height: 250 };
```javascript
const { createWorker } = require('tesseract.js');
const worker = createWorker();
const worker = await createWorker();
const rectangles = [
{
left: 0,
@ -145,7 +139,6 @@ const rectangles = [ @@ -145,7 +139,6 @@ const rectangles = [
];
(async () => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const values = [];
@ -164,8 +157,8 @@ const rectangles = [ @@ -164,8 +157,8 @@ const rectangles = [
const { createWorker, createScheduler } = require('tesseract.js');
const scheduler = createScheduler();
const worker1 = createWorker();
const worker2 = createWorker();
const worker1 = await createWorker();
const worker2 = await createWorker();
const rectangles = [
{
left: 0,
@ -182,8 +175,6 @@ const rectangles = [ @@ -182,8 +175,6 @@ const rectangles = [
];
(async () => {
await worker1.load();
await worker2.load();
await worker1.loadLanguage('eng');
await worker2.loadLanguage('eng');
await worker1.initialize('eng');
@ -198,18 +189,16 @@ const rectangles = [ @@ -198,18 +189,16 @@ const rectangles = [
})();
```
### with multiple workers to speed up (^2.0.0-beta.1)
### with multiple workers to speed up
```javascript
const { createWorker, createScheduler } = require('tesseract.js');
const scheduler = createScheduler();
const worker1 = createWorker();
const worker2 = createWorker();
const worker1 = await createWorker();
const worker2 = await createWorker();
(async () => {
await worker1.load();
await worker2.load();
await worker1.loadLanguage('eng');
await worker2.loadLanguage('eng');
await worker1.initialize('eng');

40
docs/faq.md

@ -1,6 +1,13 @@ @@ -1,6 +1,13 @@
FAQ
===
# Project
## What is the scope of this project?
Tesseract.js is the JavaScript/Webassembly port of the Tesseract OCR engine. We do not edit the underlying Tesseract recognition engine in any way. Therefore, if you encounter bugs caused by the Tesseract engine you may open an issue here for the purposes of raising awareness to other users, but fixing is outside the scope of this repository.
If you encounter a Tesseract bug you would like to see fixed you should confirm the behavior is the same in the [main (CLI) version](https://github.com/tesseract-ocr/tesseract) of Tesseract and then open a Git Issue in that repository.
# Trained Data
## How does tesseract.js download and keep \*.traineddata?
The language model is downloaded by `worker.loadLanguage()` and you need to pass the langs to `worker.initialize()`.
@ -9,34 +16,5 @@ During the downloading of language model, Tesseract.js will first check if \*.tr @@ -9,34 +16,5 @@ During the downloading of language model, Tesseract.js will first check if \*.tr
## How can I train my own \*.traineddata?
For tesseract.js v2, check [TrainingTesseract 4.00](https://tesseract-ocr.github.io/tessdoc/TrainingTesseract-4.00)
For tesseract.js v1, check [Training Tesseract 3.03–3.05](https://tesseract-ocr.github.io/tessdoc/Training-Tesseract-3.03%E2%80%933.05)
## How can I get HOCR, TSV, Box, UNLV, OSD?
Starting from 2.0.0-beta.1, you can get all these information in the final result.
```javascript
import { createWorker } from 'tesseract.js';
const worker = createWorker({
logger: m => console.log(m)
});
(async () => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
await worker.setParameters({
tessedit_create_box: '1',
tessedit_create_unlv: '1',
tessedit_create_osd: '1',
});
const { data: { text, hocr, tsv, box, unlv } } = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png');
console.log(text);
console.log(hocr);
console.log(tsv);
console.log(box);
console.log(unlv);
})();
```
See the documentation from the main [Tesseract project](https://tesseract-ocr.github.io/tessdoc/) for training instructions.

4
docs/local-installation.md

@ -19,7 +19,7 @@ Tesseract.recognize(image, langs, { @@ -19,7 +19,7 @@ Tesseract.recognize(image, langs, {
Or
```javascript
const worker = createWorker({
const worker = await createWorker({
workerPath: 'https://unpkg.com/tesseract.js@v2.0.0/dist/worker.min.js',
langPath: 'https://tessdata.projectnaptha.com/4.0.0',
corePath: 'https://unpkg.com/tesseract.js-core@v2.0.0/tesseract-core.wasm.js',
@ -33,6 +33,6 @@ A string specifying the location of the [worker.js](./dist/worker.min.js) file. @@ -33,6 +33,6 @@ A string specifying the location of the [worker.js](./dist/worker.min.js) file.
A string specifying the location of the tesseract language files, with default value 'https://tessdata.projectnaptha.com/4.0.0'. Language file URLs are calculated according to the formula `langPath + langCode + '.traineddata.gz'`.
### corePath
A string specifying the location of the [tesseract.js-core library](https://github.com/naptha/tesseract.js-core), with default value 'https://unpkg.com/tesseract.js-core@v2.0.0/tesseract-core.wasm.js' (fallback to tesseract-core.asm.js when WebAssembly is not available).
A string specifying the location of the [tesseract.js-core library](https://github.com/naptha/tesseract.js-core), with default value 'https://unpkg.com/tesseract.js-core@v2.0.0/tesseract-core.wasm.js'.
Another WASM option is 'https://unpkg.com/tesseract.js-core@v2.0.0/tesseract-core.js' which is a script that loads 'https://unpkg.com/tesseract.js-core@v2.0.0/tesseract-core.wasm'. But it fails to fetch at this moment.

16
examples/browser/basic-edge.html

@ -6,9 +6,9 @@ @@ -6,9 +6,9 @@
<body>
<input type="file" id="uploader">
<script>
const recognize = function(evt){
const recognize = async function(evt){
const files = evt.target.files;
const worker = Tesseract.createWorker({
const worker = await Tesseract.createWorker({
/*
* As Edge don't support webassembly,
* here we force to use asm.js version.
@ -21,14 +21,12 @@ @@ -21,14 +21,12 @@
*/
cacheMethod: 'none',
});
Promise.resolve()
.then(() => worker.load())
.then(() => worker.loadLanguage('eng'))
.then(() => worker.initialize('eng'))
.then(() => worker.recognize(files[0]))
.then((ret) => {
await worker.loadLanguage('eng');
await worker.initialize('eng');
const ret = await worker.recognize(files[0]);
console.log(ret.data.text);
});
}
const elm = document.getElementById('uploader');
elm.addEventListener('change', recognize);

1
examples/browser/basic.html

@ -8,6 +8,7 @@ @@ -8,6 +8,7 @@
const recognize = async ({ target: { files } }) => {
const { data: { text } } = await Tesseract.recognize(files[0], 'eng', {
corePath: '../../node_modules/tesseract.js-core/tesseract-core.wasm.js',
workerPath: "/dist/worker.dev.js",
logger: m => console.log(m),
});
console.log(text);

3
examples/browser/benchmark.html

@ -7,9 +7,8 @@ @@ -7,9 +7,8 @@
<script>
const { createWorker } = Tesseract;
const worker = createWorker();
const worker = await createWorker();
(async () => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');

14
examples/browser/download-pdf.html

@ -8,27 +8,29 @@ @@ -8,27 +8,29 @@
<button id="download-pdf" disabled="true">Download PDF</button>
</div>
<textarea id="board" readonly rows="8" cols="80">Upload an image file</textarea>
<script>
<script type="module">
const { createWorker } = Tesseract;
const worker = createWorker({
const worker = await createWorker({
corePath: '/node_modules/tesseract.js-core/tesseract-core.wasm.js',
workerPath: "/dist/worker.dev.js",
logger: m => console.log(m),
});
const uploader = document.getElementById('uploader');
const dlBtn = document.getElementById('download-pdf');
let pdf;
const recognize = async ({ target: { files } }) => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const { data: { text } } = await worker.recognize(files[0]);
const res = await worker.recognize(files[0],{pdfTitle: "Example PDF"},{pdf: true});
pdf = res.data.pdf;
const text = res.data.text;
const board = document.getElementById('board');
board.value = text;
dlBtn.disabled = false;
};
const downloadPDF = async () => {
const filename = 'tesseract-ocr-result.pdf';
const { data } = await worker.getPDF('Tesseract OCR Result');
const blob = new Blob([new Uint8Array(data)], { type: 'application/pdf' });
const blob = new Blob([new Uint8Array(pdf)], { type: 'application/pdf' });
if (navigator.msSaveBlob) {
// IE 10+
navigator.msSaveBlob(blob, filename);

59
examples/browser/image-processing.html

@ -0,0 +1,59 @@ @@ -0,0 +1,59 @@
<html>
<head>
<script src="/dist/tesseract.dev.js"></script>
<style>
.column {
float: left;
width: 20%;
padding: 5px;
}
</style>
</head>
<body>
<input type="file" id="uploader">
<div class="row">
<div class="column">
<p>Input Image</p>
<img id="imgInput" style="max-width:500px;">
</div>
<div class="column">
<p>Rotated, Original Color</p>
<img id="imgOriginal" style="max-width:500px;">
</div>
<div class="column">
<p>Rotated, Grey</p>
<img id="imgGrey" style="max-width:500px;">
</div>
<div class="column">
<p>Rotated, Binary</p>
<img id="imgBinary" style="max-width:500px;">
</div>
</div>
<script>
const recognize = async ({ target: { files } }) => {
document.getElementById("imgInput").src = URL.createObjectURL(files[0]);
const worker = await Tesseract.createWorker({
// corePath: '/tesseract-core-simd.wasm.js',
workerPath: "/dist/worker.dev.js"
});
await worker.loadLanguage('eng');
await worker.initialize('eng');
await worker.initialize();
const ret = await worker.recognize(files[0], {rotateAuto: true}, {imageColor: true, imageGrey: true, imageBinary: true});
document.getElementById("imgOriginal").src = ret.data.imageColor;
document.getElementById("imgGrey").src = ret.data.imageGrey;
document.getElementById("imgBinary").src = ret.data.imageBinary;
}
const elm = document.getElementById('uploader');
elm.addEventListener('change', recognize);
</script>
</body>
</html>

4
examples/node/benchmark.js

@ -2,10 +2,8 @@ @@ -2,10 +2,8 @@
const path = require('path');
const { createWorker } = require('../../');
const worker = createWorker();
(async () => {
await worker.load();
const worker = await createWorker();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const fileArr = ["../data/meditations.jpg", "../data/tyger.jpg", "../data/testocr.png"];

8
examples/node/download-pdf.js

@ -9,14 +9,12 @@ const image = path.resolve(__dirname, (imagePath || '../../tests/assets/images/c @@ -9,14 +9,12 @@ const image = path.resolve(__dirname, (imagePath || '../../tests/assets/images/c
console.log(`Recognizing ${image}`);
(async () => {
const worker = createWorker();
await worker.load();
const worker = await createWorker();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const { data: { text } } = await worker.recognize(image);
const { data: { text, pdf } } = await worker.recognize(image, {pdfTitle: "Example PDF"}, {pdf: true});
console.log(text);
const { data } = await worker.getPDF('Tesseract OCR Result');
fs.writeFileSync('tesseract-ocr-result.pdf', Buffer.from(data));
fs.writeFileSync('tesseract-ocr-result.pdf', Buffer.from(pdf));
console.log('Generate PDF: tesseract-ocr-result.pdf');
await worker.terminate();
})();

7
examples/node/recognize.js

@ -6,12 +6,11 @@ const [,, imagePath] = process.argv; @@ -6,12 +6,11 @@ const [,, imagePath] = process.argv;
const image = path.resolve(__dirname, (imagePath || '../../tests/assets/images/cosmic.png'));
console.log(`Recognizing ${image}`);
const worker = createWorker({
logger: m => console.log(m),
});
(async () => {
await worker.load();
const worker = await createWorker({
logger: m => console.log(m),
});
await worker.loadLanguage('eng');
await worker.initialize('eng');
const { data: { text } } = await worker.recognize(image);

26
examples/node/scheduler.js

@ -0,0 +1,26 @@ @@ -0,0 +1,26 @@
const { createWorker, createScheduler } = require('../../');
const scheduler = createScheduler();
// Creates worker and adds to scheduler
const workerGen = async () => {
const worker = createWorker({cachePath: "."});
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
scheduler.addWorker(worker);
}
const workerN = 4;
(async () => {
const resArr = Array(workerN);
for (let i=0; i<workerN; i++) {
resArr[i] = workerGen();
}
await Promise.all(resArr);
/** Add 4 recognition jobs */
const results = await Promise.all(Array(10).fill(0).map(() => (
scheduler.addJob('recognize', 'https://tesseract.projectnaptha.com/img/eng_bw.png').then((x) => console.log(x.data.text))
)))
await scheduler.terminate(); // It also terminates all workers.
})();

2909
package-lock.json generated

File diff suppressed because it is too large Load Diff

4
package.json

@ -47,8 +47,8 @@ @@ -47,8 +47,8 @@
"eslint-plugin-import": "^2.22.1",
"expect.js": "^0.3.1",
"express": "^4.17.1",
"mocha": "^8.1.3",
"mocha-headless-chrome": "^2.0.3",
"mocha": "^10.0.0",
"mocha-headless-chrome": "^4.0.0",
"npm-run-all": "^4.1.5",
"nyc": "^15.1.0",
"rimraf": "^2.7.1",

6
src/Tesseract.js

@ -1,8 +1,7 @@ @@ -1,8 +1,7 @@
const createWorker = require('./createWorker');
const recognize = async (image, langs, options) => {
const worker = createWorker(options);
await worker.load();
const worker = await createWorker(options);
await worker.loadLanguage(langs);
await worker.initialize(langs);
return worker.recognize(image)
@ -12,8 +11,7 @@ const recognize = async (image, langs, options) => { @@ -12,8 +11,7 @@ const recognize = async (image, langs, options) => {
};
const detect = async (image, options) => {
const worker = createWorker(options);
await worker.load();
const worker = await createWorker(options);
await worker.loadLanguage('osd');
await worker.initialize('osd');
return worker.detect(image)

5
src/constants/imageType.js

@ -0,0 +1,5 @@ @@ -0,0 +1,5 @@
module.exports = {
COLOR: 0,
GREY: 1,
BINARY: 2,
};

42
src/createWorker.js

@ -15,7 +15,7 @@ const { @@ -15,7 +15,7 @@ const {
let workerCounter = 0;
module.exports = (_options = {}) => {
module.exports = async (_options = {}) => {
const id = getId('Worker', workerCounter);
const {
logger,
@ -27,7 +27,17 @@ module.exports = (_options = {}) => { @@ -27,7 +27,17 @@ module.exports = (_options = {}) => {
});
const resolves = {};
const rejects = {};
let workerResReject;
let workerResResolve;
const workerRes = new Promise((resolve, reject) => {
workerResResolve = resolve;
workerResReject = reject;
});
const workerError = (event) => { workerResReject(event.message); };
let worker = spawnWorker(options);
worker.onerror = workerError;
workerCounter += 1;
@ -53,7 +63,11 @@ module.exports = (_options = {}) => { @@ -53,7 +63,11 @@ module.exports = (_options = {}) => {
})
);
const load = (jobId) => (
const load = () => (
console.warn('`load` is depreciated and should be removed from code (workers now come pre-loaded)')
);
const loadInternal = (jobId) => (
startJob(createJob({
id: jobId, action: 'load', payload: { options },
}))
@ -99,11 +113,11 @@ module.exports = (_options = {}) => { @@ -99,11 +113,11 @@ module.exports = (_options = {}) => {
}))
);
const initialize = (langs = 'eng', oem = defaultOEM, jobId) => (
const initialize = (langs = 'eng', oem = defaultOEM, config, jobId) => (
startJob(createJob({
id: jobId,
action: 'initialize',
payload: { langs, oem },
payload: { langs, oem, config },
}))
);
@ -115,21 +129,22 @@ module.exports = (_options = {}) => { @@ -115,21 +129,22 @@ module.exports = (_options = {}) => {
}))
);
const recognize = async (image, opts = {}, jobId) => (
const recognize = async (image, opts = {}, output = {blocks: true, text: true, hocr: true, tsv: true}, jobId) => (
startJob(createJob({
id: jobId,
action: 'recognize',
payload: { image: await loadImage(image), options: opts },
payload: { image: await loadImage(image), options: opts, output },
}))
);
const getPDF = (title = 'Tesseract OCR Result', textonly = false, jobId) => (
startJob(createJob({
const getPDF = (title = 'Tesseract OCR Result', textonly = false, jobId) => {
console.log('`getPDF` function is depreciated. `recognize` option `savePDF` should be used instead.');
return startJob(createJob({
id: jobId,
action: 'getPDF',
payload: { title, textonly },
}))
);
}));
};
const detect = async (image, jobId) => (
startJob(createJob({
@ -167,6 +182,7 @@ module.exports = (_options = {}) => { @@ -167,6 +182,7 @@ module.exports = (_options = {}) => {
resolves[action]({ jobId, data: d });
} else if (status === 'reject') {
rejects[action](data);
if (action === 'load') workerResReject(data);
if (errorHandler) {
errorHandler(data);
} else {
@ -177,7 +193,7 @@ module.exports = (_options = {}) => { @@ -177,7 +193,7 @@ module.exports = (_options = {}) => {
}
});
return {
const resolveObj = {
id,
worker,
setResolve,
@ -195,4 +211,8 @@ module.exports = (_options = {}) => { @@ -195,4 +211,8 @@ module.exports = (_options = {}) => {
detect,
terminate,
};
loadInternal().then(() => workerResResolve(resolveObj)).catch(() => {});
return workerRes;
};

61
src/index.d.ts vendored

@ -1,6 +1,6 @@ @@ -1,6 +1,6 @@
declare namespace Tesseract {
function createScheduler(): Scheduler
function createWorker(options?: Partial<WorkerOptions>): Worker
function createWorker(options?: Partial<WorkerOptions>): Promise<Worker>
function setLogging(logging: boolean): void
function recognize(image: ImageLike, langs?: string, options?: Partial<WorkerOptions>): Promise<RecognizeResult>
function detect(image: ImageLike, options?: Partial<WorkerOptions>): any
@ -20,13 +20,23 @@ declare namespace Tesseract { @@ -20,13 +20,23 @@ declare namespace Tesseract {
removeText(path: string, jobId?: string): Promise<ConfigResult>
FS(method: string, args: any[], jobId?: string): Promise<ConfigResult>
loadLanguage(langs?: string, jobId?: string): Promise<ConfigResult>
initialize(langs?: string, oem?: OEM, jobId?: string): Promise<ConfigResult>
initialize(langs?: string, oem?: OEM, config?: string | Partial<InitOptions>, jobId?: string): Promise<ConfigResult>
setParameters(params: Partial<WorkerParams>, jobId?: string): Promise<ConfigResult>
recognize(image: ImageLike, options?: Partial<RecognizeOptions>, jobId?: string): Promise<RecognizeResult>
getImage(type: imageType): string
recognize(image: ImageLike, options?: Partial<RecognizeOptions>, output?: Partial<OutputFormats>, jobId?: string): Promise<RecognizeResult>
detect(image: ImageLike, jobId?: string): Promise<DetectResult>
terminate(jobId?: string): Promise<ConfigResult>
getPDF(title?: string, textonly?: boolean, jobId?: string):Promise<GetPDFResult>
}
interface InitOptions {
load_system_dawg: string
load_freq_dawg: string
load_unambig_dawg: string
load_punc_dawg: string
load_number_dawg: string
load_bigram_dawg: string
}
interface WorkerOptions {
corePath: string
langPath: string
@ -51,8 +61,26 @@ declare namespace Tesseract { @@ -51,8 +61,26 @@ declare namespace Tesseract {
tessjs_create_unlv: string
tessjs_create_osd: string
}
interface OutputFormats {
text: boolean;
blocks: boolean;
hocr: boolean;
tsv: boolean;
box: boolean;
unlv: boolean;
osd: boolean;
pdf: boolean;
imageColor: boolean;
imageGrey: boolean;
imageBinary: boolean;
debug: boolean;
}
interface RecognizeOptions {
rectangle: Rectangle
pdfTitle: string
pdfTextOnly: boolean
rotateAuto: boolean
rotateRadians: number
}
interface ConfigResult {
jobId: string
@ -62,16 +90,20 @@ declare namespace Tesseract { @@ -62,16 +90,20 @@ declare namespace Tesseract {
jobId: string
data: Page
}
interface GetPDFResult {
jobId: string
data: number[]
}
interface DetectResult {
jobId: string
data: DetectData
}
interface DetectData {
tesseract_script_id: number
script: string
script_confidence: number
orientation_degrees: number
orientation_confidence: number
tesseract_script_id: number | null
script: string | null
script_confidence: number | null
orientation_degrees: number | null
orientation_confidence: number | null
}
interface Rectangle {
left: number
@ -99,6 +131,12 @@ declare namespace Tesseract { @@ -99,6 +131,12 @@ declare namespace Tesseract {
SINGLE_CHAR = '10',
SPARSE_TEXT = '11',
SPARSE_TEXT_OSD = '12',
RAW_LINE = '13'
}
const enum imageType {
COLOR = 0,
GREY = 1,
BINARY = 2
}
type ImageLike = string | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement
| CanvasRenderingContext2D | File | Blob | ImageData | Buffer;
@ -197,7 +235,7 @@ declare namespace Tesseract { @@ -197,7 +235,7 @@ declare namespace Tesseract {
page: Page;
}
interface Page {
blocks: Block[];
blocks: Block[] | null;
confidence: number;
lines: Line[];
oem: string;
@ -213,6 +251,11 @@ declare namespace Tesseract { @@ -213,6 +251,11 @@ declare namespace Tesseract {
box: string | null;
unlv: string | null;
sd: string | null;
imageColor: string | null;
imageGrey: string | null;
imageBinary: string | null;
rotateRadians: number | null;
pdf: number[] | null;
}
}

2
src/utils/circularize.js

@ -22,6 +22,7 @@ module.exports = (page) => { @@ -22,6 +22,7 @@ module.exports = (page) => {
const words = [];
const symbols = [];
if (page.blocks) {
page.blocks.forEach((block) => {
block.paragraphs.forEach((paragraph) => {
paragraph.lines.forEach((line) => {
@ -47,6 +48,7 @@ module.exports = (page) => { @@ -47,6 +48,7 @@ module.exports = (page) => {
...block, page,
});
});
}
return {
...page, blocks, paragraphs, lines, words, symbols,

17
src/worker-script/constants/defaultOutput.js

@ -0,0 +1,17 @@ @@ -0,0 +1,17 @@
/*
* default output formats for tesseract.js
*/
module.exports = {
text: true,
blocks: true,
hocr: true,
tsv: true,
box: false,
unlv: false,
osd: false,
pdf: false,
imageColor: false,
imageGrey: false,
imageBinary: false
};

209
src/worker-script/index.js

@ -14,7 +14,10 @@ const dump = require('./utils/dump'); @@ -14,7 +14,10 @@ const dump = require('./utils/dump');
const isWebWorker = require('../utils/getEnvironment')('type') === 'webworker';
const setImage = require('./utils/setImage');
const defaultParams = require('./constants/defaultParams');
const defaultOutput = require('./constants/defaultOutput');
const { log, setLogging } = require('../utils/log');
const imageType = require('../constants/imageType');
const PSM = require('../constants/PSM');
/*
* Tesseract Module returned by TesseractCore.
@ -54,7 +57,7 @@ const load = async ({ workerId, jobId, payload: { options: { corePath, logging } @@ -54,7 +57,7 @@ const load = async ({ workerId, jobId, payload: { options: { corePath, logging }
}
};
const FS = ({ workerId, payload: { method, args } }, res) => {
const FS = async ({ workerId, payload: { method, args } }, res) => {
log(`[${workerId}]: FS.${method} with args ${args}`);
res.resolve(TessModule.FS[method](...args));
};
@ -79,6 +82,7 @@ res) => { @@ -79,6 +82,7 @@ res) => {
? () => Promise.resolve()
: adapter.readCache;
let data = null;
let newData = false;
try {
const _data = await readCache(`${cachePath || '.'}/${lang}.traineddata`);
@ -90,6 +94,7 @@ res) => { @@ -90,6 +94,7 @@ res) => {
throw Error('Not found in cache');
}
} catch (e) {
newData = true;
log(`[${workerId}]: Load ${lang}.traineddata from ${langPath}`);
if (typeof _lang === 'string') {
let path = null;
@ -131,8 +136,13 @@ res) => { @@ -131,8 +136,13 @@ res) => {
TessModule.FS.writeFile(`${dataPath || '.'}/${lang}.traineddata`, data);
}
if (['write', 'refresh', undefined].includes(cacheMethod)) {
if (newData && ['write', 'refresh', undefined].includes(cacheMethod)) {
try {
await adapter.writeCache(`${cachePath || '.'}/${lang}.traineddata`, data);
} catch (err) {
log(`[${workerId}]: Failed to write ${lang}.traineddata to cache due to error:`);
log(err.toString());
}
}
return Promise.resolve(data);
@ -156,7 +166,7 @@ res) => { @@ -156,7 +166,7 @@ res) => {
}
};
const setParameters = ({ payload: { params: _params } }, res) => {
const setParameters = async ({ payload: { params: _params } }, res) => {
Object.keys(_params)
.filter((k) => !k.startsWith('tessjs_'))
.forEach((key) => {
@ -169,9 +179,9 @@ const setParameters = ({ payload: { params: _params } }, res) => { @@ -169,9 +179,9 @@ const setParameters = ({ payload: { params: _params } }, res) => {
}
};
const initialize = ({
const initialize = async ({
workerId,
payload: { langs: _langs, oem },
payload: { langs: _langs, oem, config},
}, res) => {
const langs = (typeof _langs === 'string')
? _langs
@ -184,10 +194,24 @@ const initialize = ({ @@ -184,10 +194,24 @@ const initialize = ({
if (api !== null) {
api.End();
}
let configFile = undefined;
let configStr = undefined;
// config argument may either be config file text, or object with key/value pairs
// In the latter case we convert to config file text here
if (typeof config === "object") {
configStr = JSON.stringify(config).replace(/,/g, "\n").replace(/:/g, " ").replace(/["'{}]/g, "");
} else {
configStr = config;
}
if (typeof configStr === "string") {
configFile = "/config";
TessModule.FS.writeFile(configFile, configStr);
}
api = new TessModule.TessBaseAPI();
api.Init(null, langs, oem);
api.Init(null, langs, oem, configFile);
params = defaultParams;
setParameters({ payload: { params } });
await setParameters({ payload: { params } });
res.progress({
workerId, status: 'initialized api', progress: 1,
});
@ -197,46 +221,167 @@ const initialize = ({ @@ -197,46 +221,167 @@ const initialize = ({
}
};
const recognize = ({ payload: { image, options: { rectangle: rec } } }, res) => {
const getPDFInternal = (title, textonly) => {
const pdfRenderer = new TessModule.TessPDFRenderer('tesseract-ocr', '/', textonly);
pdfRenderer.BeginDocument(title);
pdfRenderer.AddImage(api);
pdfRenderer.EndDocument();
TessModule._free(pdfRenderer);
return TessModule.FS.readFile('/tesseract-ocr.pdf');
};
const getPDF = async ({ payload: { title, textonly } }, res) => {
res.resolve(getPDFInternal(title, textonly));
};
// Combines default output with user-specified options and
// counts (1) total output formats requested and (2) outputs that require OCR
const processOutput = (output) => {
const workingOutput = JSON.parse(JSON.stringify(defaultOutput));
// Output formats were set using `setParameters` in previous versions
// These settings are copied over for compatability
if (params.tessjs_create_box === "1") workingOutput.box = true;
if (params.tessjs_create_hocr === "1") workingOutput.hocr = true;
if (params.tessjs_create_osd === "1") workingOutput.osd = true;
if (params.tessjs_create_tsv === "1") workingOutput.tsv = true;
if (params.tessjs_create_unlv === "1") workingOutput.unlv = true;
const nonRecOutputs = ["imageColor", "imageGrey", "imageBinary"];
let recOutputCount = 0;
for (const prop in output) {
workingOutput[prop] = output[prop];
}
for (const prop in workingOutput) {
if (workingOutput[prop]) {
if (!nonRecOutputs.includes(prop)) {
recOutputCount++;
}
}
}
return {workingOutput, recOutputCount}
}
// List of options for Tesseract.js (rather than passed through to Tesseract),
// not including those with prefix "tessjs_"
const tessjsOptions = ["rectangle", "pdfTitle", "pdfTextOnly", "rotateAuto", "rotateRadians"];
const recognize = async ({
payload: {
image, options, output
},
}, res) => {
try {
const ptr = setImage(TessModule, api, image);
const optionsTess = {};
if (typeof options === "object" && Object.keys(options).length > 0) {
// The options provided by users contain a mix of options for Tesseract.js
// and parameters passed through to Tesseract.
for (const param in options) {
if (!param.startsWith('tessjs_') && !tessjsOptions.includes(param)) {
optionsTess[param] = options[param];
}
}
}
if (output.debug) {
optionsTess["debug_file"] = "/debugInternal.txt";
TessModule.FS.writeFile("/debugInternal.txt", "");
}
// If any parameters are changed here they are changed back at the end
if (Object.keys(optionsTess).length > 0) {
api.SaveParameters();
for (const prop in optionsTess) {
api.SetVariable(prop, optionsTess[prop]);
}
}
const {workingOutput, recOutputCount} = processOutput(output);
// When the auto-rotate option is True, setImage is called with no angle,
// then the angle is calculated by Tesseract and then setImage is re-called.
// Otherwise, setImage is called once using the user-provided rotateRadiansFinal value.
let rotateRadiansFinal;
if (options.rotateAuto) {
// The angle is only detected if auto page segmentation is used
// Therefore, if this is not the mode specified by the user, it is enabled temporarily here
const psmInit = api.GetPageSegMode();
let psmEdit = false;
if (![PSM.AUTO, PSM.AUTO_ONLY, PSM.OSD].includes(psmInit)) {
psmEdit = true;
api.SetVariable('tessedit_pageseg_mode', String(PSM.AUTO));
}
setImage(TessModule, api, image);
api.FindLines();
const rotateRadiansCalc = api.GetAngle();
// Restore user-provided PSM setting
if (psmEdit) {
api.SetVariable('tessedit_pageseg_mode', String(psmInit));
}
// Small angles (<0.005 radians/~0.3 degrees) are ignored to save on runtime
if (Math.abs(rotateRadiansCalc) >= 0.005) {
rotateRadiansFinal = rotateRadiansCalc;
setImage(TessModule, api, image, rotateRadiansFinal);
} else {
// Image needs to be reset if run with different PSM setting earlier
if (psmEdit) {
setImage(TessModule, api, image);
}
rotateRadiansFinal = 0;
}
} else {
rotateRadiansFinal = options.rotateRadians || 0;
setImage(TessModule, api, image, rotateRadiansFinal);
}
const rec = options.rectangle;
if (typeof rec === 'object') {
api.SetRectangle(rec.left, rec.top, rec.width, rec.height);
}
if (recOutputCount > 0) {
api.Recognize(null);
res.resolve(dump(TessModule, api, params));
TessModule._free(ptr);
} else {
log(`Skipping recognition: all output options requiring recognition are disabled.`);
}
const pdfTitle = options.pdfTitle;
const pdfTextOnly = options.pdfTextOnly;
const result = dump(TessModule, api, workingOutput, {pdfTitle, pdfTextOnly});
result.rotateRadians = rotateRadiansFinal;
if (output.debug) TessModule.FS.unlink("/debugInternal.txt");
if (Object.keys(optionsTess).length > 0) {
api.RestoreParameters();
}
res.resolve(result);
} catch (err) {
res.reject(err.toString());
}
};
const getPDF = ({ payload: { title, textonly } }, res) => {
const pdfRenderer = new TessModule.TessPDFRenderer('tesseract-ocr', '/', textonly);
pdfRenderer.BeginDocument(title);
pdfRenderer.AddImage(api);
pdfRenderer.EndDocument();
TessModule._free(pdfRenderer);
res.resolve(TessModule.FS.readFile('/tesseract-ocr.pdf'));
};
const detect = ({ payload: { image } }, res) => {
const detect = async ({ payload: { image } }, res) => {
try {
const ptr = setImage(TessModule, api, image);
setImage(TessModule, api, image);
const results = new TessModule.OSResults();
if (!api.DetectOS(results)) {
api.End();
TessModule._free(ptr);
res.reject('Failed to detect OS');
res.resolve({
tesseract_script_id: null,
script: null,
script_confidence: null,
orientation_degrees: null,
orientation_confidence: null,
});
} else {
const best = results.best_result;
const oid = best.orientation_id;
const sid = best.script_id;
TessModule._free(ptr);
res.resolve({
tesseract_script_id: sid,
script: results.unicharset.get_script_from_script_id(sid),
@ -250,7 +395,7 @@ const detect = ({ payload: { image } }, res) => { @@ -250,7 +395,7 @@ const detect = ({ payload: { image } }, res) => {
}
};
const terminate = (_, res) => {
const terminate = async (_, res) => {
try {
if (api !== null) {
api.End();
@ -287,7 +432,6 @@ exports.dispatchHandlers = (packet, send) => { @@ -287,7 +432,6 @@ exports.dispatchHandlers = (packet, send) => {
latestJob = res;
try {
({
load,
FS,
@ -298,11 +442,8 @@ exports.dispatchHandlers = (packet, send) => { @@ -298,11 +442,8 @@ exports.dispatchHandlers = (packet, send) => {
getPDF,
detect,
terminate,
})[packet.action](packet, res);
} catch (err) {
/** Prepare exception to travel through postMessage */
res.reject(err.toString());
}
})[packet.action](packet, res)
.catch((err) => res.reject(err.toString()));
};
/**

56
src/worker-script/utils/arrayBufferToBase64.js

@ -0,0 +1,56 @@ @@ -0,0 +1,56 @@
// Copied from https://gist.github.com/jonleighton/958841
// Copyright 2011 Jon Leighton, MIT LICENSE
/* eslint no-bitwise: 0 */
module.exports = (arrayBuffer) => {
let base64 = '';
const encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const bytes = new Uint8Array(arrayBuffer);
const { byteLength } = bytes;
const byteRemainder = byteLength % 3;
const mainLength = byteLength - byteRemainder;
let a; let b; let c; let
d;
let chunk;
// Main loop deals with bytes in chunks of 3
for (let i = 0; i < mainLength; i += 3) {
// Combine the three bytes into a single integer
chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
// Use bitmasks to extract 6-bit segments from the triplet
a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18
b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12
c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6
d = chunk & 63; // 63 = 2^6 - 1
// Convert the raw binary segments to the appropriate ASCII encoding
base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
}
// Deal with the remaining bytes and padding
if (byteRemainder === 1) {
chunk = bytes[mainLength];
a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2
// Set the 4 least significant bits to zero
b = (chunk & 3) << 4; // 3 = 2^2 - 1
base64 += `${encodings[a] + encodings[b]}==`;
} else if (byteRemainder === 2) {
chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1];
a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10
b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4
// Set the 2 least significant bits to zero
c = (chunk & 15) << 2; // 15 = 2^4 - 1
base64 += `${encodings[a] + encodings[b] + encodings[c]}=`;
}
return base64;
};

51
src/worker-script/utils/dump.js

@ -7,6 +7,8 @@ @@ -7,6 +7,8 @@
* @author Guillermo Webster <gui@mit.edu>
* @author Jerome Wu <jeromewus@gmail.com>
*/
const arrayBufferToBase64 = require('./arrayBufferToBase64');
const imageType = require('../../constants/imageType');
/**
* deindent
@ -37,13 +39,7 @@ const deindent = (html) => { @@ -37,13 +39,7 @@ const deindent = (html) => {
* @function dump recognition result to a JSON object
* @access public
*/
module.exports = (TessModule, api, {
tessjs_create_hocr,
tessjs_create_tsv,
tessjs_create_box,
tessjs_create_unlv,
tessjs_create_osd,
}) => {
module.exports = (TessModule, api, output, options) => {
const ri = api.GetIterator();
const {
RIL_BLOCK,
@ -65,6 +61,26 @@ module.exports = (TessModule, api, { @@ -65,6 +61,26 @@ module.exports = (TessModule, api, {
.map((e) => e.slice(prefix.length + 1))[0]
);
const getImage = (type) => {
api.WriteImage(type, '/image.png');
const pngBuffer = TessModule.FS.readFile('/image.png');
const pngStr = `data:image/png;base64,${arrayBufferToBase64(pngBuffer.buffer)}`;
TessModule.FS.unlink('/image.png');
return pngStr;
};
const getPDFInternal = (title, textonly) => {
const pdfRenderer = new TessModule.TessPDFRenderer('tesseract-ocr', '/', textonly);
pdfRenderer.BeginDocument(title);
pdfRenderer.AddImage(api);
pdfRenderer.EndDocument();
TessModule._free(pdfRenderer);
return TessModule.FS.readFile('/tesseract-ocr.pdf');
};
if (output.blocks) {
ri.Begin();
do {
if (ri.IsAtBeginningOf(RIL_BLOCK)) {
@ -185,17 +201,24 @@ module.exports = (TessModule, api, { @@ -185,17 +201,24 @@ module.exports = (TessModule, api, {
} while (ri.Next(RIL_SYMBOL));
TessModule.destroy(ri);
}
return {
text: api.GetUTF8Text(),
hocr: tessjs_create_hocr === '1' ? deindent(api.GetHOCRText()) : null,
tsv: tessjs_create_tsv === '1' ? api.GetTSVText() : null,
box: tessjs_create_box === '1' ? api.GetBoxText() : null,
unlv: tessjs_create_unlv === '1' ? api.GetUNLVText() : null,
osd: tessjs_create_osd === '1' ? api.GetOsdText() : null,
text: output.text ? api.GetUTF8Text() : null,
hocr: output.hocr ? deindent(api.GetHOCRText()) : null,
tsv: output.tsv ? api.GetTSVText() : null,
box: output.box ? api.GetBoxText() : null,
unlv: output.unlv ? api.GetUNLVText() : null,
osd: output.osd ? api.GetOsdText() : null,
pdf: output.pdf ? getPDFInternal(options.pdfTitle ?? 'Tesseract OCR Result', options.pdfTextOnly ?? false) : null,
imageColor: output.imageColor ? getImage(imageType.COLOR) : null,
imageGrey: output.imageGrey ? getImage(imageType.GREY) : null,
imageBinary: output.imageBinary ? getImage(imageType.BINARY) : null,
confidence: api.MeanTextConf(),
blocks,
blocks: output.blocks ? blocks : null,
psm: enumToString(api.GetPageSegMode(), 'PSM'),
oem: enumToString(api.oem(), 'OEM'),
version: api.Version(),
debug: output.debug ? TessModule.FS.readFile('/debugInternal.txt', { encoding: 'utf8', flags:"a+" }) : null
};
};

61
src/worker-script/utils/setImage.js

@ -8,56 +8,27 @@ const fileType = require('file-type'); @@ -8,56 +8,27 @@ const fileType = require('file-type');
* @function set image in tesseract for recognition
* @access public
*/
module.exports = (TessModule, api, image) => {
const buf = Buffer.from(Array.from({ ...image, length: Object.keys(image).length }));
const type = fileType(buf);
let bytesPerPixel = 0;
let data = null;
let pix = null;
let w = 0;
let h = 0;
module.exports = (TessModule, api, image, angle = 0) => {
const exif = buf.slice(0, 500).toString().match(/\x01\x12\x00\x03\x00\x00\x00\x01\x00(.)/)?.[1]?.charCodeAt(0) || 1;
const type = fileType(image);
/*
* Leptonica supports uncompressed but not compressed bmp files
* @see https://github.com/DanBloomberg/leptonica/issues/607#issuecomment-1068802516
* We therefore use bmp-js to process all bmp files
*/
const exif = image.slice(0, 500).toString().match(/\x01\x12\x00\x03\x00\x00\x00\x01\x00(.)/)?.[1]?.charCodeAt(0) || 1;
// /*
// * Leptonica supports some but not all bmp files
// * @see https://github.com/DanBloomberg/leptonica/issues/607#issuecomment-1068802516
// * We therefore use bmp-js to convert all bmp files into a format Leptonica is known to support
// */
if (type && type.mime === 'image/bmp') {
// Not sure what this line actually does, but removing breaks the function
const buf = Buffer.from(Array.from({ ...image, length: Object.keys(image).length }));
const bmpBuf = bmp.decode(buf);
data = TessModule._malloc(bmpBuf.data.length * Uint8Array.BYTES_PER_ELEMENT);
TessModule.HEAPU8.set(bmpBuf.data, data);
w = bmpBuf.width;
h = bmpBuf.height;
bytesPerPixel = 4;
TessModule.FS.writeFile("/input", bmp.encode(bmpBuf).data);
} else {
const ptr = TessModule._malloc(buf.length * Uint8Array.BYTES_PER_ELEMENT);
TessModule.HEAPU8.set(buf, ptr);
pix = TessModule._pixReadMem(ptr, buf.length);
if (TessModule.getValue(pix + (7 * 4), 'i32') === 0) {
/*
* Set a yres default value to prevent warning from tesseract
* See kMinCredibleResolution in tesseract/src/ccstruct/publictypes.h
*/
TessModule.setValue(pix + (7 * 4), 300, 'i32');
}
[w, h] = Array(2).fill(0)
.map((v, idx) => (
TessModule.getValue(pix + (idx * 4), 'i32')
));
TessModule.FS.writeFile("/input", image);
}
/*
* As some image format (ex. bmp) is not supported natiely by tesseract,
* sometimes it will not return pix directly, but data and bytesPerPixel
* for another SetImage usage.
*
*/
if (data === null) {
api.SetImage(pix, undefined, undefined, undefined, undefined, exif);
} else {
api.SetImage(data, w, h, bytesPerPixel, w * bytesPerPixel, exif);
}
return data === null ? pix : data;
api.SetImageFile(exif, angle);
return;
};

6
tests/FS.test.js

@ -1,9 +1,9 @@ @@ -1,9 +1,9 @@
const { createWorker } = Tesseract;
const FS_WAIT = 500;
const worker = createWorker(OPTIONS);
before(function cb() {
let worker;
before(async function cb() {
this.timeout(0);
return worker.load();
worker = await createWorker(OPTIONS);
});
describe('FS', async () => {

18
tests/detect.test.js

@ -1,8 +1,8 @@ @@ -1,8 +1,8 @@
const { createWorker } = Tesseract;
const worker = createWorker(OPTIONS);
before(function cb() {
let worker;
before(async function cb() {
this.timeout(0);
return worker.load();
worker = await createWorker(OPTIONS);
});
describe('detect()', async () => {
@ -17,3 +17,15 @@ describe('detect()', async () => { @@ -17,3 +17,15 @@ describe('detect()', async () => {
});
}).timeout(TIMEOUT);
});
describe('detect()', async () => {
it('should detect OSD (simplified interface)', () => {
[
{ name: 'cosmic.png', ans: { script: 'Latin' } },
].forEach(async ({ name, ans: { script } }) => {
const { data: { script: s } } = await Tesseract.detect(`${IMAGE_PATH}/${name}`, undefined, OPTIONS);
expect(s).to.be(script);
});
}).timeout(TIMEOUT);
});

17
tests/recognize.test.js

@ -1,8 +1,8 @@ @@ -1,8 +1,8 @@
const { createWorker, PSM } = Tesseract;
const worker = createWorker(OPTIONS);
let worker;
before(async function cb() {
this.timeout(0);
await worker.load();
worker = await createWorker(OPTIONS);
await worker.loadLanguage('eng+chi_tra+osd');
});
@ -30,6 +30,19 @@ describe('recognize()', () => { @@ -30,6 +30,19 @@ describe('recognize()', () => {
));
});
describe('should recognize base64 image (simplified interface)', () => {
[
{ format: 'png', image: SIMPLE_PNG_BASE64, ans: SIMPLE_TEXT },
{ format: 'jpg', image: SIMPLE_JPG_BASE64, ans: SIMPLE_TEXT },
].forEach(({ format, image, ans }) => (
it(`recongize ${format} in base64`, async () => {
const { data: { text } } = await Tesseract.recognize(image, undefined, OPTIONS);
expect(text).to.be(ans);
}).timeout(TIMEOUT)
));
});
describe('should recognize different langs', () => {
[
{ name: 'chinese.png', lang: 'chi_tra', ans: CHINESE_TEXT },

3
tests/scheduler.test.js

@ -7,8 +7,7 @@ before(async function cb() { @@ -7,8 +7,7 @@ before(async function cb() {
const NUM_WORKERS = 5;
console.log(`Initializing ${NUM_WORKERS} workers`);
workers = await Promise.all(Array(NUM_WORKERS).fill(0).map(async () => {
const w = createWorker(OPTIONS);
await w.load();
const w = await createWorker(OPTIONS);
await w.loadLanguage('eng');
await w.initialize('eng');
return w;

Loading…
Cancel
Save