mindee 1.3.1 → 1.4.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 (86) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/mindee/api/request.js +1 -1
  3. package/mindee/errors/handler.js +1 -1
  4. package/mindee/index.js +5 -2
  5. package/mindee/inputs.js +45 -25
  6. package/mindee/logger.js +8 -7
  7. package/package.json +13 -4
  8. package/.eslintrc +0 -24
  9. package/.mocharc.yaml +0 -2
  10. package/.nyc_output/f57ba3bc-1777-4ecc-81e1-230327c2a401.json +0 -1
  11. package/.nyc_output/processinfo/f57ba3bc-1777-4ecc-81e1-230327c2a401.json +0 -1
  12. package/.nyc_output/processinfo/index.json +0 -1
  13. package/.prettierrc +0 -4
  14. package/.tool-versions +0 -1
  15. package/CODE_OF_CONDUCT.md +0 -63
  16. package/CONTRIBUTING.md +0 -84
  17. package/ISSUE_TEMPLATE.md +0 -45
  18. package/PULL_REQUEST_TEMPLATE.md +0 -45
  19. package/babel.config.json +0 -10
  20. package/coverage/coverage.json +0 -1
  21. package/coverage/lcov-report/base.css +0 -224
  22. package/coverage/lcov-report/block-navigation.js +0 -79
  23. package/coverage/lcov-report/favicon.png +0 -0
  24. package/coverage/lcov-report/index.html +0 -171
  25. package/coverage/lcov-report/prettify.css +0 -1
  26. package/coverage/lcov-report/prettify.js +0 -2
  27. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  28. package/coverage/lcov-report/sorter.js +0 -170
  29. package/coverage/lcov.info +0 -1595
  30. package/coverage.lcov +0 -1595
  31. package/dist/api/financialDocument.js +0 -51
  32. package/dist/api/index.js +0 -13
  33. package/dist/api/invoice.js +0 -59
  34. package/dist/api/object.js +0 -80
  35. package/dist/api/receipt.js +0 -45
  36. package/dist/api/request.js +0 -90
  37. package/dist/api/response.js +0 -91
  38. package/dist/documents/document.js +0 -80
  39. package/dist/documents/fields/amount.js +0 -21
  40. package/dist/documents/fields/date.js +0 -17
  41. package/dist/documents/fields/field.js +0 -85
  42. package/dist/documents/fields/index.js +0 -17
  43. package/dist/documents/fields/locale.js +0 -25
  44. package/dist/documents/fields/orientation.js +0 -22
  45. package/dist/documents/fields/paymentDetails.js +0 -50
  46. package/dist/documents/fields/tax.js +0 -42
  47. package/dist/documents/financialDocument.js +0 -216
  48. package/dist/documents/index.js +0 -13
  49. package/dist/documents/invoice.js +0 -361
  50. package/dist/documents/receipt.js +0 -231
  51. package/dist/errors/handler.js +0 -17
  52. package/dist/index.js +0 -23
  53. package/dist/inputs.js +0 -208
  54. package/dist/logger.js +0 -34
  55. package/examples/.env.example +0 -2
  56. package/examples/documents/invoices/credit_note.pdf +0 -900
  57. package/examples/documents/invoices/invoice.pdf +0 -0
  58. package/examples/documents/invoices/invoice_6p.pdf +0 -0
  59. package/examples/documents/receipts/receipt.jpg +0 -0
  60. package/examples/financialDocument.js +0 -32
  61. package/examples/invoice.js +0 -74
  62. package/examples/receipt.js +0 -45
  63. package/lib/api/financialDocument.js +0 -59
  64. package/lib/api/index.js +0 -7
  65. package/lib/api/invoice.js +0 -73
  66. package/lib/api/object.js +0 -90
  67. package/lib/api/receipt.js +0 -58
  68. package/lib/api/request.js +0 -84
  69. package/lib/api/response.js +0 -92
  70. package/lib/documents/document.js +0 -97
  71. package/lib/documents/fields/amount.js +0 -35
  72. package/lib/documents/fields/date.js +0 -36
  73. package/lib/documents/fields/field.js +0 -102
  74. package/lib/documents/fields/index.js +0 -9
  75. package/lib/documents/fields/locale.js +0 -35
  76. package/lib/documents/fields/orientation.js +0 -33
  77. package/lib/documents/fields/paymentDetails.js +0 -71
  78. package/lib/documents/fields/tax.js +0 -57
  79. package/lib/documents/financialDocument.js +0 -280
  80. package/lib/documents/index.js +0 -7
  81. package/lib/documents/invoice.js +0 -451
  82. package/lib/documents/receipt.js +0 -332
  83. package/lib/errors/handler.js +0 -19
  84. package/lib/index.js +0 -40
  85. package/lib/inputs.js +0 -190
  86. package/lib/logger.js +0 -52
@@ -1,51 +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.APIFinancialDocument = void 0;
13
- const object_1 = require("@api/object");
14
- const inputs_1 = require("@mindee/inputs");
15
- class APIFinancialDocument extends object_1.APIObject {
16
- constructor(invoiceToken, receiptToken) {
17
- super(undefined, "financialDocument");
18
- this.invoiceToken = invoiceToken;
19
- this.receiptToken = receiptToken;
20
- this.invoiceToken = invoiceToken;
21
- this.receiptToken = receiptToken;
22
- }
23
- /**
24
- * @param {String} file: Receipt filepath (allowed jpg, png, tiff, pdf)
25
- * @param {String} inputType: String in {'path', 'stream', 'base64'}
26
- * @param {Boolean} includeWords: extract all words into http_response
27
- * @param {String} version: expense_receipt api version
28
- * @param {Boolean} cutPdf: Automatically reconstruct pdf with more than 4 pages
29
- * @returns {Response} Wrapped response with Receipts objects parsed
30
- */
31
- parse({ input, inputType = "path", filename = undefined, version = "3", cutPdf = true, includeWords = false, }) {
32
- const _super = Object.create(null, {
33
- parse: { get: () => super.parse },
34
- _request: { get: () => super._request }
35
- });
36
- return __awaiter(this, void 0, void 0, function* () {
37
- const inputFile = new inputs_1.Input(input, inputType, cutPdf, filename);
38
- yield inputFile.init();
39
- this.apiToken =
40
- inputFile.fileExtension === "application/pdf"
41
- ? this.invoiceToken
42
- : this.receiptToken;
43
- const url = inputFile.fileExtension === "application/pdf"
44
- ? `/invoices/v${version}/predict`
45
- : `/expense_receipts/v${version}/predict`;
46
- _super.parse.call(this);
47
- return _super._request.call(this, url, inputFile, includeWords);
48
- });
49
- }
50
- }
51
- exports.APIFinancialDocument = APIFinancialDocument;
package/dist/api/index.js DELETED
@@ -1,13 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.APIInvoice = exports.request = exports.Response = exports.APIReceipt = exports.APIObject = void 0;
4
- var object_1 = require("@api/object");
5
- Object.defineProperty(exports, "APIObject", { enumerable: true, get: function () { return object_1.APIObject; } });
6
- var receipt_1 = require("@api/receipt");
7
- Object.defineProperty(exports, "APIReceipt", { enumerable: true, get: function () { return receipt_1.APIReceipt; } });
8
- var response_1 = require("@api/response");
9
- Object.defineProperty(exports, "Response", { enumerable: true, get: function () { return response_1.Response; } });
10
- var request_1 = require("@api/request");
11
- Object.defineProperty(exports, "request", { enumerable: true, get: function () { return request_1.request; } });
12
- var invoice_1 = require("@api/invoice");
13
- Object.defineProperty(exports, "APIInvoice", { enumerable: true, get: function () { return invoice_1.APIInvoice; } });
@@ -1,59 +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.APIInvoice = void 0;
13
- const object_1 = require("@api/object");
14
- const inputs_1 = require("@mindee/inputs");
15
- class APIInvoice extends object_1.APIObject {
16
- constructor(apiToken = undefined) {
17
- super(apiToken, "invoice");
18
- this.apiToken = apiToken;
19
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
20
- // @ts-ignore TO DO : FIX
21
- this.baseUrl = `${this.baseUrl}/invoices/`;
22
- }
23
- /**
24
- * @param {Boolean} includeWords: , extract all words into http_response
25
- * @param {Boolean} cutPdf: Automatically reconstruct pdf with more than 4 pages
26
- * @param {String} inputType: String in {'path', 'stream', 'base64'}
27
- * @param {String} file: Receipt filepath (allowed jpg, png, tiff, pdf)
28
- * @param {String} version: expense_receipt api version
29
- * @returns {Response} Wrapped response with Receipts objects parsed
30
- */
31
- parse({ input, inputType = "path", filename = undefined, version = "3", cutPdf = true, includeWords = false, }) {
32
- const _super = Object.create(null, {
33
- parse: { get: () => super.parse },
34
- _request: { get: () => super._request }
35
- });
36
- return __awaiter(this, void 0, void 0, function* () {
37
- _super.parse.call(this);
38
- const inputFile = new inputs_1.Input(input, inputType, cutPdf, filename);
39
- yield inputFile.init();
40
- const url = `v${version}/predict`;
41
- return yield _super._request.call(this, url, inputFile, includeWords);
42
- });
43
- }
44
- /**
45
- @param {String} inputFile - Input object
46
- @param {} response - HTTP response
47
- @param {Document} documentType - Document class in {"Receipt", "Invoice", "Financial_document"}
48
- @returns {Response}
49
- */
50
- wrapResponse(inputFile, response, documentType) {
51
- var _a, _b, _c, _d, _e;
52
- const result = super.wrapResponse(inputFile, response, documentType);
53
- result.documentType =
54
- ((_e = (_d = (_c = (_b = (_a = result.httpResponse.data) === null || _a === void 0 ? void 0 : _a.predictions) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.document_type) === null || _d === void 0 ? void 0 : _d.value) === null || _e === void 0 ? void 0 : _e.toLowerCase()) ||
55
- result.documentType;
56
- return result;
57
- }
58
- }
59
- exports.APIInvoice = APIInvoice;
@@ -1,80 +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.APIObject = void 0;
13
- const response_1 = require("@api/response");
14
- const handler_1 = require("@errors/handler");
15
- const request_1 = require("@api/request");
16
- /**
17
- * Base class for APIs (APIReceipt & APIInvoice)
18
- * @param {String} apiToken - Token of the API used for parsing document
19
- * @param {String} apiName - Name of the API used for parsing document
20
- */
21
- class APIObject {
22
- constructor(apiToken = undefined, apiName = "") {
23
- this.apiToken = apiToken;
24
- this.apiName = apiName;
25
- this.apiToken = apiToken;
26
- this.baseUrl = "https://api.mindee.net/v1/products/mindee";
27
- this.apiName = apiName;
28
- }
29
- /**
30
- */
31
- parse() {
32
- if (!this.apiToken) {
33
- handler_1.errorHandler.throw({
34
- error: new Error(`Missing API token for ${this.apiName}. \
35
- Have you create a mindee Client with a ${this.apiName}Token in parameters ?`),
36
- });
37
- }
38
- }
39
- /**
40
- @param {String} url - API url for request
41
- @param {Input} inputFile - input file for API
42
- @param {Boolean} includeWords - Include Mindee vision words in Response
43
- @returns {Response}
44
- */
45
- _request(url, inputFile, includeWords = false) {
46
- return __awaiter(this, void 0, void 0, function* () {
47
- const headers = {
48
- "X-Inferuser-Token": this.apiToken,
49
- };
50
- const response = yield (0, request_1.request)(`${this.baseUrl}${url}`, "POST", headers, inputFile, includeWords);
51
- return this.wrapResponse(inputFile, response, this.apiName);
52
- });
53
- }
54
- /**
55
- @param {String} inputFile - Input object
56
- @param {} response - HTTP response
57
- @param {Document} documentType - Document class in {"Receipt", "Invoice", "Financial_document"}
58
- @returns {Response}
59
- */
60
- wrapResponse(inputFile, response, documentType) {
61
- if (response.statusCode > 201) {
62
- const errorMessage = JSON.stringify(response.data, null, 4);
63
- handler_1.errorHandler.throw(new Error(`${this.apiName} API ${response.statusCode} HTTP error: ${errorMessage}`));
64
- return new response_1.Response({
65
- httpResponse: response,
66
- documentType: documentType,
67
- document: undefined,
68
- input: inputFile,
69
- error: true,
70
- });
71
- }
72
- return new response_1.Response({
73
- httpResponse: response,
74
- documentType: documentType,
75
- document: inputFile,
76
- input: inputFile,
77
- });
78
- }
79
- }
80
- exports.APIObject = APIObject;
@@ -1,45 +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.APIReceipt = void 0;
13
- const object_1 = require("@api/object");
14
- const inputs_1 = require("@mindee/inputs");
15
- class APIReceipt extends object_1.APIObject {
16
- constructor(apiToken = undefined) {
17
- super(apiToken, "receipt");
18
- this.apiToken = apiToken;
19
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
20
- // @ts-ignore TO DO : FIX
21
- this.baseUrl = `${this.baseUrl}/expense_receipts/`;
22
- }
23
- /**
24
- * @param {String} file: Receipt filepath (allowed jpg, png, tiff, pdf)
25
- * @param {String} inputType: String in {'path', 'stream', 'base64'}
26
- * @param {Boolean} includeWords: extract all words into http_response
27
- * @param {String} version: expense_receipt api version
28
- * @param {Boolean} cutPdf: Automatically reconstruct pdf with more than 4 pages
29
- * @returns {Response} Wrapped response with Receipts objects parsed
30
- */
31
- parse({ input, inputType = "path", filename = undefined, version = "3", cutPdf = true, includeWords = false, }) {
32
- const _super = Object.create(null, {
33
- parse: { get: () => super.parse },
34
- _request: { get: () => super._request }
35
- });
36
- return __awaiter(this, void 0, void 0, function* () {
37
- _super.parse.call(this);
38
- const inputFile = new inputs_1.Input(input, inputType, cutPdf, filename);
39
- yield inputFile.init();
40
- const url = `v${version}/predict`;
41
- return yield _super._request.call(this, url, inputFile, includeWords);
42
- });
43
- }
44
- }
45
- exports.APIReceipt = APIReceipt;
@@ -1,90 +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 __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.request = void 0;
30
- const https = __importStar(require("https"));
31
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
32
- // @ts-ignore
33
- const package_json_1 = require("../../package.json");
34
- const url_1 = require("url");
35
- const form_data_1 = __importDefault(require("form-data"));
36
- const os = __importStar(require("os"));
37
- const request = (url, method, headers, input, includeWords = false) => {
38
- return new Promise(function (resolve, reject) {
39
- const form = new form_data_1.default();
40
- let body;
41
- headers["User-Agent"] = `mindee-api-nodejs@v${package_json_1.version} nodejs-${process.version} ${os.type().toLowerCase()}`;
42
- if (["path", "stream"].includes(input.inputType)) {
43
- const fileParams = { filename: input.filename };
44
- form.append("document", input.fileObject, fileParams);
45
- if (includeWords)
46
- form.append("include_mvision", "true");
47
- headers = Object.assign(Object.assign({}, headers), form.getHeaders());
48
- }
49
- else if (input.inputType === "base64") {
50
- const body_obj = { document: input.fileObject };
51
- if (includeWords)
52
- body_obj["include_mvision"] = "true";
53
- body = JSON.stringify(body_obj);
54
- headers["Content-Type"] = "application/json";
55
- headers["Content-Length"] = body.length;
56
- }
57
- const uri = new url_1.URL(url);
58
- const options = {
59
- method: method,
60
- headers: headers,
61
- hostname: uri.hostname,
62
- path: `${uri.pathname}${uri.search}`,
63
- };
64
- const req = https.request(options, function (res) {
65
- let responseBody = [];
66
- res.on("data", function (chunk) {
67
- responseBody += chunk;
68
- });
69
- res.on("end", function () {
70
- try {
71
- resolve(Object.assign(Object.assign({}, res), { data: JSON.parse(responseBody) }));
72
- }
73
- catch (error) {
74
- console.log(responseBody, error);
75
- }
76
- });
77
- });
78
- req.on("error", (err) => {
79
- reject(err);
80
- });
81
- if (["path", "stream"].includes(input.inputType)) {
82
- form.pipe(req);
83
- }
84
- if (input.inputType === "base64") {
85
- req.write(body);
86
- req.end();
87
- }
88
- });
89
- };
90
- exports.request = request;
@@ -1,91 +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
- var __rest = (this && this.__rest) || function (s, e) {
12
- var t = {};
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
- t[p] = s[p];
15
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
- t[p[i]] = s[p[i]];
19
- }
20
- return t;
21
- };
22
- var __importDefault = (this && this.__importDefault) || function (mod) {
23
- return (mod && mod.__esModule) ? mod : { "default": mod };
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.Response = void 0;
27
- const receipt_1 = require("@documents/receipt");
28
- const invoice_1 = require("@documents/invoice");
29
- const financialDocument_1 = require("@documents/financialDocument");
30
- const promises_1 = __importDefault(require("fs/promises"));
31
- class Response {
32
- constructor(_a) {
33
- var { httpResponse, documentType, input, error, reconsctruted = false } = _a, args = __rest(_a, ["httpResponse", "documentType", "input", "error", "reconsctruted"]);
34
- this.httpResponse = httpResponse;
35
- this.documentType = documentType;
36
- this.input = input;
37
- if (!error && !reconsctruted)
38
- this.formatResponse();
39
- if (reconsctruted === true) {
40
- Object.assign(this, args);
41
- }
42
- }
43
- dump(path) {
44
- return __awaiter(this, void 0, void 0, function* () {
45
- return yield promises_1.default.writeFile(path, JSON.stringify(Object.entries(this)));
46
- });
47
- }
48
- static load(path) {
49
- return __awaiter(this, void 0, void 0, function* () {
50
- const file = promises_1.default.readFile(path);
51
- const args = JSON.parse(file);
52
- return new Response(Object.assign({ reconsctruted: true }, args));
53
- });
54
- }
55
- formatResponse() {
56
- const http_data_document = this.httpResponse.data.document;
57
- const constructors = {
58
- receipt: (params) => new receipt_1.Receipt(params),
59
- invoice: (params) => new invoice_1.Invoice(params),
60
- financialDocument: (params) => new financialDocument_1.FinancialDocument(params),
61
- };
62
- const predictions = http_data_document.inference.pages.entries();
63
- this[`${this.documentType}s`] = [];
64
- const document_words_content = [];
65
- // Create a list of Document (Receipt, Invoice...) for each page of the input document
66
- for (const [pageNumber, prediction] of predictions) {
67
- let page_words_content = [];
68
- if ("ocr" in http_data_document &&
69
- Object.keys(http_data_document.ocr).length > 0) {
70
- page_words_content =
71
- http_data_document.ocr["mvision-v1"].pages[pageNumber].all_words;
72
- document_words_content.push(...http_data_document.ocr["mvision-v1"].pages[pageNumber].all_words);
73
- }
74
- this[`${this.documentType}s`].push(constructors[this.documentType]({
75
- apiPrediction: prediction.prediction,
76
- inputFile: this.input,
77
- pageNumber: pageNumber,
78
- words: page_words_content,
79
- }));
80
- }
81
- // Merge the list of Document into a unique Document
82
- this[this.documentType] = constructors[this.documentType]({
83
- apiPrediction: http_data_document.inference.prediction,
84
- inputFile: this.input,
85
- pageNumber: http_data_document.n_pages,
86
- level: "document",
87
- words: document_words_content,
88
- });
89
- }
90
- }
91
- exports.Response = Response;
@@ -1,80 +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
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.Document = void 0;
16
- const promises_1 = __importDefault(require("fs/promises"));
17
- class Document {
18
- /**
19
- * Takes a list of Documents and return one Document where
20
- * each field is set with the maximum probability field
21
- * @param {Input} inputFile - input file given to parse the document
22
- */
23
- constructor(inputFile = undefined) {
24
- this.filepath = undefined;
25
- this.filename = undefined;
26
- this.fileExtension = undefined;
27
- if (inputFile != undefined) {
28
- this.filepath = inputFile.filepath;
29
- this.filename = inputFile.filename;
30
- this.fileExtension = inputFile.fileExtension;
31
- }
32
- this.checklist = {};
33
- }
34
- clone() {
35
- return JSON.parse(JSON.stringify(this));
36
- }
37
- /** return true if all checklist of the document if true */
38
- checkAll() {
39
- return this.checklist.every((item) => item == true);
40
- }
41
- /** Export document into a JSON file */
42
- dump(path) {
43
- return __awaiter(this, void 0, void 0, function* () {
44
- return yield promises_1.default.writeFile(path, JSON.stringify(Object.entries(this)));
45
- });
46
- }
47
- /** Create a Document from a JSON file */
48
- static load(path) {
49
- return __awaiter(this, void 0, void 0, function* () {
50
- const file = promises_1.default.readFile(path);
51
- const args = JSON.parse(file);
52
- return new Document(Object.assign({ reconsctruted: true }, args));
53
- });
54
- }
55
- /**
56
- * Takes a list of Documents and return one Document where
57
- * each field is set with the maximum probability field
58
- * @param {Array<Document>} documents - A list of Documents
59
- */
60
- static mergePages(documents) {
61
- var _a, _b;
62
- const finalDocument = documents[0].clone();
63
- const attributes = Object.getOwnPropertyNames(finalDocument);
64
- for (const document of documents) {
65
- for (const attribute of attributes) {
66
- if (Array.isArray(document === null || document === void 0 ? void 0 : document[attribute])) {
67
- finalDocument[attribute] = ((_a = finalDocument[attribute]) === null || _a === void 0 ? void 0 : _a.length)
68
- ? finalDocument[attribute]
69
- : document === null || document === void 0 ? void 0 : document[attribute];
70
- }
71
- else if (((_b = document === null || document === void 0 ? void 0 : document[attribute]) === null || _b === void 0 ? void 0 : _b.probability) >
72
- finalDocument[attribute].probability) {
73
- finalDocument[attribute] = document === null || document === void 0 ? void 0 : document[attribute];
74
- }
75
- }
76
- }
77
- return finalDocument;
78
- }
79
- }
80
- exports.Document = Document;
@@ -1,21 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Amount = void 0;
4
- const field_1 = require("@fields/field");
5
- class Amount extends field_1.Field {
6
- /**
7
- * @param {Object} prediction - Prediction object from HTTP response
8
- * @param {String} valueKey - Key to use in the prediction dict
9
- * @param {Boolean} reconstructed - Does the object is reconstructed (not extracted by the API)
10
- * @param {Integer} pageNumber - Page number for multi pages pdf
11
- */
12
- constructor({ prediction, valueKey = "amount", reconstructed = false, pageNumber = 0, }) {
13
- super({ prediction, valueKey, reconstructed, pageNumber });
14
- this.value = +parseFloat(prediction[valueKey]).toFixed(3);
15
- if (isNaN(this.value)) {
16
- this.value = undefined;
17
- this.probability = 0;
18
- }
19
- }
20
- }
21
- exports.Amount = Amount;
@@ -1,17 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DateField = void 0;
4
- const field_1 = require("@fields/field");
5
- class DateField extends field_1.Field {
6
- constructor({ prediction, valueKey = "iso", reconstructed = false, pageNumber = 0, }) {
7
- super({ prediction, valueKey, reconstructed, pageNumber });
8
- this.dateObject = new Date(this.value);
9
- if (!(this.dateObject instanceof Date) ||
10
- isNaN(this.dateObject.valueOf())) {
11
- this.dateObject = undefined;
12
- this.probability = 0.0;
13
- this.value = undefined;
14
- }
15
- }
16
- }
17
- exports.DateField = DateField;
@@ -1,85 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Field = void 0;
4
- class Field {
5
- /**
6
- * @param {Object} prediction - Prediction object from HTTP response
7
- * @param {String} valueKey - Key to use in the prediction dict
8
- * @param {Boolean} reconstructed - Does the object is reconstructed (not extracted by the API)
9
- * @param {Integer} pageNumber - Page number for multi pages pdf
10
- * @param {Array<String>} extraFields - Extra fields to get from the prediction and to set as attribute of the Field
11
- */
12
- constructor({ prediction, valueKey = "value", reconstructed = false, extraFields, pageNumber, }) {
13
- this.pageNumber = pageNumber;
14
- this.reconstructed = reconstructed;
15
- this.value = undefined;
16
- this.probability = prediction.confidence ? prediction.confidence : 0.0;
17
- this.bbox = prediction.polygon ? prediction.polygon : [];
18
- if (valueKey in prediction && prediction[valueKey] !== null) {
19
- this.value = prediction[valueKey];
20
- if (extraFields) {
21
- for (const fieldName of extraFields) {
22
- this[fieldName] = prediction[fieldName];
23
- }
24
- }
25
- }
26
- }
27
- compare(other) {
28
- if (this.value == null && other.value == null)
29
- return true;
30
- else if (this.value == null || other.value == null)
31
- return false;
32
- else {
33
- if (typeof this.value == "string") {
34
- return this.value.toLowerCase() === other.value.toLowerCase();
35
- }
36
- else {
37
- return this.value === other.value;
38
- }
39
- }
40
- }
41
- /**
42
- @param {Array<Field>} array1 - first Array of Fields
43
- @param {Array<Field>} array2 - second Array of Fields
44
- @param {String} attr - Attribute to compare
45
- @returns {Boolean} - true if all elements in array1 exist in array2 and vice-versa, false otherwise
46
- */
47
- static compareArrays(array1, array2, attr = "value") {
48
- const list1 = array1.map((item) => item[attr]);
49
- const list2 = array2.map((item) => item[attr]);
50
- if (list1.length !== list2.length)
51
- return false;
52
- for (const item1 of list1) {
53
- if (!list2.includes(item1))
54
- return false;
55
- }
56
- return true;
57
- }
58
- /**
59
- * @param {Array<Field>} array - Array of Fields
60
- * @returns {Number} product of all the fields probaility
61
- */
62
- static arrayProbability(array) {
63
- let total = 1.0;
64
- for (const field of array) {
65
- total *= field.probability;
66
- if (isNaN(total))
67
- return 0.0;
68
- }
69
- return total;
70
- }
71
- /**
72
- * @param {Array<Field>} array - Array of Fields
73
- * @returns {Number} Sum of all the Fields values in the array
74
- */
75
- static arraySum(array) {
76
- let total = 0;
77
- for (const field of array) {
78
- total += field.value;
79
- if (isNaN(total))
80
- return 0.0;
81
- }
82
- return total;
83
- }
84
- }
85
- exports.Field = Field;
@@ -1,17 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Field = exports.DateField = exports.Amount = exports.Locale = exports.Orientation = exports.PaymentDetails = exports.Tax = void 0;
4
- var tax_1 = require("@fields/tax");
5
- Object.defineProperty(exports, "Tax", { enumerable: true, get: function () { return tax_1.Tax; } });
6
- var paymentDetails_1 = require("@fields/paymentDetails");
7
- Object.defineProperty(exports, "PaymentDetails", { enumerable: true, get: function () { return paymentDetails_1.PaymentDetails; } });
8
- var orientation_1 = require("@fields/orientation");
9
- Object.defineProperty(exports, "Orientation", { enumerable: true, get: function () { return orientation_1.Orientation; } });
10
- var locale_1 = require("@fields/locale");
11
- Object.defineProperty(exports, "Locale", { enumerable: true, get: function () { return locale_1.Locale; } });
12
- var amount_1 = require("@fields/amount");
13
- Object.defineProperty(exports, "Amount", { enumerable: true, get: function () { return amount_1.Amount; } });
14
- var date_1 = require("@fields/date");
15
- Object.defineProperty(exports, "DateField", { enumerable: true, get: function () { return date_1.DateField; } });
16
- var field_1 = require("@fields/field");
17
- Object.defineProperty(exports, "Field", { enumerable: true, get: function () { return field_1.Field; } });