mindee 1.0.6 → 1.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 (55) hide show
  1. package/.nyc_output/f57ba3bc-1777-4ecc-81e1-230327c2a401.json +1 -0
  2. package/.nyc_output/processinfo/f57ba3bc-1777-4ecc-81e1-230327c2a401.json +1 -0
  3. package/.nyc_output/processinfo/index.json +1 -0
  4. package/CHANGELOG.md +37 -2
  5. package/LICENSE +202 -0
  6. package/README.md +1 -1
  7. package/coverage/coverage.json +1 -0
  8. package/coverage/lcov-report/base.css +224 -0
  9. package/coverage/lcov-report/block-navigation.js +79 -0
  10. package/coverage/lcov-report/favicon.png +0 -0
  11. package/coverage/lcov-report/index.html +171 -0
  12. package/coverage/lcov-report/prettify.css +1 -0
  13. package/coverage/lcov-report/prettify.js +2 -0
  14. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  15. package/coverage/lcov-report/sorter.js +170 -0
  16. package/coverage/lcov.info +1595 -0
  17. package/coverage.lcov +1595 -0
  18. package/lib/api/financialDocument.js +5 -5
  19. package/lib/api/invoice.js +3 -3
  20. package/lib/api/object.js +2 -2
  21. package/lib/api/receipt.js +3 -3
  22. package/lib/api/request.js +12 -6
  23. package/lib/api/response.js +8 -3
  24. package/lib/documents/document.js +5 -1
  25. package/lib/documents/fields/field.js +1 -1
  26. package/lib/documents/financialDocument.js +36 -28
  27. package/lib/documents/invoice.js +49 -31
  28. package/lib/documents/receipt.js +40 -25
  29. package/lib/inputs.js +78 -24
  30. package/mindee/api/financialDocument.js +47 -0
  31. package/mindee/api/index.js +5 -0
  32. package/mindee/api/invoice.js +53 -0
  33. package/mindee/api/object.js +82 -0
  34. package/mindee/api/receipt.js +39 -0
  35. package/mindee/api/request.js +70 -0
  36. package/mindee/api/response.js +65 -0
  37. package/mindee/documents/document.js +69 -0
  38. package/mindee/documents/fields/amount.js +25 -0
  39. package/mindee/documents/fields/date.js +29 -0
  40. package/mindee/documents/fields/field.js +89 -0
  41. package/mindee/documents/fields/index.js +7 -0
  42. package/mindee/documents/fields/locale.js +30 -0
  43. package/mindee/documents/fields/orientation.js +24 -0
  44. package/mindee/documents/fields/paymentDetails.js +52 -0
  45. package/mindee/documents/fields/tax.js +47 -0
  46. package/mindee/documents/financialDocument.js +228 -0
  47. package/mindee/documents/index.js +5 -0
  48. package/mindee/documents/invoice.js +411 -0
  49. package/mindee/documents/receipt.js +287 -0
  50. package/mindee/errors/handler.js +16 -0
  51. package/mindee/index.js +36 -0
  52. package/mindee/inputs.js +156 -0
  53. package/mindee/logger.js +33 -0
  54. package/package.json +7 -3
  55. package/LICENSE.md +0 -674
package/lib/inputs.js CHANGED
@@ -16,11 +16,20 @@ var {
16
16
  PDFDocument
17
17
  } = require("pdf-lib");
18
18
 
19
+ var concat = require("concat-stream");
20
+
21
+ var {
22
+ Base64Encode
23
+ } = require("base64-stream");
24
+
25
+ var fileType = require("file-type");
26
+
27
+ var ArrayBufferEncode = require("base64-arraybuffer");
28
+
19
29
  class Input {
20
30
  /**
21
31
  * @param {(String | Buffer)} file - the file that will be read. Either path or base64 string, or a steam
22
32
  * @param {String} inputType - the type of input used in file ("base64", "path", "dummy").
23
- * NB: in case of base64 file, only jpeg file is supported
24
33
  * NB: dummy is only used for tests purposes
25
34
  * @param {String} filename - File name of the input
26
35
  * @param {Boolean} cut_pdf: Automatically reconstruct pdf with more than 4 pages
@@ -61,45 +70,60 @@ class Input {
61
70
  var _this = this;
62
71
 
63
72
  return _asyncToGenerator(function* () {
64
- if (_this.inputType === "base64") _this.initBase64();else if (_this.inputType === "path") yield _this.initFile();else if (_this.inputType === "stream") yield _this.initStream();else _this.initDummy();
73
+ if (_this.inputType === "base64") yield _this.initBase64();else if (_this.inputType === "path") yield _this.initFile();else if (_this.inputType === "stream") yield _this.initStream();else _this.initDummy();
65
74
  })();
66
75
  }
67
76
 
68
77
  initBase64() {
69
- this.fileObject = this.file;
70
- this.filepath = undefined;
71
- this.fileExtension = undefined;
78
+ var _this2 = this;
79
+
80
+ return _asyncToGenerator(function* () {
81
+ _this2.fileObject = _this2.file;
82
+ _this2.filepath = undefined;
83
+ _this2.fileExtension = undefined;
84
+
85
+ if (_this2.allowCutPdf == true) {
86
+ var typeOfFile = yield fileType.fromBuffer(Buffer.from(_this2.fileObject, "base64"));
87
+
88
+ if (typeOfFile === undefined) {
89
+ console.error("Cannot detect mime type of: ".concat(_this2.fileObject));
90
+ } else if (typeOfFile.mime === "application/pdf") {
91
+ yield _this2.cutPdf();
92
+ }
93
+ }
94
+ })();
72
95
  }
73
96
 
74
97
  initFile() {
75
- var _this2 = this;
98
+ var _this3 = this;
76
99
 
77
100
  return _asyncToGenerator(function* () {
78
- _this2.fileObject = yield fs.readFile(_this2.file);
79
- _this2.filepath = _this2.file;
80
- _this2.filename = _this2.filename || path.basename(_this2.file); // Check if file type is valid
101
+ _this3.fileObject = yield fs.readFile(_this3.file);
102
+ _this3.filepath = _this3.file;
103
+ _this3.filename = _this3.filename || path.basename(_this3.file); // Check if file type is valid
81
104
 
82
- var filetype = _this2.filename.split(".").pop();
105
+ var filetype = _this3.filename.split(".").pop();
83
106
 
84
- if (!(filetype in _this2.MIMETYPES)) {
85
- errorHandler.throw(new Error("File type is not allowed. It must be ".concat(Object.keys(_this2.MIMETYPES).toString())));
107
+ if (!(filetype in _this3.MIMETYPES)) {
108
+ errorHandler.throw(new Error("File type is not allowed. It must be ".concat(Object.keys(_this3.MIMETYPES).toString())));
86
109
  }
87
110
 
88
- _this2.fileExtension = _this2.MIMETYPES[filetype];
111
+ _this3.fileExtension = _this3.MIMETYPES[filetype];
89
112
 
90
- if (_this2.fileExtension === "application/pdf" && _this2.allowCutPdf == true) {
91
- yield _this2.cutPdf();
113
+ if (_this3.fileExtension === "application/pdf" && _this3.allowCutPdf == true) {
114
+ yield _this3.cutPdf();
92
115
  }
93
116
  })();
94
117
  }
95
118
 
96
119
  initStream() {
97
- var _this3 = this;
120
+ var _this4 = this;
98
121
 
99
122
  return _asyncToGenerator(function* () {
100
- _this3.fileObject = _this3.file;
101
- _this3.filename = _this3.filename || "stream";
102
- _this3.filepath = undefined;
123
+ var file = yield _this4.streamToBase64(_this4.file);
124
+ _this4.file = file;
125
+ _this4.inputType = "base64";
126
+ yield _this4.initBase64();
103
127
  })();
104
128
  }
105
129
 
@@ -109,23 +133,53 @@ class Input {
109
133
  this.filepath = "";
110
134
  this.fileExtension = "";
111
135
  }
136
+ /**
137
+ * Convert ReadableStream to Base64 encoded String
138
+ *
139
+ * @param {*} stream ReadableStream to encode
140
+ * @returns Base64 encoded String
141
+ */
142
+
143
+
144
+ streamToBase64(stream) {
145
+ return _asyncToGenerator(function* () {
146
+ return new Promise((resolve, reject) => {
147
+ var base64 = new Base64Encode();
148
+
149
+ var cbConcat = base64 => {
150
+ resolve(base64);
151
+ };
152
+
153
+ stream.pipe(base64).pipe(concat(cbConcat)).on("error", error => {
154
+ reject(error);
155
+ });
156
+ });
157
+ })();
158
+ }
112
159
  /** Cut PDF if pages > 5 */
113
160
 
114
161
 
115
162
  cutPdf() {
116
- var _this4 = this;
163
+ var _this5 = this;
117
164
 
118
165
  return _asyncToGenerator(function* () {
119
166
  // convert document to PDFDocument & cut CUT_PDF_SIZE - 1 first pages and last page
120
- var pdfDocument = yield PDFDocument.load(_this4.fileObject);
167
+ var pdfDocument = yield PDFDocument.load(_this5.fileObject, {
168
+ ignoreEncryption: true
169
+ });
121
170
  var splitedPdfDocument = yield PDFDocument.create();
122
171
  var pdfLength = pdfDocument.getPageCount();
123
- if (pdfLength <= _this4.CUT_PDF_SIZE) return;
124
- var pagesNumbers = [...Array(_this4.CUT_PDF_SIZE - 1).keys(), pdfLength - 1];
172
+ if (pdfLength <= _this5.CUT_PDF_SIZE) return;
173
+ var pagesNumbers = [...Array(_this5.CUT_PDF_SIZE - 1).keys(), pdfLength - 1];
125
174
  var pages = yield splitedPdfDocument.copyPages(pdfDocument, pagesNumbers);
126
175
  pages.forEach(page => splitedPdfDocument.addPage(page));
127
176
  var data = yield splitedPdfDocument.save();
128
- _this4.fileObject = Buffer.from(data);
177
+
178
+ if (_this5.inputType === "path") {
179
+ _this5.fileObject = Buffer.from(data);
180
+ } else if (_this5.inputType === "base64") {
181
+ _this5.fileObject = ArrayBufferEncode.encode(data);
182
+ }
129
183
  })();
130
184
  }
131
185
 
@@ -0,0 +1,47 @@
1
+ const APIObject = require("./object");
2
+ const Input = require("../inputs");
3
+
4
+ class APIFinancialDocument extends APIObject {
5
+ constructor(invoiceToken, receiptToken) {
6
+ super(undefined, "financialDocument");
7
+ this.invoiceToken = invoiceToken;
8
+ this.receiptToken = receiptToken;
9
+ }
10
+
11
+ /**
12
+ * @param {String} file: Receipt filepath (allowed jpg, png, tiff, pdf)
13
+ * @param {String} inputType: String in {'path', 'stream', 'base64'}
14
+ * @param {Boolean} includeWords: extract all words into http_response
15
+ * @param {String} version: expense_receipt api version
16
+ * @param {Boolean} cutPdf: Automatically reconstruct pdf with more than 4 pages
17
+ * @returns {Response} Wrapped response with Receipts objects parsed
18
+ */
19
+ async parse({
20
+ input,
21
+ inputType = "path",
22
+ filename = undefined,
23
+ version = "3",
24
+ cutPdf = true,
25
+ includeWords = false,
26
+ }) {
27
+ const inputFile = new Input({
28
+ file: input,
29
+ inputType: inputType,
30
+ filename: filename,
31
+ allowCutPdf: cutPdf,
32
+ });
33
+ await inputFile.init();
34
+ this.apiToken =
35
+ inputFile.fileExtension === "application/pdf"
36
+ ? this.invoiceToken
37
+ : this.receiptToken;
38
+ const url =
39
+ inputFile.fileExtension === "application/pdf"
40
+ ? "/invoices/v2/predict"
41
+ : "/expense_receipts/v3/predict";
42
+ super.parse();
43
+ return await super._request(url, inputFile, version, includeWords);
44
+ }
45
+ }
46
+
47
+ module.exports = APIFinancialDocument;
@@ -0,0 +1,5 @@
1
+ exports.APIObject = require("./object");
2
+ exports.APIReceipt = require("./receipt");
3
+ exports.Response = require("./response");
4
+ exports.Request = require("./response");
5
+ exports.Invoice = require("./invoice");
@@ -0,0 +1,53 @@
1
+ const APIObject = require("./object");
2
+ const Input = require("../inputs");
3
+
4
+ class APIInvoice extends APIObject {
5
+ constructor(apiToken = undefined) {
6
+ super(apiToken, "invoice");
7
+ this.baseUrl = `${this.baseUrl}/invoices/`;
8
+ }
9
+
10
+ /**
11
+ * @param {Boolean} includeWords: , extract all words into http_response
12
+ * @param {Boolean} cutPdf: Automatically reconstruct pdf with more than 4 pages
13
+ * @param {String} inputType: String in {'path', 'stream', 'base64'}
14
+ * @param {String} file: Receipt filepath (allowed jpg, png, tiff, pdf)
15
+ * @param {String} version: expense_receipt api version
16
+ * @returns {Response} Wrapped response with Receipts objects parsed
17
+ */
18
+ async parse({
19
+ input,
20
+ inputType = "path",
21
+ filename = undefined,
22
+ version = "2",
23
+ cutPdf = true,
24
+ includeWords = false,
25
+ }) {
26
+ super.parse();
27
+ const inputFile = new Input({
28
+ file: input,
29
+ inputType: inputType,
30
+ filename: filename,
31
+ allowCutPdf: cutPdf,
32
+ });
33
+ await inputFile.init();
34
+ const url = `v${version}/predict`;
35
+ return await super._request(url, inputFile, includeWords);
36
+ }
37
+
38
+ /**
39
+ @param {String} inputFile - Input object
40
+ @param {} response - HTTP response
41
+ @param {Document} documentType - Document class in {"Receipt", "Invoice", "Financial_document"}
42
+ @returns {Response}
43
+ */
44
+ wrapResponse(inputFile, response, documentType) {
45
+ let result = super.wrapResponse(inputFile, response, documentType);
46
+ result.documentType =
47
+ result.httpResponse.data?.predictions?.[0]?.document_type?.value?.toLowerCase() ||
48
+ result.documentType;
49
+ return result;
50
+ }
51
+ }
52
+
53
+ module.exports = APIInvoice;
@@ -0,0 +1,82 @@
1
+ const Response = require("./response");
2
+ const errorHandler = require("../errors/handler");
3
+ const request = require("./request");
4
+
5
+ /**
6
+ * Base class for APIs (APIReceipt & APIInvoice)
7
+ * @param {String} apiToken - Token of the API used for parsing document
8
+ * @param {String} apiName - Name of the API used for parsing document
9
+ */
10
+ class APIObject {
11
+ constructor(apiToken = undefined, apiName = "") {
12
+ this.apiToken = apiToken;
13
+ this.baseUrl = "https://api.mindee.net/v1/products/mindee/";
14
+ this.apiName = apiName;
15
+ }
16
+
17
+ /**
18
+ */
19
+ parse() {
20
+ if (!this.apiToken) {
21
+ errorHandler.throw({
22
+ error: new Error(
23
+ `Missing API token for ${this.apiName}. \
24
+ Have you create a mindee Client with a ${this.apiName}Token in parameters ?`
25
+ ),
26
+ });
27
+ }
28
+ }
29
+
30
+ /**
31
+ @param {String} url - API url for request
32
+ @param {Input} inputFile - input file for API
33
+ @param {Boolean} includeWords - Include Mindee vision words in Response
34
+ @returns {Response}
35
+ */
36
+ async _request(url, inputFile, includeWords = false) {
37
+ const headers = {
38
+ "X-Inferuser-Token": this.apiToken,
39
+ };
40
+ const response = await request(
41
+ `${this.baseUrl}${url}`,
42
+ "POST",
43
+ headers,
44
+ inputFile,
45
+ includeWords
46
+ );
47
+ return this.wrapResponse(inputFile, response, this.apiName);
48
+ }
49
+
50
+ /**
51
+ @param {String} inputFile - Input object
52
+ @param {} response - HTTP response
53
+ @param {Document} documentType - Document class in {"Receipt", "Invoice", "Financial_document"}
54
+ @returns {Response}
55
+ */
56
+ wrapResponse(inputFile, response, documentType) {
57
+ if (response.statusCode > 201) {
58
+ const errorMessage = JSON.stringify(response.data, null, 4);
59
+ errorHandler.throw(
60
+ new Error(
61
+ `${this.apiName} API ${response.statusCode} HTTP error: ${errorMessage}`
62
+ ),
63
+ false
64
+ );
65
+ return new Response({
66
+ httpResponse: response,
67
+ documentType: documentType,
68
+ document: undefined,
69
+ input: inputFile,
70
+ error: true,
71
+ });
72
+ }
73
+ return new Response({
74
+ httpResponse: response,
75
+ documentType: documentType,
76
+ document: inputFile,
77
+ input: inputFile,
78
+ });
79
+ }
80
+ }
81
+
82
+ module.exports = APIObject;
@@ -0,0 +1,39 @@
1
+ const APIObject = require("./object");
2
+ const Input = require("../inputs");
3
+
4
+ class APIReceipt extends APIObject {
5
+ constructor(apiToken = undefined) {
6
+ super(apiToken, "receipt");
7
+ this.baseUrl = `${this.baseUrl}/expense_receipts/`;
8
+ }
9
+
10
+ /**
11
+ * @param {String} file: Receipt filepath (allowed jpg, png, tiff, pdf)
12
+ * @param {String} inputType: String in {'path', 'stream', 'base64'}
13
+ * @param {Boolean} includeWords: extract all words into http_response
14
+ * @param {String} version: expense_receipt api version
15
+ * @param {Boolean} cutPdf: Automatically reconstruct pdf with more than 4 pages
16
+ * @returns {Response} Wrapped response with Receipts objects parsed
17
+ */
18
+ async parse({
19
+ input,
20
+ inputType = "path",
21
+ filename = undefined,
22
+ version = "3",
23
+ cutPdf = true,
24
+ includeWords = false,
25
+ }) {
26
+ super.parse();
27
+ const inputFile = new Input({
28
+ file: input,
29
+ inputType: inputType,
30
+ filename: filename,
31
+ allowCutPdf: cutPdf,
32
+ });
33
+ await inputFile.init();
34
+ const url = `v${version}/predict`;
35
+ return await super._request(url, inputFile, includeWords);
36
+ }
37
+ }
38
+
39
+ module.exports = APIReceipt;
@@ -0,0 +1,70 @@
1
+ const https = require("https");
2
+ const { version: sdkVersion } = require("../../package.json");
3
+ const { URL } = require("url");
4
+ const FormData = require("form-data");
5
+ const os = require("os");
6
+
7
+ const request = (url, method, headers, input, includeWords = false) => {
8
+ return new Promise(function (resolve, reject) {
9
+ const form = new FormData();
10
+ let body;
11
+
12
+ headers["User-Agent"] = `mindee-api-nodejs@v${sdkVersion} nodejs-${
13
+ process.version
14
+ } ${os.type().toLowerCase()}`;
15
+ if (["path", "stream"].includes(input.inputType)) {
16
+ const fileParams = { filename: input.filename };
17
+ form.append("document", input.fileObject, fileParams);
18
+ if (includeWords) form.append("include_mvision", "true");
19
+ headers = { ...headers, ...form.getHeaders() };
20
+ } else if (input.inputType === "base64") {
21
+ let body_obj = { document: input.fileObject };
22
+ if (includeWords) body_obj["include_mvision"] = "true";
23
+ body = JSON.stringify(body_obj);
24
+ headers["Content-Type"] = "application/json";
25
+ headers["Content-Length"] = body.length;
26
+ }
27
+
28
+ const uri = new URL(url);
29
+ const options = {
30
+ method: method,
31
+ headers: headers,
32
+ hostname: uri.hostname,
33
+ path: `${uri.pathname}${uri.search}`,
34
+ };
35
+
36
+ const req = https.request(options, function (res) {
37
+ let responseBody = [];
38
+
39
+ res.on("data", function (chunk) {
40
+ responseBody += chunk;
41
+ });
42
+
43
+ res.on("end", function () {
44
+ try {
45
+ resolve({
46
+ ...res,
47
+ data: JSON.parse(responseBody),
48
+ });
49
+ } catch (error) {
50
+ console.log(responseBody, error);
51
+ }
52
+ });
53
+ });
54
+
55
+ req.on("error", (err) => {
56
+ reject(err);
57
+ });
58
+
59
+ if (["path", "stream"].includes(input.inputType)) {
60
+ form.pipe(req);
61
+ }
62
+
63
+ if (input.inputType === "base64") {
64
+ req.write(body);
65
+ req.end();
66
+ }
67
+ });
68
+ };
69
+
70
+ module.exports = request;
@@ -0,0 +1,65 @@
1
+ const Document = require("../documents").document;
2
+ const Receipt = require("../documents").receipt;
3
+ const Invoice = require("../documents").invoice;
4
+ const FinancialDocument = require("../documents").financialDocument;
5
+ const fs = require("fs").promises;
6
+
7
+ class Response {
8
+ constructor({
9
+ httpResponse,
10
+ documentType,
11
+ input,
12
+ error,
13
+ reconsctruted = false,
14
+ ...args
15
+ }) {
16
+ this.httpResponse = httpResponse;
17
+ this.documentType = documentType;
18
+ this.input = input;
19
+ if (!error && !reconsctruted) this.formatResponse();
20
+ if (reconsctruted === true) {
21
+ Object.assign(this, args);
22
+ }
23
+ }
24
+
25
+ async dump(path) {
26
+ return await fs.writeFile(path, JSON.stringify(Object.entries(this)));
27
+ }
28
+
29
+ static async load(path) {
30
+ const file = fs.readFile(path);
31
+ const args = JSON.parse(file);
32
+ return new Response({ reconsctruted: true, ...args });
33
+ }
34
+
35
+ formatResponse() {
36
+ const constructors = {
37
+ receipt: (params) => new Receipt(params),
38
+ invoice: (params) => new Invoice(params),
39
+ financialDocument: (params) => new FinancialDocument(params),
40
+ };
41
+ const predictions = this.httpResponse.data.document.inference.pages.entries();
42
+ this[`${this.documentType}s`] = [];
43
+
44
+ // Create a list of Document (Receipt, Invoice...) for each page of the input document
45
+ for (const [pageNumber, prediction] of predictions) {
46
+ this[`${this.documentType}s`].push(
47
+ constructors[this.documentType]({
48
+ apiPrediction: prediction.prediction,
49
+ inputFile: this.input,
50
+ pageNumber: pageNumber,
51
+ })
52
+ );
53
+ }
54
+
55
+ // Merge the list of Document into a unique Document
56
+ this[this.documentType] = constructors[this.documentType]({
57
+ apiPrediction: this.httpResponse.data.document.inference.prediction,
58
+ inputFile: this.input,
59
+ pageNumber: -1,
60
+ level: "document",
61
+ });
62
+ }
63
+ }
64
+
65
+ module.exports = Response;
@@ -0,0 +1,69 @@
1
+ const fs = require("fs").promises;
2
+
3
+ class Document {
4
+ /**
5
+ * Takes a list of Documents and return one Document where
6
+ * each field is set with the maximum probability field
7
+ * @param {Input} inputFile - input file given to parse the document
8
+ */
9
+ constructor(inputFile = undefined) {
10
+ this.filepath = undefined;
11
+ this.filename = undefined;
12
+ this.fileExtension = undefined;
13
+
14
+ if (inputFile != undefined) {
15
+ this.filepath = inputFile.filepath;
16
+ this.filename = inputFile.filename;
17
+ this.fileExtension = inputFile.fileExtension;
18
+ }
19
+ this.checklist = {};
20
+ }
21
+
22
+ clone() {
23
+ return JSON.parse(JSON.stringify(this));
24
+ }
25
+
26
+ /** return true if all checklist of the document if true */
27
+ checkAll() {
28
+ return this.checklist.every((item) => item == true);
29
+ }
30
+
31
+ /** Export document into a JSON file */
32
+ async dump(path) {
33
+ return await fs.writeFile(path, JSON.stringify(Object.entries(this)));
34
+ }
35
+
36
+ /** Create a Document from a JSON file */
37
+ static async load(path) {
38
+ const file = fs.readFile(path);
39
+ const args = JSON.parse(file);
40
+ return new Document({ reconsctruted: true, ...args });
41
+ }
42
+
43
+ /**
44
+ * Takes a list of Documents and return one Document where
45
+ * each field is set with the maximum probability field
46
+ * @param {Array<Document>} documents - A list of Documents
47
+ */
48
+ static mergePages(documents) {
49
+ const finalDocument = documents[0].clone();
50
+ const attributes = Object.getOwnPropertyNames(finalDocument);
51
+ for (const document of documents) {
52
+ for (const attribute of attributes) {
53
+ if (Array.isArray(document?.[attribute])) {
54
+ finalDocument[attribute] = finalDocument[attribute]?.length
55
+ ? finalDocument[attribute]
56
+ : document?.[attribute];
57
+ } else if (
58
+ document?.[attribute]?.probability >
59
+ finalDocument[attribute].probability
60
+ ) {
61
+ finalDocument[attribute] = document?.[attribute];
62
+ }
63
+ }
64
+ }
65
+ return finalDocument;
66
+ }
67
+ }
68
+
69
+ module.exports = Document;
@@ -0,0 +1,25 @@
1
+ const Field = require("./field");
2
+
3
+ class Amount extends Field {
4
+ /**
5
+ * @param {Object} prediction - Prediction object from HTTP response
6
+ * @param {String} valueKey - Key to use in the prediction dict
7
+ * @param {Boolean} reconstructed - Does the object is reconstructed (not extracted by the API)
8
+ * @param {Integer} pageNumber - Page number for multi pages pdf
9
+ */
10
+ constructor({
11
+ prediction,
12
+ valueKey = "amount",
13
+ reconstructed = false,
14
+ pageNumber = 0,
15
+ }) {
16
+ super({ prediction, valueKey, reconstructed, pageNumber });
17
+ this.value = +parseFloat(prediction[valueKey]).toFixed(3);
18
+ if (isNaN(this.value)) {
19
+ this.value = undefined;
20
+ this.probability = 0;
21
+ }
22
+ }
23
+ }
24
+
25
+ module.exports = Amount;
@@ -0,0 +1,29 @@
1
+ const Field = require("./field");
2
+
3
+ class DateField extends Field {
4
+ /**
5
+ * @param {Object} prediction - Prediction object from HTTP response
6
+ * @param {String} valueKey - Key to use in the prediction dict
7
+ * @param {Boolean} reconstructed - Does the object is reconstructed (not extracted by the API)
8
+ * @param {Integer} pageNumber - Page number for multi pages pdf
9
+ */
10
+ constructor({
11
+ prediction,
12
+ valueKey = "iso",
13
+ reconstructed = false,
14
+ pageNumber = 0,
15
+ }) {
16
+ super({ prediction, valueKey, reconstructed, pageNumber });
17
+ this.dateObject = new Date(this.value);
18
+ if (
19
+ !(this.dateObject instanceof Date) ||
20
+ isNaN(this.dateObject.valueOf())
21
+ ) {
22
+ this.dateObject = undefined;
23
+ this.probability = 0.0;
24
+ this.value = undefined;
25
+ }
26
+ }
27
+ }
28
+
29
+ module.exports = DateField;