mindee 1.3.0 → 1.3.3

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.
package/CHANGELOG.md CHANGED
@@ -1,102 +1,117 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## v1.3.3
4
+
5
+ ### Fixes
6
+ * 🐛 reject errors instead of printing them only to the console
7
+
8
+ ## v1.3.2
9
+
10
+ ### Fixes
11
+ * 🐛 use PDF length instead of cut PDF size limit
12
+
13
+ ## v1.3.1
14
+
15
+ ### Fixes
16
+ * 🐛 forward api error to stderr instead of stdout
17
+
3
18
  ## v1.3.0
4
19
 
5
20
  ### Changes
6
21
 
7
- - :sparkles: allow sending the filename for streams and base64
8
- - fixes :bug: not able to specify MIME type
9
- - :page_facing_up: change license to MIT
10
- - :white_check_mark: add node18 to tests
11
- - various package updates
22
+ * :sparkles: allow sending the filename for streams and base64
23
+ * fixes :bug: not able to specify MIME type
24
+ * :page_facing_up: change license to MIT
25
+ * :white_check_mark: add node18 to tests
26
+ * various package updates
12
27
 
13
28
  ## v1.2.0
14
29
 
15
30
  ### Fixes
16
31
 
17
- - fix: 🐛 Get `words` values when `includeWords` parameter is `true`
32
+ * fix: 🐛 Get `words` values when `includeWords` parameter is `true`
18
33
 
19
34
  ## v1.1.2
20
35
 
21
36
  ### Fixes
22
37
 
23
- - fix: 🐛 Fix returned probability value
24
- - fix: 🐛 Fix returned bbox value
38
+ * fix: 🐛 Fix returned probability value
39
+ * fix: 🐛 Fix returned bbox value
25
40
 
26
41
  ### new
27
42
 
28
- - new: ✨ New Mindee Invoice API V3 support
29
- - new: ✨ Add new supplier and customer fields
43
+ * new: ✨ New Mindee Invoice API V3 support
44
+ * new: ✨ Add new supplier and customer fields
30
45
 
31
46
  ## v1.1.0 (2022-01-03)
32
47
 
33
48
  ### new
34
49
 
35
- - chg: :sparkles: New Mindee API V2 support
36
- - chg: :zap: Server side invoice reconstruction from multi-page pdfs
37
- - new: :sparkles: Added OS in User-Agent headers
50
+ * chg: :sparkles: New Mindee API V2 support
51
+ * chg: :zap: Server side invoice reconstruction from multi-page pdfs
52
+ * new: :sparkles: Added OS in User-Agent headers
38
53
 
39
54
 
40
55
  ## v1.0.9 (2021-12-09)
41
56
 
42
57
  ### Fixes
43
58
 
44
- - fix: 🐛 handle attribute of type array when merging pages
59
+ * fix: 🐛 handle attribute of type array when merging pages
45
60
 
46
61
  ## v1.0.8 (2021-11-29)
47
62
 
48
63
  ### Fixes
49
64
 
50
- - 🐛 fix cutPDF for ReadableStream + add it for base64 file string
51
- - 🐛 Updated api Input initialization to specifically declare parameters
52
- - 🐛 prevent error when the mime type isn't detectable
53
- - 🐛 raise proper error when the APi doesn't return a valid JSON
65
+ * 🐛 fix cutPDF for ReadableStream + add it for base64 file string
66
+ * 🐛 Updated api Input initialization to specifically declare parameters
67
+ * 🐛 prevent error when the mime type isn't detectable
68
+ * 🐛 raise proper error when the APi doesn't return a valid JSON
54
69
 
55
70
  ### new
56
71
 
57
- - :see_no_evil: add .DS_Store to ignore file
72
+ * :see_no_evil: add .DS_Store to ignore file
58
73
 
59
74
  ## v1.0.7 (2021-11-25)
60
75
 
61
76
  ### New
62
77
 
63
- - ✨ Added pdf page number parameter for multi-pages pdfs with file
78
+ * ✨ Added pdf page number parameter for multi-pages pdfs with file
64
79
 
65
80
  ### Changes
66
81
 
67
- - :arrow_up: upgrade path-parse dependency
68
- - :arrow_up: upgrade browserslist dependency
69
- - :arrow_up: upgrade lodash dependency
70
- - :arrow_up: upgrade y18n dependency
82
+ * :arrow_up: upgrade path-parse dependency
83
+ * :arrow_up: upgrade browserslist dependency
84
+ * :arrow_up: upgrade lodash dependency
85
+ * :arrow_up: upgrade y18n dependency
71
86
 
72
87
  ## v1.0.4 (2021-02-18)
73
88
 
74
89
  ### New
75
90
 
76
- - :sparkles: :zap: Add a parameter `filename` and a default filename for streams
91
+ * :sparkles: :zap: Add a parameter `filename` and a default filename for streams
77
92
 
78
93
  ### Changes
79
94
 
80
- - :zap: Change parse function to use an object instead of multiples parameters
95
+ * :zap: Change parse function to use an object instead of multiples parameters
81
96
 
82
97
  ## v1.0.3 (2021-02-01)
83
98
 
84
99
  ### Fixes
85
100
 
86
- - :bug: \_request parameters
87
- - :bug: `pageNumber` default value
88
- - :bug: reconstruction method set fields to probability
101
+ * :bug: \_request parameters
102
+ * :bug: `pageNumber` default value
103
+ * :bug: reconstruction method set fields to probability
89
104
 
90
105
  ## v1.0.2 (2021-02-01)
91
106
 
92
107
  ### Changes
93
108
 
94
- - :zap: Better coverage for total tax
109
+ * :zap: Better coverage for total tax
95
110
 
96
111
  ### Fixes
97
112
 
98
- - :bug: `includeWords` is now working
113
+ * :bug: `includeWords` is now working
99
114
 
100
115
  ## v1.0.1 (2021-01-11)
101
116
 
102
- - 🎉 First release
117
+ * 🎉 First release
@@ -0,0 +1,51 @@
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;
@@ -0,0 +1,13 @@
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; } });
@@ -0,0 +1,59 @@
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;
@@ -0,0 +1,80 @@
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;
@@ -0,0 +1,45 @@
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;
@@ -0,0 +1,90 @@
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;
@@ -0,0 +1,91 @@
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;
@@ -0,0 +1,80 @@
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;