mindee 1.0.2 → 1.0.7

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 (43) hide show
  1. package/CHANGELOG.md +36 -5
  2. package/README.md +11 -8
  3. package/examples/documents/invoices/credit_note.pdf +899 -1
  4. package/examples/financialDocument.js +2 -2
  5. package/examples/invoice.js +21 -4
  6. package/examples/receipt.js +3 -3
  7. package/lib/api/financialDocument.js +12 -8
  8. package/lib/api/invoice.js +28 -9
  9. package/lib/api/receipt.js +13 -9
  10. package/lib/api/request.js +1 -5
  11. package/lib/documents/document.js +4 -2
  12. package/lib/documents/fields/amount.js +1 -1
  13. package/lib/documents/fields/date.js +1 -1
  14. package/lib/documents/fields/locale.js +1 -1
  15. package/lib/documents/fields/orientation.js +1 -1
  16. package/lib/documents/fields/paymentDetails.js +1 -1
  17. package/lib/documents/fields/tax.js +1 -1
  18. package/lib/inputs.js +52 -4
  19. package/mindee/api/financialDocument.js +40 -0
  20. package/mindee/api/index.js +5 -0
  21. package/mindee/api/invoice.js +48 -0
  22. package/mindee/api/object.js +82 -0
  23. package/mindee/api/receipt.js +34 -0
  24. package/mindee/api/request.js +63 -0
  25. package/mindee/api/response.js +62 -0
  26. package/mindee/documents/document.js +65 -0
  27. package/mindee/documents/fields/amount.js +25 -0
  28. package/mindee/documents/fields/date.js +29 -0
  29. package/mindee/documents/fields/field.js +89 -0
  30. package/mindee/documents/fields/index.js +7 -0
  31. package/mindee/documents/fields/locale.js +30 -0
  32. package/mindee/documents/fields/orientation.js +24 -0
  33. package/mindee/documents/fields/paymentDetails.js +52 -0
  34. package/mindee/documents/fields/tax.js +47 -0
  35. package/mindee/documents/financialDocument.js +204 -0
  36. package/mindee/documents/index.js +5 -0
  37. package/mindee/documents/invoice.js +395 -0
  38. package/mindee/documents/receipt.js +272 -0
  39. package/mindee/errors/handler.js +16 -0
  40. package/mindee/index.js +35 -0
  41. package/mindee/inputs.js +155 -0
  42. package/mindee/logger.js +33 -0
  43. package/package.json +12 -7
@@ -5,7 +5,7 @@ const mindeeClient = new Client();
5
5
 
6
6
  // parsing receipt from picture
7
7
  mindeeClient.financialDocument
8
- .parse("./documents/receipts/receipt.jpg")
8
+ .parse({ input: "./documents/receipts/receipt.jpg" })
9
9
  .then((res) => {
10
10
  console.log("Success !");
11
11
  console.log(res.financialDocuments);
@@ -21,7 +21,7 @@ const base64 = fs.readFileSync("./documents/receipts/receipt.jpg", {
21
21
  encoding: "base64",
22
22
  });
23
23
  mindeeClient.financialDocument
24
- .parse(base64, "base64")
24
+ .parse({ input: base64, inputType: "base64" })
25
25
  .then((res) => {
26
26
  console.log("Success !");
27
27
  console.log(res.financialDocuments);
@@ -6,11 +6,25 @@ const mindeeClient = new Client();
6
6
 
7
7
  // parsing invoice from pdf
8
8
  mindeeClient.invoice
9
- .parse("./documents/invoices/invoice.pdf")
9
+ .parse({ input: "./documents/invoices/invoice.pdf" })
10
10
  .then((res) => {
11
11
  console.log("Success !");
12
12
  console.log(res.invoices);
13
13
  console.log(res.invoice);
14
+ console.log(res.documentType);
15
+ })
16
+ .catch((err) => {
17
+ console.error(err);
18
+ });
19
+
20
+ // parsing credit note from pdf
21
+ mindeeClient.invoice
22
+ .parse({ input: "./documents/invoices/credit_note.pdf" })
23
+ .then((res) => {
24
+ console.log("Success !");
25
+ console.log(res.invoices);
26
+ console.log(res.invoice);
27
+ console.log(res.documentType);
14
28
  })
15
29
  .catch((err) => {
16
30
  console.error(err);
@@ -18,9 +32,10 @@ mindeeClient.invoice
18
32
 
19
33
  // // parsing invoice from multiple page pdf
20
34
  mindeeClient.invoice
21
- .parse("./documents/invoices/invoice_6p.pdf")
35
+ .parse({ input: "./documents/invoices/invoice_6p.pdf" })
22
36
  .then((res) => {
23
37
  console.log("Success !");
38
+ console.log(res.documentType);
24
39
  console.log(res.invoices);
25
40
  console.log(res.invoice);
26
41
  })
@@ -33,9 +48,10 @@ const base64 = fs.readFileSync("./documents/invoices/invoice.pdf", {
33
48
  encoding: "base64",
34
49
  });
35
50
  mindeeClient.invoice
36
- .parse(base64, "base64")
51
+ .parse({ input: base64, inputType: "base64" })
37
52
  .then((res) => {
38
53
  console.log("Success !");
54
+ console.log(res.documentType);
39
55
  console.log(res.invoices);
40
56
  console.log(res.invoice);
41
57
  })
@@ -46,9 +62,10 @@ mindeeClient.invoice
46
62
  // parsing invoice from stream
47
63
  const stream = fs.createReadStream("./documents/invoices/invoice.pdf");
48
64
  mindeeClient.invoice
49
- .parse(stream, "stream")
65
+ .parse({ input: stream, inputType: "stream" })
50
66
  .then((res) => {
51
67
  console.log("Success !");
68
+ console.log(res.documentType);
52
69
  console.log(res.invoices);
53
70
  console.log(res.invoice);
54
71
  })
@@ -6,7 +6,7 @@ const mindeeClient = new Client();
6
6
 
7
7
  // parsing receipt from picture
8
8
  mindeeClient.receipt
9
- .parse("./documents/receipts/receipt.jpg")
9
+ .parse({ input: "./documents/receipts/receipt.jpg" })
10
10
  .then((res) => {
11
11
  console.log("Success !");
12
12
  console.log(res.receipts);
@@ -21,7 +21,7 @@ const base64 = fs.readFileSync("./documents/receipts/receipt.jpg", {
21
21
  encoding: "base64",
22
22
  });
23
23
  mindeeClient.receipt
24
- .parse(base64, "base64")
24
+ .parse({ input: base64, inputType: "base64" })
25
25
  .then((res) => {
26
26
  console.log("Success !");
27
27
  console.log(res.receipts);
@@ -34,7 +34,7 @@ mindeeClient.receipt
34
34
  // parsing receipt from stream
35
35
  const stream = fs.createReadStream("./documents/receipts/receipt.jpg");
36
36
  mindeeClient.receipt
37
- .parse(stream, "stream")
37
+ .parse({ input: stream, inputType: "stream" })
38
38
  .then((res) => {
39
39
  console.log("Success !");
40
40
  console.log(res.receipts);
@@ -24,20 +24,24 @@ class APIFinancialDocument extends APIObject {
24
24
  */
25
25
 
26
26
 
27
- parse(file) {
28
- var _arguments = arguments,
29
- _superprop_getParse = () => super.parse,
27
+ parse(_ref) {
28
+ var _superprop_getParse = () => super.parse,
30
29
  _superprop_get_request = () => super._request,
31
30
  _this = this;
32
31
 
33
32
  return _asyncToGenerator(function* () {
34
- var inputType = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : "path";
35
- var version = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : "3";
36
- var cutPdf = _arguments.length > 3 && _arguments[3] !== undefined ? _arguments[3] : true;
37
- var includeWords = _arguments.length > 4 && _arguments[4] !== undefined ? _arguments[4] : false;
33
+ var {
34
+ input,
35
+ inputType = "path",
36
+ filename = undefined,
37
+ version = "3",
38
+ cutPdf = true,
39
+ includeWords = false
40
+ } = _ref;
38
41
  var inputFile = new Input({
39
- file,
42
+ file: input,
40
43
  inputType,
44
+ filename,
41
45
  cutPdf
42
46
  });
43
47
  _this.apiToken = inputFile.fileExtension === "pdf" ? _this.invoiceToken : _this.receiptToken;
@@ -24,30 +24,49 @@ class APIInvoice extends APIObject {
24
24
  */
25
25
 
26
26
 
27
- parse(file) {
28
- var _arguments = arguments,
29
- _superprop_getParse = () => super.parse,
27
+ parse(_ref) {
28
+ var _superprop_getParse = () => super.parse,
30
29
  _superprop_get_request = () => super._request,
31
30
  _this = this;
32
31
 
33
32
  return _asyncToGenerator(function* () {
34
- var inputType = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : "path";
35
- var version = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : "2";
36
- var cutPdf = _arguments.length > 3 && _arguments[3] !== undefined ? _arguments[3] : true;
37
- var includeWords = _arguments.length > 4 && _arguments[4] !== undefined ? _arguments[4] : true;
33
+ var {
34
+ input,
35
+ inputType = "path",
36
+ filename = undefined,
37
+ version = "2",
38
+ cutPdf = true,
39
+ includeWords = false
40
+ } = _ref;
38
41
 
39
42
  _superprop_getParse().call(_this);
40
43
 
41
44
  var inputFile = new Input({
42
- file,
45
+ file: input,
43
46
  inputType,
47
+ filename,
44
48
  cutPdf
45
49
  });
46
50
  yield inputFile.init();
47
51
  var url = "v".concat(version, "/predict");
48
- return yield _superprop_get_request().call(_this, url, inputFile, version, includeWords);
52
+ return yield _superprop_get_request().call(_this, url, inputFile, includeWords);
49
53
  })();
50
54
  }
55
+ /**
56
+ @param {String} inputFile - Input object
57
+ @param {} response - HTTP response
58
+ @param {Document} documentType - Document class in {"Receipt", "Invoice", "Financial_document"}
59
+ @returns {Response}
60
+ */
61
+
62
+
63
+ wrapResponse(inputFile, response, documentType) {
64
+ var _result$httpResponse$, _result$httpResponse$2, _result$httpResponse$3, _result$httpResponse$4, _result$httpResponse$5;
65
+
66
+ var result = super.wrapResponse(inputFile, response, documentType);
67
+ result.documentType = ((_result$httpResponse$ = result.httpResponse.data) === null || _result$httpResponse$ === void 0 ? void 0 : (_result$httpResponse$2 = _result$httpResponse$.predictions) === null || _result$httpResponse$2 === void 0 ? void 0 : (_result$httpResponse$3 = _result$httpResponse$2[0]) === null || _result$httpResponse$3 === void 0 ? void 0 : (_result$httpResponse$4 = _result$httpResponse$3.document_type) === null || _result$httpResponse$4 === void 0 ? void 0 : (_result$httpResponse$5 = _result$httpResponse$4.value) === null || _result$httpResponse$5 === void 0 ? void 0 : _result$httpResponse$5.toLowerCase()) || result.documentType;
68
+ return result;
69
+ }
51
70
 
52
71
  }
53
72
 
@@ -24,28 +24,32 @@ class APIReceipt extends APIObject {
24
24
  */
25
25
 
26
26
 
27
- parse(file) {
28
- var _arguments = arguments,
29
- _superprop_getParse = () => super.parse,
27
+ parse(_ref) {
28
+ var _superprop_getParse = () => super.parse,
30
29
  _superprop_get_request = () => super._request,
31
30
  _this = this;
32
31
 
33
32
  return _asyncToGenerator(function* () {
34
- var inputType = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : "path";
35
- var version = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : "3";
36
- var cutPdf = _arguments.length > 3 && _arguments[3] !== undefined ? _arguments[3] : true;
37
- var includeWords = _arguments.length > 4 && _arguments[4] !== undefined ? _arguments[4] : false;
33
+ var {
34
+ input,
35
+ inputType = "path",
36
+ filename = undefined,
37
+ version = "3",
38
+ cutPdf = true,
39
+ includeWords = false
40
+ } = _ref;
38
41
 
39
42
  _superprop_getParse().call(_this);
40
43
 
41
44
  var inputFile = new Input({
42
- file,
45
+ file: input,
43
46
  inputType,
47
+ filename,
44
48
  cutPdf
45
49
  });
46
50
  yield inputFile.init();
47
51
  var url = "v".concat(version, "/predict");
48
- return yield _superprop_get_request().call(_this, url, inputFile, version, includeWords);
52
+ return yield _superprop_get_request().call(_this, url, inputFile, includeWords);
49
53
  })();
50
54
  }
51
55
 
@@ -25,17 +25,13 @@ var request = function request(url, method, headers, input) {
25
25
  var body;
26
26
  headers["User-Agent"] = "mindee-node/".concat(sdkVersion, " node/").concat(process.version);
27
27
 
28
- if (input.inputType === "path") {
28
+ if (["path", "stream"].includes(input.inputType)) {
29
29
  var fileParams = {
30
30
  filename: input.filename
31
31
  };
32
32
  form.append("file", input.fileObject, fileParams);
33
33
  if (includeWords) form.append("include_mvision", "true");
34
34
  headers = _objectSpread(_objectSpread({}, headers), form.getHeaders());
35
- } else if (input.inputType === "stream") {
36
- form.append("file", input.fileObject);
37
- if (includeWords) form.append("include_mvision", "true");
38
- headers = _objectSpread(_objectSpread({}, headers), form.getHeaders());
39
35
  } else if (input.inputType === "base64") {
40
36
  var body_obj = {
41
37
  file: input.fileObject
@@ -77,9 +77,11 @@ class Document {
77
77
 
78
78
  for (var document of documents) {
79
79
  for (var attribute of attributes) {
80
- var _document$attribute, _document$attribute2;
80
+ var _document$attribute;
81
81
 
82
- if ((document === null || document === void 0 ? void 0 : (_document$attribute = document[attribute]) === null || _document$attribute === void 0 ? void 0 : _document$attribute.probability) > finalDocument[attribute].probability) finalDocument[attribute] = document === null || document === void 0 ? void 0 : (_document$attribute2 = document[attribute]) === null || _document$attribute2 === void 0 ? void 0 : _document$attribute2.probability;
82
+ if ((document === null || document === void 0 ? void 0 : (_document$attribute = document[attribute]) === null || _document$attribute === void 0 ? void 0 : _document$attribute.probability) > finalDocument[attribute].probability) {
83
+ finalDocument[attribute] = document === null || document === void 0 ? void 0 : document[attribute];
84
+ }
83
85
  }
84
86
  }
85
87
 
@@ -14,7 +14,7 @@ class Amount extends Field {
14
14
  prediction,
15
15
  valueKey = "amount",
16
16
  reconstructed = false,
17
- pageNumber = undefined
17
+ pageNumber = 0
18
18
  } = _ref;
19
19
  super({
20
20
  prediction,
@@ -14,7 +14,7 @@ class DateField extends Field {
14
14
  prediction,
15
15
  valueKey = "iso",
16
16
  reconstructed = false,
17
- pageNumber = undefined
17
+ pageNumber = 0
18
18
  } = _ref;
19
19
  super({
20
20
  prediction,
@@ -14,7 +14,7 @@ class Locale extends Field {
14
14
  prediction,
15
15
  valueKey = "value",
16
16
  reconstructed = false,
17
- pageNumber = undefined
17
+ pageNumber = 0
18
18
  } = _ref;
19
19
  super({
20
20
  prediction,
@@ -14,7 +14,7 @@ class Orientation extends Field {
14
14
  prediction,
15
15
  valueKey = "degrees",
16
16
  reconstructed = false,
17
- pageNumber = undefined
17
+ pageNumber = 0
18
18
  } = _ref;
19
19
  var orientations = [0, 90, 180, 270];
20
20
  super({
@@ -26,7 +26,7 @@ class PaymentDetails extends Field {
26
26
  routingNumberKey = "routing_number",
27
27
  swiftKey = "swift",
28
28
  reconstructed = false,
29
- pageNumber = undefined
29
+ pageNumber = 0
30
30
  } = _ref;
31
31
  super({
32
32
  prediction,
@@ -20,7 +20,7 @@ class Tax extends Field {
20
20
  rateKey = "rate",
21
21
  codeKey = "code",
22
22
  reconstructed = false,
23
- pageNumber = undefined
23
+ pageNumber = 0
24
24
  } = _ref;
25
25
  super({
26
26
  prediction,
package/lib/inputs.js CHANGED
@@ -16,6 +16,16 @@ var {
16
16
  PDFDocument
17
17
  } = require("pdf-lib");
18
18
 
19
+ var magic = require("stream-mmmagic");
20
+
21
+ var concat = require("concat-stream");
22
+
23
+ var {
24
+ Base64Encode
25
+ } = require("base64-stream");
26
+
27
+ var ReadableStreamClone = require("readable-stream-clone");
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
@@ -77,7 +87,7 @@ class Input {
77
87
  return _asyncToGenerator(function* () {
78
88
  _this2.fileObject = yield fs.readFile(_this2.file);
79
89
  _this2.filepath = _this2.file;
80
- _this2.filename = path.basename(_this2.file); // Check if file type is valid
90
+ _this2.filename = _this2.filename || path.basename(_this2.file); // Check if file type is valid
81
91
 
82
92
  var filetype = _this2.filename.split(".").pop();
83
93
 
@@ -98,8 +108,16 @@ class Input {
98
108
 
99
109
  return _asyncToGenerator(function* () {
100
110
  _this3.fileObject = _this3.file;
101
- _this3.filepath = undefined;
102
- _this3.filename = undefined;
111
+ _this3.filename = _this3.filename || "stream";
112
+ _this3.filepath = undefined; //Copy the ReadableStream
113
+
114
+ var stream = new ReadableStreamClone(_this3.fileObject);
115
+ _this3.fileObject = new ReadableStreamClone(_this3.fileObject);
116
+ var [mime, output] = yield magic.promise(stream);
117
+
118
+ if (mime.type === "application/pdf" && _this3.allowCutPdf == true) {
119
+ yield _this3.cutPdf();
120
+ }
103
121
  })();
104
122
  }
105
123
 
@@ -109,6 +127,29 @@ class Input {
109
127
  this.filepath = "";
110
128
  this.fileExtension = "";
111
129
  }
130
+ /**
131
+ * Convert ReadableStream to Base64 encoded String
132
+ *
133
+ * @param {*} stream ReadableStream to encode
134
+ * @returns Base64 encoded String
135
+ */
136
+
137
+
138
+ streamToBase64(stream) {
139
+ return _asyncToGenerator(function* () {
140
+ return yield new Promise((resolve, reject) => {
141
+ var base64 = new Base64Encode();
142
+
143
+ var cbConcat = base64 => {
144
+ resolve(base64);
145
+ };
146
+
147
+ stream.pipe(base64).pipe(concat(cbConcat)).on("error", error => {
148
+ reject(error);
149
+ });
150
+ });
151
+ })();
152
+ }
112
153
  /** Cut PDF if pages > 5 */
113
154
 
114
155
 
@@ -117,7 +158,14 @@ class Input {
117
158
 
118
159
  return _asyncToGenerator(function* () {
119
160
  // convert document to PDFDocument & cut CUT_PDF_SIZE - 1 first pages and last page
120
- var pdfDocument = yield PDFDocument.load(_this4.fileObject);
161
+ var pdfDocument;
162
+
163
+ if (_this4.filename == "stream") {
164
+ pdfDocument = yield PDFDocument.load(yield _this4.streamToBase64(_this4.fileObject));
165
+ } else {
166
+ pdfDocument = yield PDFDocument.load(_this4.fileObject);
167
+ }
168
+
121
169
  var splitedPdfDocument = yield PDFDocument.create();
122
170
  var pdfLength = pdfDocument.getPageCount();
123
171
  if (pdfLength <= _this4.CUT_PDF_SIZE) return;
@@ -0,0 +1,40 @@
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({ file: input, inputType, filename, cutPdf });
28
+ this.apiToken =
29
+ inputFile.fileExtension === "pdf" ? this.invoiceToken : this.receiptToken;
30
+ await inputFile.init();
31
+ const url =
32
+ inputFile.fileExtension === "pdf"
33
+ ? "/invoices/v1/predict"
34
+ : "/expense_receipts/v3/predict";
35
+ super.parse();
36
+ return await super._request(url, inputFile, version, includeWords);
37
+ }
38
+ }
39
+
40
+ 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,48 @@
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({ file: input, inputType, filename, cutPdf });
28
+ await inputFile.init();
29
+ const url = `v${version}/predict`;
30
+ return await super._request(url, inputFile, includeWords);
31
+ }
32
+
33
+ /**
34
+ @param {String} inputFile - Input object
35
+ @param {} response - HTTP response
36
+ @param {Document} documentType - Document class in {"Receipt", "Invoice", "Financial_document"}
37
+ @returns {Response}
38
+ */
39
+ wrapResponse(inputFile, response, documentType) {
40
+ let result = super.wrapResponse(inputFile, response, documentType);
41
+ result.documentType =
42
+ result.httpResponse.data?.predictions?.[0]?.document_type?.value?.toLowerCase() ||
43
+ result.documentType;
44
+ return result;
45
+ }
46
+ }
47
+
48
+ 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/products";
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 != 200) {
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,34 @@
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({ file: input, inputType, filename, cutPdf });
28
+ await inputFile.init();
29
+ const url = `v${version}/predict`;
30
+ return await super._request(url, inputFile, includeWords);
31
+ }
32
+ }
33
+
34
+ module.exports = APIReceipt;