mindee 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +11 -1
  2. package/README.md +15 -11
  3. package/bin/mindee.d.ts +2 -0
  4. package/bin/mindee.js +5 -0
  5. package/package.json +68 -68
  6. package/{dist/src → src}/api/endpoint.d.ts +4 -1
  7. package/{dist/src → src}/api/endpoint.js +20 -21
  8. package/src/api/index.d.ts +2 -0
  9. package/{dist/src → src}/api/index.js +3 -1
  10. package/{dist/src → src}/api/response.d.ts +5 -2
  11. package/{dist/src → src}/api/response.js +19 -5
  12. package/{dist/src → src}/cli.d.ts +0 -0
  13. package/src/cli.js +125 -0
  14. package/{dist/src → src}/client.d.ts +1 -0
  15. package/{dist/src → src}/client.js +39 -46
  16. package/{dist/src → src}/constants.d.ts +0 -0
  17. package/{dist/src → src}/constants.js +6 -0
  18. package/src/documents/cropper.d.ts +7 -0
  19. package/src/documents/cropper.js +31 -0
  20. package/{dist/src → src}/documents/custom.d.ts +2 -2
  21. package/{dist/src → src}/documents/custom.js +4 -4
  22. package/src/documents/document.d.ts +42 -0
  23. package/{dist/src → src}/documents/document.js +24 -14
  24. package/{dist/src → src}/documents/documentConfig.d.ts +6 -2
  25. package/{dist/src → src}/documents/documentConfig.js +29 -39
  26. package/{dist/src → src}/documents/financialDocument.d.ts +2 -9
  27. package/{dist/src → src}/documents/financialDocument.js +14 -13
  28. package/{dist/src → src}/documents/index.d.ts +3 -1
  29. package/{dist/src → src}/documents/index.js +4 -1
  30. package/{dist/src → src}/documents/invoice.d.ts +2 -9
  31. package/{dist/src → src}/documents/invoice.js +3 -15
  32. package/{dist/src → src}/documents/passport.d.ts +1 -7
  33. package/{dist/src → src}/documents/passport.js +13 -19
  34. package/src/documents/receipt.d.ts +17 -0
  35. package/{dist/src → src}/documents/receipt.js +4 -16
  36. package/{dist/src → src}/errors/handler.d.ts +0 -0
  37. package/{dist/src → src}/errors/handler.js +0 -0
  38. package/{dist/src → src}/fields/amount.d.ts +0 -0
  39. package/{dist/src → src}/fields/amount.js +0 -0
  40. package/{dist/src → src}/fields/companyRegistration.d.ts +0 -0
  41. package/{dist/src → src}/fields/companyRegistration.js +0 -0
  42. package/src/fields/cropper.d.ts +16 -0
  43. package/src/fields/cropper.js +18 -0
  44. package/{dist/src → src}/fields/customDocs.d.ts +2 -2
  45. package/{dist/src → src}/fields/customDocs.js +4 -4
  46. package/{dist/src → src}/fields/date.d.ts +0 -0
  47. package/{dist/src → src}/fields/date.js +0 -0
  48. package/{dist/src → src}/fields/field.d.ts +10 -11
  49. package/{dist/src → src}/fields/field.js +4 -3
  50. package/{dist/src → src}/fields/fullText.d.ts +0 -0
  51. package/{dist/src → src}/fields/fullText.js +0 -0
  52. package/{dist/src → src}/fields/index.d.ts +4 -4
  53. package/{dist/src → src}/fields/index.js +6 -5
  54. package/{dist/src → src}/fields/locale.d.ts +0 -0
  55. package/{dist/src → src}/fields/locale.js +0 -0
  56. package/{dist/src → src}/fields/orientation.d.ts +10 -3
  57. package/{dist/src → src}/fields/orientation.js +9 -7
  58. package/{dist/src → src}/fields/paymentDetails.d.ts +0 -0
  59. package/{dist/src → src}/fields/paymentDetails.js +0 -0
  60. package/{dist/src → src}/fields/tax.d.ts +0 -0
  61. package/{dist/src → src}/fields/tax.js +1 -2
  62. package/{dist/src → src}/geometry.d.ts +0 -0
  63. package/{dist/src → src}/geometry.js +0 -0
  64. package/{dist/src → src}/index.d.ts +1 -1
  65. package/{dist/src → src}/index.js +2 -1
  66. package/{dist/src → src}/inputs.d.ts +0 -0
  67. package/src/inputs.js +196 -0
  68. package/{dist/src → src}/logger.d.ts +0 -0
  69. package/{dist/src → src}/logger.js +0 -0
  70. package/bin/mindee +0 -3
  71. package/dist/package.json +0 -70
  72. package/dist/src/api/index.d.ts +0 -2
  73. package/dist/src/cli.js +0 -117
  74. package/dist/src/documents/document.d.ts +0 -38
  75. package/dist/src/documents/receipt.d.ts +0 -24
  76. package/dist/src/inputs.js +0 -223
package/src/inputs.js ADDED
@@ -0,0 +1,196 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.BytesInput = exports.StreamInput = exports.Base64Input = exports.PathInput = exports.Input = exports.INPUT_TYPE_PATH = exports.INPUT_TYPE_BYTES = exports.INPUT_TYPE_BASE64 = exports.INPUT_TYPE_STREAM = void 0;
27
+ const fs_1 = require("fs");
28
+ const path = __importStar(require("path"));
29
+ const fileType = __importStar(require("file-type"));
30
+ const handler_1 = require("./errors/handler");
31
+ const pdf_lib_1 = require("pdf-lib");
32
+ const node_buffer_1 = require("node:buffer");
33
+ const logger_1 = require("./logger");
34
+ exports.INPUT_TYPE_STREAM = "stream";
35
+ exports.INPUT_TYPE_BASE64 = "base64";
36
+ exports.INPUT_TYPE_BYTES = "bytes";
37
+ exports.INPUT_TYPE_PATH = "path";
38
+ const MIMETYPES = new Map([
39
+ [".pdf", "application/pdf"],
40
+ [".heic", "image/heic"],
41
+ [".jpg", "image/jpeg"],
42
+ [".jpeg", "image/jpeg"],
43
+ [".png", "image/png"],
44
+ [".tif", "image/tiff"],
45
+ [".tiff", "image/tiff"],
46
+ [".webp", "image/webp"],
47
+ ]);
48
+ const ALLOWED_INPUT_TYPES = [
49
+ exports.INPUT_TYPE_STREAM,
50
+ exports.INPUT_TYPE_BASE64,
51
+ exports.INPUT_TYPE_BYTES,
52
+ exports.INPUT_TYPE_PATH,
53
+ ];
54
+ class Input {
55
+ /**
56
+ * @param {String} inputType - the type of input used in file ("base64", "path", "dummy").
57
+ * NB: dummy is only used for tests purposes
58
+ * @param {Boolean} cutPages
59
+ * NB: Because of async calls, init() should be called after creating the object
60
+ */
61
+ constructor({ inputType }) {
62
+ this.MAX_DOC_PAGES = 3;
63
+ this.filename = "";
64
+ this.mimeType = "";
65
+ this.fileObject = node_buffer_1.Buffer.alloc(0);
66
+ // Check if inputType is valid
67
+ if (!ALLOWED_INPUT_TYPES.includes(inputType)) {
68
+ const allowed = Array.from(MIMETYPES.keys()).join(", ");
69
+ handler_1.errorHandler.throw(new Error(`Invalid input type, must be one of ${allowed}.`));
70
+ }
71
+ this.inputType = inputType;
72
+ logger_1.logger.debug(`Loading file from: ${inputType}`);
73
+ }
74
+ async init() {
75
+ throw new Error("not Implemented");
76
+ }
77
+ isPdf() {
78
+ return this.mimeType === "application/pdf";
79
+ }
80
+ async checkMimetype() {
81
+ let mimeType;
82
+ const fileExt = path.extname(this.filename);
83
+ if (fileExt) {
84
+ mimeType = MIMETYPES.get(fileExt.toLowerCase()) || "";
85
+ }
86
+ else {
87
+ const guess = await fileType.fromBuffer(this.fileObject);
88
+ if (guess !== undefined) {
89
+ mimeType = guess.mime;
90
+ }
91
+ else {
92
+ throw "Could not determine the MIME type of the file";
93
+ }
94
+ }
95
+ if (!mimeType) {
96
+ const allowed = Array.from(MIMETYPES.keys()).join(", ");
97
+ const err = new Error(`Invalid file type, must be one of ${allowed}.`);
98
+ handler_1.errorHandler.throw(err);
99
+ }
100
+ logger_1.logger.debug(`File is of type: ${mimeType}`);
101
+ return mimeType;
102
+ }
103
+ async countPages() {
104
+ const pdfDocument = await pdf_lib_1.PDFDocument.load(this.fileObject, {
105
+ ignoreEncryption: true,
106
+ });
107
+ return pdfDocument.getPageCount();
108
+ }
109
+ /** Merge PDF pages */
110
+ async cutPdf() {
111
+ const currentPdf = await pdf_lib_1.PDFDocument.load(this.fileObject, {
112
+ ignoreEncryption: true,
113
+ });
114
+ const pdfLength = currentPdf.getPageCount();
115
+ if (pdfLength <= this.MAX_DOC_PAGES) {
116
+ return;
117
+ }
118
+ const newPdf = await pdf_lib_1.PDFDocument.create();
119
+ const pagesNumbers = [0, pdfLength - 2, pdfLength - 1].slice(0, this.MAX_DOC_PAGES);
120
+ logger_1.logger.debug(`Cutting PDF, keeping pages: ${pagesNumbers}`);
121
+ const pages = await newPdf.copyPages(currentPdf, pagesNumbers);
122
+ pages.forEach((page) => newPdf.addPage(page));
123
+ const data = await newPdf.save();
124
+ this.fileObject = node_buffer_1.Buffer.from(data);
125
+ }
126
+ }
127
+ exports.Input = Input;
128
+ class PathInput extends Input {
129
+ constructor({ inputPath }) {
130
+ super({
131
+ inputType: exports.INPUT_TYPE_PATH,
132
+ });
133
+ this.inputPath = inputPath;
134
+ this.filename = path.basename(this.inputPath);
135
+ }
136
+ async init() {
137
+ logger_1.logger.debug(`Loading from: ${this.inputPath}`);
138
+ this.fileObject = node_buffer_1.Buffer.from(await fs_1.promises.readFile(this.inputPath));
139
+ this.mimeType = await this.checkMimetype();
140
+ }
141
+ }
142
+ exports.PathInput = PathInput;
143
+ class Base64Input extends Input {
144
+ constructor({ inputString, filename }) {
145
+ super({
146
+ inputType: exports.INPUT_TYPE_BASE64,
147
+ });
148
+ this.filename = filename;
149
+ this.inputString = inputString;
150
+ }
151
+ async init() {
152
+ this.fileObject = node_buffer_1.Buffer.from(this.inputString, "base64");
153
+ this.mimeType = await this.checkMimetype();
154
+ // clear out the string
155
+ this.inputString = "";
156
+ }
157
+ }
158
+ exports.Base64Input = Base64Input;
159
+ class StreamInput extends Input {
160
+ constructor({ inputStream, filename }) {
161
+ super({
162
+ inputType: exports.INPUT_TYPE_STREAM,
163
+ });
164
+ this.filename = filename;
165
+ this.inputStream = inputStream;
166
+ }
167
+ async init() {
168
+ this.fileObject = await this.stream2buffer(this.inputStream);
169
+ this.mimeType = await this.checkMimetype();
170
+ }
171
+ async stream2buffer(stream) {
172
+ return new Promise((resolve, reject) => {
173
+ const _buf = Array();
174
+ stream.on("data", (chunk) => _buf.push(chunk));
175
+ stream.on("end", () => resolve(node_buffer_1.Buffer.concat(_buf)));
176
+ stream.on("error", (err) => reject(`Error converting stream - ${err}`));
177
+ });
178
+ }
179
+ }
180
+ exports.StreamInput = StreamInput;
181
+ class BytesInput extends Input {
182
+ constructor({ inputBytes, filename }) {
183
+ super({
184
+ inputType: exports.INPUT_TYPE_BYTES,
185
+ });
186
+ this.filename = filename;
187
+ this.inputBytes = inputBytes;
188
+ }
189
+ async init() {
190
+ this.fileObject = node_buffer_1.Buffer.from(this.inputBytes, "hex");
191
+ this.mimeType = await this.checkMimetype();
192
+ // clear out the string
193
+ this.inputBytes = "";
194
+ }
195
+ }
196
+ exports.BytesInput = BytesInput;
File without changes
File without changes
package/bin/mindee DELETED
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- require('../dist/src/cli').cli();
package/dist/package.json DELETED
@@ -1,70 +0,0 @@
1
- {
2
- "name": "mindee",
3
- "version": "2.0.0",
4
- "description": "Mindee Client Library for Node.js",
5
- "main": "src/index.js",
6
- "license": "MIT",
7
- "scripts": {
8
- "build": "tsc --build",
9
- "clean": "rm -rf ./dist",
10
- "test": "mocha 'tests/**/*.spec.ts'",
11
- "lint-fix": "eslint 'src/**/*.ts' --fix",
12
- "lint": "eslint 'src/**/*.ts' --report-unused-disable-directives && echo 'Your .ts files look good.'",
13
- "docs": "jsdoc -r src -d docs"
14
- },
15
- "files": [
16
- "dist/",
17
- "bin/",
18
- "LICENSE",
19
- "README.md",
20
- "CHANGELOG.md"
21
- ],
22
- "engines": {
23
- "node": ">= 14.0.0"
24
- },
25
- "repository": {
26
- "type": "git",
27
- "url": "git+https://github.com/mindee/mindee-api-nodejs.git"
28
- },
29
- "author": {
30
- "name": "Mindee",
31
- "email": "devrel@mindee.com",
32
- "url": "https://mindee.com/"
33
- },
34
- "bugs": {
35
- "url": "https://github.com/mindee/mindee-api-nodejs/issues"
36
- },
37
- "homepage": "https://mindee.com/",
38
- "devDependencies": {
39
- "@tsconfig/node16": "^1.0.3",
40
- "@types/chai": "^4.3.1",
41
- "@types/mocha": "^9.1.1",
42
- "@types/node": "^17.0.38",
43
- "@typescript-eslint/eslint-plugin": "^5.30.0",
44
- "@typescript-eslint/parser": "^5.30.0",
45
- "chai": "^4.3.6",
46
- "eslint": "^8.18.0",
47
- "eslint-config-prettier": "^8.5.0",
48
- "eslint-plugin-prettier": "^4.1.0",
49
- "jsdoc": "^3.6.10",
50
- "mocha": "^10.0.0",
51
- "prettier": "^2.7.1",
52
- "ts-node": "^10.8.1",
53
- "typescript": "^4.7.4"
54
- },
55
- "dependencies": {
56
- "commander": "^9.4.0",
57
- "file-type": "^16.5.4",
58
- "form-data": "^3.0.1",
59
- "mrz": "^3.1.4",
60
- "pdf-lib": "^1.17.1"
61
- },
62
- "keywords": [
63
- "typescript",
64
- "mindee",
65
- "api",
66
- "client",
67
- "client library",
68
- "nodejs"
69
- ]
70
- }
@@ -1,2 +0,0 @@
1
- export { Response, InvoiceResponse, ReceiptResponse, FinancialDocResponse, PassportResponse, CustomResponse, } from "./response";
2
- export { Endpoint, InvoiceEndpoint, ReceiptEndpoint, PassportEndpoint, CustomEndpoint, STANDARD_API_OWNER, API_KEY_ENVVAR_NAME, } from "./endpoint";
package/dist/src/cli.js DELETED
@@ -1,117 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.cli = void 0;
13
- const commander_1 = require("commander");
14
- const documents_1 = require("./documents");
15
- const api_1 = require("./api");
16
- const client_1 = require("./client");
17
- const constants_1 = require("./constants");
18
- const program = new commander_1.Command();
19
- const COMMAND_INVOICE = "invoice";
20
- const COMMAND_RECEIPT = "receipt";
21
- const COMMAND_PASSPORT = "passport";
22
- const COMMAND_FINANCIAL = "financial";
23
- const COMMAND_CUSTOM = "custom";
24
- const CLI_COMMAND_CONFIG = new Map([
25
- [COMMAND_INVOICE, constants_1.ProductConfigs.getByDocType(documents_1.DOC_TYPE_INVOICE)],
26
- [COMMAND_RECEIPT, constants_1.ProductConfigs.getByDocType(documents_1.DOC_TYPE_RECEIPT)],
27
- [COMMAND_PASSPORT, constants_1.ProductConfigs.getByDocType(documents_1.DOC_TYPE_PASSPORT)],
28
- [COMMAND_FINANCIAL, constants_1.ProductConfigs.getByDocType(documents_1.DOC_TYPE_FINANCIAL)],
29
- [COMMAND_CUSTOM, constants_1.ProductConfigs.getByDocType(documents_1.DOC_TYPE_CUSTOM)],
30
- ]);
31
- function predictCall(command, inputPath, options) {
32
- return __awaiter(this, void 0, void 0, function* () {
33
- const conf = CLI_COMMAND_CONFIG.get(command);
34
- if (conf === undefined) {
35
- throw new Error(`Invalid document type ${command}`);
36
- }
37
- const mindeeClient = new client_1.Client({
38
- apiKey: options.apiKey,
39
- debug: options.debug,
40
- });
41
- if (command === COMMAND_CUSTOM) {
42
- mindeeClient.addEndpoint({
43
- accountName: options.user,
44
- documentType: options.documentType,
45
- });
46
- }
47
- const doc = mindeeClient.docFromPath(inputPath);
48
- const params = {
49
- docType: command === COMMAND_CUSTOM ? options.documentType : conf.docType,
50
- username: command === COMMAND_CUSTOM ? options.user : api_1.STANDARD_API_OWNER,
51
- cutPages: options.cutPages,
52
- fullText: options.fullText,
53
- };
54
- // Tried setting the response by using the responseClass property in constants.PRODUCTS_CONFIG
55
- // This compiled, but threw an exception:
56
- // TypeError: responseType is not a constructor
57
- //
58
- // So using a switch to explicitly set the response class parameter. Ugly, but works.
59
- // Improvements welcome!
60
- let response;
61
- switch (command) {
62
- case COMMAND_INVOICE:
63
- response = yield doc.parse(api_1.InvoiceResponse, params);
64
- break;
65
- case COMMAND_RECEIPT:
66
- response = yield doc.parse(api_1.ReceiptResponse, params);
67
- break;
68
- case COMMAND_FINANCIAL:
69
- response = yield doc.parse(api_1.FinancialDocResponse, params);
70
- break;
71
- case COMMAND_PASSPORT:
72
- response = yield doc.parse(api_1.PassportResponse, params);
73
- break;
74
- case COMMAND_CUSTOM:
75
- response = yield doc.parse(api_1.CustomResponse, params);
76
- break;
77
- default:
78
- throw `Unhandled command: ${command}`;
79
- }
80
- if (response.document) {
81
- console.log(`\n${response.document}`);
82
- }
83
- });
84
- }
85
- function cli() {
86
- program.name("mindee");
87
- program.option("-d, --debug", "high verbosity mode");
88
- CLI_COMMAND_CONFIG.forEach((info, name) => {
89
- const prog = program.command(name);
90
- prog.description(info.description);
91
- prog.option("-k, --api-key <api_key>", "API key for document endpoint");
92
- prog.option("-C, --no-cut-pages", "Don't cut document pages");
93
- if (info.fullText) {
94
- prog.option("-t, --full-text", "Include full document text in response");
95
- }
96
- if (name === COMMAND_CUSTOM) {
97
- prog.requiredOption("-u, --user <username>", "API account name for the endpoint");
98
- prog.option("-v, --version <version>", "API account name for the endpoint");
99
- prog.argument("<endpoint_name>", "API endpoint name");
100
- }
101
- prog.argument("<input_path>", "Full path to the file");
102
- if (name === COMMAND_CUSTOM) {
103
- prog.action((endpointName, inputPath, options, command) => {
104
- const allOptions = Object.assign(Object.assign(Object.assign({}, program.opts()), options), { documentType: endpointName });
105
- predictCall(command.name(), inputPath, allOptions);
106
- });
107
- }
108
- else {
109
- prog.action((inputPath, options, command) => {
110
- const allOptions = Object.assign(Object.assign(Object.assign({}, program.opts()), options), { endpointName: undefined });
111
- predictCall(command.name(), inputPath, allOptions);
112
- });
113
- }
114
- });
115
- program.parse(process.argv);
116
- }
117
- exports.cli = cli;
@@ -1,38 +0,0 @@
1
- import { Input } from "../inputs";
2
- import { FullText } from "../fields";
3
- export interface DocumentConstructorProps {
4
- apiPrediction: {
5
- [index: string]: any;
6
- };
7
- inputFile?: Input;
8
- pageId?: number;
9
- fullText?: FullText;
10
- }
11
- export declare class Document {
12
- checklist: {
13
- [index: string]: boolean;
14
- };
15
- mimeType: string | undefined;
16
- filename: string;
17
- filepath: string | undefined;
18
- fullText?: FullText;
19
- pageId?: number | undefined;
20
- /**
21
- * Takes a list of Documents and return one Document where
22
- * each field is set with the maximum probability field
23
- * @param {Input} inputFile - input file given to parse the document
24
- * @param {number} pageId - Page ID for multi-page document
25
- * @param {FullText} fullText - full OCR extracted text
26
- */
27
- constructor(inputFile?: Input, pageId?: number, fullText?: FullText);
28
- clone(): any;
29
- /** return true if all checklist of the document if true */
30
- checkAll(): boolean;
31
- /**
32
- * Takes a list of Documents and return one Document where
33
- * each field is set with the maximum probability field
34
- * @param {Array<Document>} documents - A list of Documents
35
- */
36
- static mergePages(documents: any): any;
37
- static cleanOutString(outStr: string): string;
38
- }
@@ -1,24 +0,0 @@
1
- import { Document, DocumentConstructorProps } from "./document";
2
- import { TaxField, Field, Amount, Locale, Orientation, DateField } from "../fields";
3
- export declare class Receipt extends Document {
4
- #private;
5
- locale: Locale;
6
- totalIncl: Amount;
7
- date: DateField;
8
- /** Receipt category as seen on the receipt. */
9
- category: Field;
10
- merchantName: Field;
11
- time: Field;
12
- orientation: Orientation | undefined;
13
- totalTax: Amount;
14
- totalExcl: Amount;
15
- taxes: TaxField[];
16
- /**
17
- * @param {Object} apiPrediction - Json parsed prediction from HTTP response
18
- * @param {Input} inputFile - input file given to parse the document
19
- * @param {number} pageId - Page ID for multi-page document
20
- * @param {FullText} fullText - full OCR extracted text
21
- */
22
- constructor({ apiPrediction, inputFile, fullText, pageId, }: DocumentConstructorProps);
23
- toString(): string;
24
- }
@@ -1,223 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
- Object.defineProperty(exports, "__esModule", { value: true });
35
- exports.BytesInput = exports.StreamInput = exports.Base64Input = exports.PathInput = exports.Input = exports.INPUT_TYPE_PATH = exports.INPUT_TYPE_BYTES = exports.INPUT_TYPE_BASE64 = exports.INPUT_TYPE_STREAM = void 0;
36
- const fs_1 = require("fs");
37
- const path = __importStar(require("path"));
38
- const fileType = __importStar(require("file-type"));
39
- const handler_1 = require("./errors/handler");
40
- const pdf_lib_1 = require("pdf-lib");
41
- const node_buffer_1 = require("node:buffer");
42
- const logger_1 = require("./logger");
43
- exports.INPUT_TYPE_STREAM = "stream";
44
- exports.INPUT_TYPE_BASE64 = "base64";
45
- exports.INPUT_TYPE_BYTES = "bytes";
46
- exports.INPUT_TYPE_PATH = "path";
47
- const MIMETYPES = new Map([
48
- [".pdf", "application/pdf"],
49
- [".heic", "image/heic"],
50
- [".jpg", "image/jpeg"],
51
- [".jpeg", "image/jpeg"],
52
- [".png", "image/png"],
53
- [".tif", "image/tiff"],
54
- [".tiff", "image/tiff"],
55
- [".webp", "image/webp"],
56
- ]);
57
- const ALLOWED_INPUT_TYPES = [
58
- exports.INPUT_TYPE_STREAM,
59
- exports.INPUT_TYPE_BASE64,
60
- exports.INPUT_TYPE_BYTES,
61
- exports.INPUT_TYPE_PATH,
62
- ];
63
- class Input {
64
- /**
65
- * @param {String} inputType - the type of input used in file ("base64", "path", "dummy").
66
- * NB: dummy is only used for tests purposes
67
- * @param {Boolean} cutPages
68
- * NB: Because of async calls, init() should be called after creating the object
69
- */
70
- constructor({ inputType }) {
71
- this.MAX_DOC_PAGES = 3;
72
- this.filename = "";
73
- this.mimeType = "";
74
- this.fileObject = node_buffer_1.Buffer.alloc(0);
75
- // Check if inputType is valid
76
- if (!ALLOWED_INPUT_TYPES.includes(inputType)) {
77
- const allowed = Array.from(MIMETYPES.keys()).join(", ");
78
- handler_1.errorHandler.throw(new Error(`Invalid input type, must be one of ${allowed}.`));
79
- }
80
- this.inputType = inputType;
81
- logger_1.logger.debug(`Loading file from: ${inputType}`);
82
- }
83
- init() {
84
- return __awaiter(this, void 0, void 0, function* () {
85
- throw new Error("not Implemented");
86
- });
87
- }
88
- isPdf() {
89
- return this.mimeType === "application/pdf";
90
- }
91
- checkMimetype() {
92
- return __awaiter(this, void 0, void 0, function* () {
93
- let mimeType;
94
- const fileExt = path.extname(this.filename);
95
- if (fileExt) {
96
- mimeType = MIMETYPES.get(fileExt.toLowerCase()) || "";
97
- }
98
- else {
99
- const guess = yield fileType.fromBuffer(this.fileObject);
100
- if (guess !== undefined) {
101
- mimeType = guess.mime;
102
- }
103
- else {
104
- throw "Could not determine the MIME type of the file";
105
- }
106
- }
107
- if (!mimeType) {
108
- const allowed = Array.from(MIMETYPES.keys()).join(", ");
109
- const err = new Error(`Invalid file type, must be one of ${allowed}.`);
110
- handler_1.errorHandler.throw(err);
111
- }
112
- logger_1.logger.debug(`File is of type: ${mimeType}`);
113
- return mimeType;
114
- });
115
- }
116
- countPages() {
117
- return __awaiter(this, void 0, void 0, function* () {
118
- const pdfDocument = yield pdf_lib_1.PDFDocument.load(this.fileObject, {
119
- ignoreEncryption: true,
120
- });
121
- return pdfDocument.getPageCount();
122
- });
123
- }
124
- /** Merge PDF pages */
125
- cutPdf() {
126
- return __awaiter(this, void 0, void 0, function* () {
127
- const currentPdf = yield pdf_lib_1.PDFDocument.load(this.fileObject, {
128
- ignoreEncryption: true,
129
- });
130
- const pdfLength = currentPdf.getPageCount();
131
- if (pdfLength <= this.MAX_DOC_PAGES) {
132
- return;
133
- }
134
- const newPdf = yield pdf_lib_1.PDFDocument.create();
135
- const pagesNumbers = [0, pdfLength - 2, pdfLength - 1].slice(0, this.MAX_DOC_PAGES);
136
- logger_1.logger.debug(`Cutting PDF, keeping pages: ${pagesNumbers}`);
137
- const pages = yield newPdf.copyPages(currentPdf, pagesNumbers);
138
- pages.forEach((page) => newPdf.addPage(page));
139
- const data = yield newPdf.save();
140
- this.fileObject = node_buffer_1.Buffer.from(data);
141
- });
142
- }
143
- }
144
- exports.Input = Input;
145
- class PathInput extends Input {
146
- constructor({ inputPath }) {
147
- super({
148
- inputType: exports.INPUT_TYPE_PATH,
149
- });
150
- this.inputPath = inputPath;
151
- this.filename = path.basename(this.inputPath);
152
- }
153
- init() {
154
- return __awaiter(this, void 0, void 0, function* () {
155
- logger_1.logger.debug(`Loading from: ${this.inputPath}`);
156
- this.fileObject = node_buffer_1.Buffer.from(yield fs_1.promises.readFile(this.inputPath));
157
- this.mimeType = yield this.checkMimetype();
158
- });
159
- }
160
- }
161
- exports.PathInput = PathInput;
162
- class Base64Input extends Input {
163
- constructor({ inputString, filename }) {
164
- super({
165
- inputType: exports.INPUT_TYPE_BASE64,
166
- });
167
- this.filename = filename;
168
- this.inputString = inputString;
169
- }
170
- init() {
171
- return __awaiter(this, void 0, void 0, function* () {
172
- this.fileObject = node_buffer_1.Buffer.from(this.inputString, "base64");
173
- this.mimeType = yield this.checkMimetype();
174
- // clear out the string
175
- this.inputString = "";
176
- });
177
- }
178
- }
179
- exports.Base64Input = Base64Input;
180
- class StreamInput extends Input {
181
- constructor({ inputStream, filename }) {
182
- super({
183
- inputType: exports.INPUT_TYPE_STREAM,
184
- });
185
- this.filename = filename;
186
- this.inputStream = inputStream;
187
- }
188
- init() {
189
- return __awaiter(this, void 0, void 0, function* () {
190
- this.fileObject = yield this.stream2buffer(this.inputStream);
191
- this.mimeType = yield this.checkMimetype();
192
- });
193
- }
194
- stream2buffer(stream) {
195
- return __awaiter(this, void 0, void 0, function* () {
196
- return new Promise((resolve, reject) => {
197
- const _buf = Array();
198
- stream.on("data", (chunk) => _buf.push(chunk));
199
- stream.on("end", () => resolve(node_buffer_1.Buffer.concat(_buf)));
200
- stream.on("error", (err) => reject(`Error converting stream - ${err}`));
201
- });
202
- });
203
- }
204
- }
205
- exports.StreamInput = StreamInput;
206
- class BytesInput extends Input {
207
- constructor({ inputBytes, filename }) {
208
- super({
209
- inputType: exports.INPUT_TYPE_BYTES,
210
- });
211
- this.filename = filename;
212
- this.inputBytes = inputBytes;
213
- }
214
- init() {
215
- return __awaiter(this, void 0, void 0, function* () {
216
- this.fileObject = node_buffer_1.Buffer.from(this.inputBytes, "hex");
217
- this.mimeType = yield this.checkMimetype();
218
- // clear out the string
219
- this.inputBytes = "";
220
- });
221
- }
222
- }
223
- exports.BytesInput = BytesInput;