UNPKG

mindee

Version:

Mindee Client Library for Node.js

91 lines (88 loc) 3.42 kB
import { CropperExtra, FullTextOcrExtra, RAGExtra } from "./extras/index.js"; import { MindeeConfigurationError } from "../../../errors/index.js"; /** * * @typeParam DocT an extension of a `Prediction`. Is generic by default to * allow for easier optional `PageT` generic typing. * @typeParam PageT an extension of a `DocT` (`Prediction`). Should only be set * if a document's pages have specific implementation. */ export class Inference { constructor(rawPrediction) { /** Wrapper for a document's pages prediction. */ this.pages = []; this.isRotationApplied = rawPrediction?.is_rotation_applied ?? undefined; this.product = rawPrediction?.product; if (rawPrediction["extras"] && Object.keys(rawPrediction["extras"].length > 0)) { const extras = {}; Object.entries(rawPrediction["extras"]).forEach(([extraKey, extraValue]) => { switch (extraKey) { case "cropper": extras.cropper = new CropperExtra(extraValue); break; case "full_text_ocr": extras.fullTextOcr = new FullTextOcrExtra(extraValue); break; case "rag": extras.rag = new RAGExtra(extraValue); break; } }); this.extras = extras; } } /** * Default string representation. */ toString() { let pages = ""; if (this.pages.toString().length > 0) { pages = ` Page Predictions ================ ${this.pages.map((e) => e.toString() || "").join("\n")}`; } return `Inference ######### :Product: ${this.product.name} v${this.product.version} :Rotation applied: ${this.isRotationApplied ? "Yes" : "No"} Prediction ========== ${this.prediction.toString().length === 0 ? "" : this.prediction.toString() + "\n"}${pages}`; } /** * Takes in an input string and replaces line breaks with `\n`. * @param outStr string to cleanup * @returns cleaned out string */ static cleanOutString(outStr) { const lines = / \n/gm; return outStr.replace(lines, "\n"); } } /** * Factory to allow for static-like property access syntax in TypeScript. * Used to retrieve endpoint data for standard products. */ export class InferenceFactory { /** * Builds a blank product of the given type & sends back the endpointName & endpointVersion parameters of OTS classes. * Note: this is needed to avoid passing anything other than the class of the object to the parse()/enqueue() call. * @param inferenceClass Class of the product we are using * @returns {Inference} An empty instance of a given product. */ static getEndpoint(inferenceClass) { const emptyProduct = new inferenceClass({ prediction: {}, pages: [], }); if (!emptyProduct.endpointName || !emptyProduct.endpointVersion || emptyProduct.endpointName.length === 0 || emptyProduct.endpointVersion.length === 0) { throw new MindeeConfigurationError(`Error during endpoint verification, no endpoint found for product ${inferenceClass.name}.`); } return [emptyProduct.endpointName, emptyProduct.endpointVersion]; } }