Pure Javascript OCR for more than 100 Languages 📖🎉🖥
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.8 KiB

8 years ago
const adapter = require('./node/index.js')
const circularize = require('./common/circularize.js')
const TesseractJob = require('./common/job');
const version = require('../package.json').version;
function create(workerOptions = {}){
8 years ago
var worker = new TesseractWorker(Object.assign({}, adapter.defaultOptions, workerOptions));
worker.create = create;
worker.version = version;
return worker;
}
class TesseractWorker {
constructor(workerOptions){
this.worker = null;
this.workerOptions = workerOptions;
this._currentJob = null;
this._queue = [];
}
recognize(image, options = {}){
return this._delay(job => {
if (typeof options === 'string') options = {lang: options}
options.lang = options.lang || 'eng';
job._send('recognize', { image, options, workerOptions: this.workerOptions });
})
}
detect(image, options = {}){
return this._delay(job => {
job._send('detect', { image, options, workerOptions: this.workerOptions });
})
}
terminate(){
if(this.worker) adapter.terminateWorker(this);
this.worker = null;
8 years ago
this._currentJob = null;
this._queue = [];
}
_delay(fn){
if(!this.worker) this.worker = adapter.spawnWorker(this, this.workerOptions);
var job = new TesseractJob(this);
this._queue.push(e => {
this._queue.shift();
this._currentJob = job;
fn(job);
});
if(!this._currentJob) this._dequeue();
return job;
}
_dequeue(){
this._currentJob = null;
if(this._queue.length){
this._queue[0]();
}
}
_recv(packet){
8 years ago
if(packet.status === 'resolve' && packet.action === 'recognize'){
packet.data = circularize(packet.data);
}
if(this._currentJob.id === packet.jobId){
this._currentJob._handle(packet)
} else {
console.warn('Job ID ' + packet.jobId + ' not known.')
}
}
}
8 years ago
module.exports = create();