2019-09-04 20:37:02 +02:00
/ * *
2019-09-13 15:34:08 +02:00
* @ author n1474335 [ n1474335 @ gmail . com ]
2019-09-04 20:37:02 +02:00
* @ author mshwed [ m @ ttshwed . com ]
* @ copyright Crown Copyright 2019
* @ license Apache - 2.0
* /
import Operation from "../Operation.mjs" ;
import OperationError from "../errors/OperationError.mjs" ;
import { isImage } from "../lib/FileType.mjs" ;
2019-09-13 15:34:08 +02:00
import { toBase64 } from "../lib/Base64.mjs" ;
2019-09-04 20:37:02 +02:00
import { isWorkerEnvironment } from "../Utils.mjs" ;
import Tesseract from "tesseract.js" ;
const { TesseractWorker } = Tesseract ;
/ * *
2019-09-13 15:34:08 +02:00
* Optical Character Recognition operation
2019-09-04 20:37:02 +02:00
* /
2019-09-13 15:34:08 +02:00
class OpticalCharacterRecognition extends Operation {
2019-09-04 20:37:02 +02:00
/ * *
2019-09-13 15:34:08 +02:00
* OpticalCharacterRecognition constructor
2019-09-04 20:37:02 +02:00
* /
constructor ( ) {
super ( ) ;
2019-09-13 15:34:08 +02:00
this . name = "Optical Character Recognition" ;
this . module = "Image" ;
this . description = "Optical character recognition or optical character reader (OCR) is the mechanical or electronic conversion of images of typed, handwritten or printed text into machine-encoded text.<br><br>Supported image formats: png, jpg, bmp, pbm." ;
this . infoURL = "https://wikipedia.org/wiki/Optical_character_recognition" ;
2019-09-04 20:37:02 +02:00
this . inputType = "ArrayBuffer" ;
this . outputType = "string" ;
2019-09-13 15:34:08 +02:00
this . args = [
{
name : "Show confidence" ,
type : "boolean" ,
value : true
}
] ;
2019-09-04 20:37:02 +02:00
}
/ * *
* @ param { ArrayBuffer } input
* @ param { Object [ ] } args
2019-09-05 15:20:59 +02:00
* @ returns { string }
2019-09-04 20:37:02 +02:00
* /
async run ( input , args ) {
2019-09-13 15:34:08 +02:00
const [ showConfidence ] = args ;
const type = isImage ( input ) ;
if ( ! type ) {
2019-09-04 20:37:02 +02:00
throw new OperationError ( "Invalid File Type" ) ;
}
try {
2019-09-13 15:34:08 +02:00
const image = ` data: ${ type } ;base64, ${ toBase64 ( input ) } ` ;
2019-09-04 20:37:02 +02:00
const worker = new TesseractWorker ( ) ;
const result = await worker . recognize ( image )
. progress ( progress => {
2019-09-13 15:34:08 +02:00
if ( isWorkerEnvironment ( ) ) {
self . sendStatusMessage ( ` Status: ${ progress . status } - ${ ( parseFloat ( progress . progress ) * 100 ) . toFixed ( 2 ) } % ` ) ;
}
2019-09-04 20:37:02 +02:00
} ) ;
2019-09-13 15:34:08 +02:00
if ( showConfidence ) {
return ` Confidence: ${ result . confidence } % \n \n ${ result . text } ` ;
} else {
return result . text ;
}
2019-09-04 20:37:02 +02:00
} catch ( err ) {
throw new OperationError ( ` Error performing OCR on image. ( ${ err } ) ` ) ;
}
}
}
2019-09-13 15:34:08 +02:00
export default OpticalCharacterRecognition ;