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 {
let workerCounter = 0; let workerCounter = 0;
module.exports = (_options = {}) => { module.exports = async (_options = {}) => {
const id = getId('Worker', workerCounter); const id = getId('Worker', workerCounter);
const { const {
logger, logger,
@ -27,7 +27,18 @@ module.exports = (_options = {}) => {
}); });
const resolves = {}; const resolves = {};
const rejects = {}; 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); let worker = spawnWorker(options);
// worker.addEventListener("error", workerError);
worker.onerror = workerError;
workerCounter += 1; workerCounter += 1;
@ -185,7 +196,7 @@ module.exports = (_options = {}) => {
} }
}); });
return { const resolveObj = {
id, id,
worker, worker,
setResolve, setResolve,
@ -204,4 +215,14 @@ module.exports = (_options = {}) => {
detect, detect,
terminate, 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 }
} }
}; };
const FS = ({ workerId, payload: { method, args } }, res) => { const FS = async ({ workerId, payload: { method, args } }, res) => {
log(`[${workerId}]: FS.${method} with args ${args}`); log(`[${workerId}]: FS.${method} with args ${args}`);
res.resolve(TessModule.FS[method](...args)); res.resolve(TessModule.FS[method](...args));
}; };
@ -159,7 +159,7 @@ res) => {
} }
}; };
const setParameters = ({ payload: { params: _params } }, res) => { const setParameters = async ({ payload: { params: _params } }, res) => {
Object.keys(_params) Object.keys(_params)
.filter((k) => !k.startsWith('tessjs_')) .filter((k) => !k.startsWith('tessjs_'))
.forEach((key) => { .forEach((key) => {
@ -172,7 +172,7 @@ const setParameters = ({ payload: { params: _params } }, res) => {
} }
}; };
const initialize = ({ const initialize = async ({
workerId, workerId,
payload: { langs: _langs, oem }, payload: { langs: _langs, oem },
}, res) => { }, res) => {
@ -208,7 +208,7 @@ const getImage = (type) => {
return pngStr; return pngStr;
}; };
const recognize = ({ const recognize = async ({
payload: { payload: {
image, options: { image, options: {
rectangle: rec, saveImageOriginal, saveImageGrey, saveImageBinary, rotateAuto, rotateRadians, rectangle: rec, saveImageOriginal, saveImageGrey, saveImageBinary, rotateAuto, rotateRadians,
@ -280,7 +280,7 @@ const recognize = ({
// `threshold` is similar to `recognize` except it skips the recognition step // `threshold` is similar to `recognize` except it skips the recognition step
// Useful for getting rotated/binarized images without running recognition // Useful for getting rotated/binarized images without running recognition
const threshold = ({ const threshold = async ({
payload: { payload: {
image, options: { image, options: {
rectangle: rec, saveImageOriginal, saveImageGrey, saveImageBinary, rotateAuto, rotateRadians, rectangle: rec, saveImageOriginal, saveImageGrey, saveImageBinary, rotateAuto, rotateRadians,
@ -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); const pdfRenderer = new TessModule.TessPDFRenderer('tesseract-ocr', '/', textonly);
pdfRenderer.BeginDocument(title); pdfRenderer.BeginDocument(title);
pdfRenderer.AddImage(api); pdfRenderer.AddImage(api);
@ -350,7 +350,7 @@ const getPDF = ({ payload: { title, textonly } }, res) => {
res.resolve(TessModule.FS.readFile('/tesseract-ocr.pdf')); res.resolve(TessModule.FS.readFile('/tesseract-ocr.pdf'));
}; };
const detect = ({ payload: { image } }, res) => { const detect = async ({ payload: { image } }, res) => {
try { try {
const ptr = setImage(TessModule, api, image); const ptr = setImage(TessModule, api, image);
const results = new TessModule.OSResults(); const results = new TessModule.OSResults();
@ -379,7 +379,7 @@ const detect = ({ payload: { image } }, res) => {
} }
}; };
const terminate = (_, res) => { const terminate = async (_, res) => {
try { try {
if (api !== null) { if (api !== null) {
api.End(); api.End();
@ -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 * dispatchHandlers
* *
@ -416,7 +423,6 @@ exports.dispatchHandlers = (packet, send) => {
latestJob = res; latestJob = res;
try {
({ ({
load, load,
FS, FS,
@ -428,11 +434,9 @@ exports.dispatchHandlers = (packet, send) => {
getPDF, getPDF,
detect, detect,
terminate, terminate,
})[packet.action](packet, res); checkWorker
} catch (err) { })[packet.action](packet, res)
/** Prepare exception to travel through postMessage */ .catch((err) => res.reject(err.toString()));
res.reject(err.toString());
}
}; };
/** /**

5
tests/FS.test.js

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

5
tests/detect.test.js

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

18
tests/error.test.html

@ -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 @@
// 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 @@
const { createWorker, PSM } = Tesseract; const { createWorker, PSM } = Tesseract;
const worker = createWorker(OPTIONS); let worker;
before(async function cb() { before(async function cb() {
this.timeout(0); this.timeout(0);
worker = await createWorker(OPTIONS);
await worker.load(); await worker.load();
await worker.loadLanguage('eng+chi_tra+osd'); await worker.loadLanguage('eng+chi_tra+osd');
}); });

2
tests/scheduler.test.js

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

Loading…
Cancel
Save