OpticalCharacterRecognition.mjs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * @author n1474335 [n1474335@gmail.com]
  3. * @author mshwed [m@ttshwed.com]
  4. * @copyright Crown Copyright 2019
  5. * @license Apache-2.0
  6. */
  7. import Operation from "../Operation.mjs";
  8. import OperationError from "../errors/OperationError.mjs";
  9. import { isImage } from "../lib/FileType.mjs";
  10. import { toBase64 } from "../lib/Base64.mjs";
  11. import { isWorkerEnvironment } from "../Utils.mjs";
  12. import Tesseract from "tesseract.js";
  13. const { TesseractWorker } = Tesseract;
  14. import process from "process";
  15. /**
  16. * Optical Character Recognition operation
  17. */
  18. class OpticalCharacterRecognition extends Operation {
  19. /**
  20. * OpticalCharacterRecognition constructor
  21. */
  22. constructor() {
  23. super();
  24. this.name = "Optical Character Recognition";
  25. this.module = "OCR";
  26. 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.";
  27. this.infoURL = "https://wikipedia.org/wiki/Optical_character_recognition";
  28. this.inputType = "ArrayBuffer";
  29. this.outputType = "string";
  30. this.args = [
  31. {
  32. name: "Show confidence",
  33. type: "boolean",
  34. value: true
  35. }
  36. ];
  37. }
  38. /**
  39. * @param {ArrayBuffer} input
  40. * @param {Object[]} args
  41. * @returns {string}
  42. */
  43. async run(input, args) {
  44. const [showConfidence] = args;
  45. if (!isWorkerEnvironment()) throw OperationError("This operation only works in a browser");
  46. const type = isImage(input);
  47. if (!type) {
  48. throw new OperationError("Invalid File Type");
  49. }
  50. const assetDir = isWorkerEnvironment() ? `${self.docURL}/assets/` : `${process.cwd()}/src/core/vendor/`;
  51. try {
  52. const image = `data:${type};base64,${toBase64(input)}`;
  53. const worker = new TesseractWorker({
  54. workerPath: `${assetDir}tesseract/worker.min.js`,
  55. langPath: `${assetDir}tesseract/lang-data`,
  56. corePath: `${assetDir}tesseract/tesseract-core.wasm.js`,
  57. });
  58. const result = await worker.recognize(image)
  59. .progress(progress => {
  60. if (isWorkerEnvironment()) {
  61. self.sendStatusMessage(`Status: ${progress.status} - ${(parseFloat(progress.progress)*100).toFixed(2)}%`);
  62. }
  63. });
  64. if (showConfidence) {
  65. return `Confidence: ${result.confidence}%\n\n${result.text}`;
  66. } else {
  67. return result.text;
  68. }
  69. } catch (err) {
  70. throw new OperationError(`Error performing OCR on image. (${err})`);
  71. }
  72. }
  73. }
  74. export default OpticalCharacterRecognition;