mirror of
https://github.com/gchq/CyberChef.git
synced 2025-04-22 15:56:16 -04:00
Added basic OCR text extraction
This commit is contained in:
parent
c6de3eb2ae
commit
f1659af5e4
4 changed files with 160 additions and 10 deletions
87
src/core/operations/OCR.mjs
Normal file
87
src/core/operations/OCR.mjs
Normal file
|
@ -0,0 +1,87 @@
|
|||
/**
|
||||
* @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";
|
||||
import { isWorkerEnvironment } from "../Utils.mjs";
|
||||
|
||||
import jimp from "jimp";
|
||||
import Tesseract from "tesseract.js";
|
||||
const { TesseractWorker } = Tesseract;
|
||||
|
||||
/**
|
||||
* OCR operation
|
||||
*/
|
||||
class OCR extends Operation {
|
||||
|
||||
/**
|
||||
* OCR constructor
|
||||
*/
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.name = "OCR";
|
||||
this.module = "Default";
|
||||
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.";
|
||||
this.infoURL = "https://en.wikipedia.org/wiki/Optical_character_recognition";
|
||||
this.inputType = "ArrayBuffer";
|
||||
this.outputType = "string";
|
||||
this.args = [
|
||||
/* Example arguments. See the project wiki for full details.
|
||||
{
|
||||
name: "First arg",
|
||||
type: "string",
|
||||
value: "Don't Panic"
|
||||
},
|
||||
{
|
||||
name: "Second arg",
|
||||
type: "number",
|
||||
value: 42
|
||||
}
|
||||
*/
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ArrayBuffer} input
|
||||
* @param {Object[]} args
|
||||
* @returns {Object}
|
||||
*/
|
||||
async run(input, args) {
|
||||
if (!isImage(input)) {
|
||||
throw new OperationError("Invalid File Type");
|
||||
}
|
||||
|
||||
try {
|
||||
if (isWorkerEnvironment())
|
||||
self.sendStatusMessage("Performing OCR on image...");
|
||||
|
||||
let image;
|
||||
try {
|
||||
image = await jimp.read(input);
|
||||
image = await image.getBase64Async(jimp.AUTO);
|
||||
} catch (err) {
|
||||
throw new OperationError(`Error loading image. (${err})`);
|
||||
}
|
||||
|
||||
const worker = new TesseractWorker();
|
||||
|
||||
const result = await worker.recognize(image)
|
||||
.progress(progress => {
|
||||
if (isWorkerEnvironment()) self.sendStatusMessage(`${progress.status} - ${parseFloat(progress.progress).toFixed(2)}%`);
|
||||
});
|
||||
|
||||
console.log(result);
|
||||
|
||||
return result.text;
|
||||
} catch (err) {
|
||||
throw new OperationError(`Error performing OCR on image. (${err})`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default OCR;
|
Loading…
Add table
Add a link
Reference in a new issue