From 0277db26b105e9b33d0dab23edcffbb10c086afd Mon Sep 17 00:00:00 2001 From: Balearica Date: Wed, 14 Sep 2022 22:38:18 -0700 Subject: [PATCH] Updated createWorker to be async --- src/createWorker.js | 25 +++++++++++++++++++++++-- src/worker-script/index.js | 32 ++++++++++++++++++-------------- tests/FS.test.js | 5 +++-- tests/detect.test.js | 5 +++-- tests/error.test.html | 18 ++++++++++++++++++ tests/error.test.js | 29 +++++++++++++++++++++++++++++ tests/recognize.test.js | 3 ++- tests/scheduler.test.js | 2 +- 8 files changed, 97 insertions(+), 22 deletions(-) create mode 100644 tests/error.test.html create mode 100644 tests/error.test.js diff --git a/src/createWorker.js b/src/createWorker.js index 3c3b626..83227ec 100644 --- a/src/createWorker.js +++ b/src/createWorker.js @@ -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 = {}) => { }); 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 = {}) => { } }); - return { + const resolveObj = { id, worker, setResolve, @@ -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; + }; diff --git a/src/worker-script/index.js b/src/worker-script/index.js index 3634f1c..1b07899 100644 --- a/src/worker-script/index.js +++ b/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}`); 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) .filter((k) => !k.startsWith('tessjs_')) .forEach((key) => { @@ -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) => { return pngStr; }; -const recognize = ({ +const recognize = async ({ payload: { image, options: { rectangle: rec, saveImageOriginal, saveImageGrey, saveImageBinary, rotateAuto, rotateRadians, @@ -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 = ({ } }; -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) => { 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) => { } }; -const terminate = (_, res) => { +const terminate = async (_, res) => { try { if (api !== null) { 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 * @@ -416,7 +423,6 @@ exports.dispatchHandlers = (packet, send) => { latestJob = res; - try { ({ load, FS, @@ -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())); }; /** diff --git a/tests/FS.test.js b/tests/FS.test.js index 393926f..5fea777 100644 --- a/tests/FS.test.js +++ b/tests/FS.test.js @@ -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(); }); diff --git a/tests/detect.test.js b/tests/detect.test.js index cadef05..0903e91 100644 --- a/tests/detect.test.js +++ b/tests/detect.test.js @@ -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(); }); diff --git a/tests/error.test.html b/tests/error.test.html new file mode 100644 index 0000000..a25e162 --- /dev/null +++ b/tests/error.test.html @@ -0,0 +1,18 @@ + + + + + + +
+ + + + + + + + + diff --git a/tests/error.test.js b/tests/error.test.js new file mode 100644 index 0000000..1c56863 --- /dev/null +++ b/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); +}); diff --git a/tests/recognize.test.js b/tests/recognize.test.js index a65f108..9df5127 100644 --- a/tests/recognize.test.js +++ b/tests/recognize.test.js @@ -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'); }); diff --git a/tests/scheduler.test.js b/tests/scheduler.test.js index b47cc83..a59d516 100644 --- a/tests/scheduler.test.js +++ b/tests/scheduler.test.js @@ -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');