UNPKG

@briancullen/aws-textract-parser

Version:

Library for converting AWS Textract responses into a more usable structure.

178 lines (177 loc) 8.86 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var factory_1 = __importDefault(require("./factory")); /** * This class provides methods to process the information returned by Textract into * a tree structure that is easier to work with. * * A single instance of this class is automatically created for you and provided as * the default export from this library. */ var TextractParser = /** @class */ (function () { /** @hidden */ function TextractParser(factory) { this.factory = factory; } /** * Method that parses the textract response synchronously. * * For example it can also be used as part of processing the result of a promise * as shown below. * * ```typescript * textract.detectDocumentText(request).promise() * .then(data => textractParser.parseDetectTextResponse(data)) * .then(parsedData => console.log(parsedData)) * .catch(err => console.log(err)) * ``` * * **NOTE**: If used to process GetDocumentTextDetectionResponse response then all data should be * contained within a single response. If a NextToken is detected on the response then null will * be returned. See [[parseGetTextDetection]] for a helper method which will aggregate the * responses from the GetDocumentTextDetection operation. * * @param response the response object returned from Textract or null if the response is incomplete * @returns Document that acts as the root node for the processed tree */ TextractParser.prototype.parseDetectTextResponse = function (response) { if (response.NextToken !== undefined) { return null; } return this.factory.process(response); }; /** * Method that acts as a proxy for the standard Textract callback. * * This proxy will process the data returned by Textract and call the provided callback * with the processed information. It can be invoked as shown, where myCallback is written * by the user of the library. * * ```typescript * textract.detectDocumentText(request, textractParser.parseDetectTextCallback(myCallback)) * ``` * * @param callback the callback to be invoked with the processed data or error * @returns callback function that can be used with the AWS Textract invocation */ TextractParser.prototype.parseDetectTextCallback = function (callback) { var _this = this; return function (err, detectTextResponse) { if (err !== null || detectTextResponse === null) { callback(err, null); } else { callback(null, _this.parseDetectTextResponse(detectTextResponse)); } }; }; /** * Method that retrieves the result of a asynchronous document text detection operation * (which may require multiple requests to AWS) and produces a tree of the results. * * An example of how to use this method is shown below. * * ```typescript * const jobId = 'your-job-id' * const client = new AWS.Textract() * * textract.detectDocumentText(client, jobId) * .then(parsedData => console.log(parsedData)) * .catch(err => console.log(err)) * ``` * * If the specified Textract job is not marked as SUCCEEDED or the AWS operations fail * to return the results then the Promise will be rejected. * * **NOTE**: This method will try and retrieve all the results for the Textract job and * process them in memory. For extremely large documents then memory may become an issue. * * @param client the AWS client to use for retrieving the Textract results * @param jobId the id of the Textract job for which we want to parse the results * @returns Promise for a document that acts as the root node for the processed tree */ TextractParser.prototype.parseGetTextDetection = function (textract, jobId) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { return [2 /*return*/, this.getGetTextDetectionResponse(textract, jobId) .then(function (request) { return _this.factory.process(request); })]; }); }); }; /** @hidden */ TextractParser.prototype.getGetTextDetectionResponse = function (textract, jobId, nextToken) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { return [2 /*return*/, textract.getDocumentTextDetection({ JobId: jobId, NextToken: nextToken }).promise() .then(function (response) { if (response.JobStatus !== 'SUCCEEDED') { throw new Error("Job status is " + response.JobStatus + " only SUCCEEDED jobs can be processed"); } else if (response.NextToken !== undefined) { return _this.getGetTextDetectionResponse(textract, jobId, response.NextToken) .then(function (otherResponse) { var _a, _b; return { DocumentMetadata: response.DocumentMetadata, Blocks: (_a = response.Blocks, (_a !== null && _a !== void 0 ? _a : [])).concat((_b = otherResponse.Blocks, (_b !== null && _b !== void 0 ? _b : []))) }; }); } else { return response; } })]; }); }); }; return TextractParser; }()); exports.TextractParser = TextractParser; var types_1 = require("./types"); exports.BlockType = types_1.BlockType; var Geometry_1 = require("./model/Geometry"); exports.Geometry = Geometry_1.Geometry; exports.BoundaryBox = Geometry_1.BoundaryBox; exports.Point = Geometry_1.Point; exports.default = new TextractParser(factory_1.default);