Browse Source

Updated createWorker to be async

dev/v4
Balearica 2 years ago
parent
commit
0277db26b1
  1. 25
      src/createWorker.js
  2. 32
      src/worker-script/index.js
  3. 5
      tests/FS.test.js
  4. 5
      tests/detect.test.js
  5. 18
      tests/error.test.html
  6. 29
      tests/error.test.js
  7. 3
      tests/recognize.test.js
  8. 2
      tests/scheduler.test.js

25
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,18 @@ module.exports = (_options = {}) => { @@ -27,7 +27,18 @@ module.exports = (_options = {}) => {
});
const resolves = {};
const rejects = {};
let resReject;
let resResolve;
const res = new Promise((resolve, reject) => {
resResolve = resolve;
resReject = reject;
});
let workerError = (event) => {resReject(event.message)};
let worker = spawnWorker(options);
// worker.addEventListener("error", workerError);
worker.onerror = workerError;
workerCounter += 1;
@ -185,7 +196,7 @@ module.exports = (_options = {}) => { @@ -185,7 +196,7 @@ module.exports = (_options = {}) => {
}
});
return {
const resolveObj = {
id,
worker,
setResolve,
@ -204,4 +215,14 @@ module.exports = (_options = {}) => { @@ -204,4 +215,14 @@ module.exports = (_options = {}) => {
detect,
terminate,
};
startJob(createJob({
id: undefined, action: 'checkWorker',
})).then(() => {
console.log("Created worker");
// worker.removeEventListener("error", workerError);
resResolve(resolveObj)});
return res;
};

32
src/worker-script/index.js

@ -57,7 +57,7 @@ const load = async ({ workerId, jobId, payload: { options: { corePath, logging } @@ -57,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));
};
@ -159,7 +159,7 @@ res) => { @@ -159,7 +159,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) => {
@ -172,7 +172,7 @@ const setParameters = ({ payload: { params: _params } }, res) => { @@ -172,7 +172,7 @@ const setParameters = ({ payload: { params: _params } }, res) => {
}
};
const initialize = ({
const initialize = async ({
workerId,
payload: { langs: _langs, oem },
}, res) => {
@ -208,7 +208,7 @@ const getImage = (type) => { @@ -208,7 +208,7 @@ const getImage = (type) => {
return pngStr;
};
const recognize = ({
const recognize = async ({
payload: {
image, options: {
rectangle: rec, saveImageOriginal, saveImageGrey, saveImageBinary, rotateAuto, rotateRadians,
@ -280,7 +280,7 @@ const recognize = ({ @@ -280,7 +280,7 @@ const recognize = ({
// `threshold` is similar to `recognize` except it skips the recognition step
// Useful for getting rotated/binarized images without running recognition
const threshold = ({
const threshold = async ({
payload: {
image, options: {
rectangle: rec, saveImageOriginal, saveImageGrey, saveImageBinary, rotateAuto, rotateRadians,
@ -340,7 +340,7 @@ const threshold = ({ @@ -340,7 +340,7 @@ const threshold = ({
}
};
const getPDF = ({ payload: { title, textonly } }, res) => {
const getPDF = async ({ payload: { title, textonly } }, res) => {
const pdfRenderer = new TessModule.TessPDFRenderer('tesseract-ocr', '/', textonly);
pdfRenderer.BeginDocument(title);
pdfRenderer.AddImage(api);
@ -350,7 +350,7 @@ const getPDF = ({ payload: { title, textonly } }, res) => { @@ -350,7 +350,7 @@ const getPDF = ({ payload: { title, textonly } }, res) => {
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);
const results = new TessModule.OSResults();
@ -379,7 +379,7 @@ const detect = ({ payload: { image } }, res) => { @@ -379,7 +379,7 @@ const detect = ({ payload: { image } }, res) => {
}
};
const terminate = (_, res) => {
const terminate = async (_, res) => {
try {
if (api !== null) {
api.End();
@ -390,6 +390,13 @@ const terminate = (_, res) => { @@ -390,6 +390,13 @@ const terminate = (_, res) => {
}
};
// Function that always resolves
// Used to confirm that worker was successfully created
const checkWorker = async (_, res) => {
res.resolve();
};
/**
* dispatchHandlers
*
@ -416,7 +423,6 @@ exports.dispatchHandlers = (packet, send) => { @@ -416,7 +423,6 @@ exports.dispatchHandlers = (packet, send) => {
latestJob = res;
try {
({
load,
FS,
@ -428,11 +434,9 @@ exports.dispatchHandlers = (packet, send) => { @@ -428,11 +434,9 @@ exports.dispatchHandlers = (packet, send) => {
getPDF,
detect,
terminate,
})[packet.action](packet, res);
} catch (err) {
/** Prepare exception to travel through postMessage */
res.reject(err.toString());
}
checkWorker
})[packet.action](packet, res)
.catch((err) => res.reject(err.toString()));
};
/**

5
tests/FS.test.js

@ -1,8 +1,9 @@ @@ -1,8 +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);
worker = await createWorker(OPTIONS);
return worker.load();
});

5
tests/detect.test.js

@ -1,7 +1,8 @@ @@ -1,7 +1,8 @@
const { createWorker } = Tesseract;
const worker = createWorker(OPTIONS);
before(function cb() {
let worker;
before(async function cb() {
this.timeout(0);
worker = await createWorker(OPTIONS);
return worker.load();
});

18
tests/error.test.html

@ -0,0 +1,18 @@ @@ -0,0 +1,18 @@
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="../node_modules/mocha/mocha.css">
</head>
<body>
<div id="mocha"></div>
<script src="../node_modules/mocha/mocha.js"></script>
<script src="../node_modules/expect.js/index.js"></script>
<script src="../dist/tesseract.dev.js"></script>
<script src="./constants.js"></script>
<script>mocha.setup('bdd');</script>
<script src="./error.test.js"></script>
<script>
mocha.run();
</script>
</body>
</html>

29
tests/error.test.js

@ -0,0 +1,29 @@ @@ -0,0 +1,29 @@
// const { createWorker } = Tesseract;
// const worker = createWorker(OPTIONS);
// before(function cb() {
// this.timeout(0);
// return worker.load();
// });
(IS_BROWSER ? describe : describe.skip)('Invalid paths should result in promise rejection', () => {
it('Invalid workerPath', async () => {
const OPTIONS1 = JSON.parse(JSON.stringify(OPTIONS));
OPTIONS1.corePath = "badpath.js";
let errorThrown;
try {
const worker = Tesseract.createWorker(OPTIONS1);
await worker.load()
errorThrown = false;
} catch (error) {
errorThrown = true;
}
expect(errorThrown).to.equal(true);
// expect(func).to.throwError();
// const ret = await (worker.load().then(() => true).catch(() => false));
// expect(ret).to.equal(false);
}).timeout(TIMEOUT);
});

3
tests/recognize.test.js

@ -1,7 +1,8 @@ @@ -1,7 +1,8 @@
const { createWorker, PSM } = Tesseract;
const worker = createWorker(OPTIONS);
let worker;
before(async function cb() {
this.timeout(0);
worker = await createWorker(OPTIONS);
await worker.load();
await worker.loadLanguage('eng+chi_tra+osd');
});

2
tests/scheduler.test.js

@ -7,7 +7,7 @@ before(async function cb() { @@ -7,7 +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);
const w = await createWorker(OPTIONS);
await w.load();
await w.loadLanguage('eng');
await w.initialize('eng');

Loading…
Cancel
Save