mindee 1.1.2 → 1.3.1

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 (46) hide show
  1. package/CHANGELOG.md +47 -26
  2. package/LICENSE +21 -202
  3. package/README.md +15 -2
  4. package/coverage.lcov +0 -0
  5. package/dist/api/financialDocument.js +51 -0
  6. package/dist/api/index.js +13 -0
  7. package/dist/api/invoice.js +59 -0
  8. package/dist/api/object.js +80 -0
  9. package/dist/api/receipt.js +45 -0
  10. package/dist/api/request.js +90 -0
  11. package/dist/api/response.js +91 -0
  12. package/dist/documents/document.js +80 -0
  13. package/dist/documents/fields/amount.js +21 -0
  14. package/dist/documents/fields/date.js +17 -0
  15. package/dist/documents/fields/field.js +85 -0
  16. package/dist/documents/fields/index.js +17 -0
  17. package/dist/documents/fields/locale.js +25 -0
  18. package/dist/documents/fields/orientation.js +22 -0
  19. package/dist/documents/fields/paymentDetails.js +50 -0
  20. package/dist/documents/fields/tax.js +42 -0
  21. package/dist/documents/financialDocument.js +216 -0
  22. package/dist/documents/index.js +13 -0
  23. package/dist/documents/invoice.js +361 -0
  24. package/dist/documents/receipt.js +231 -0
  25. package/dist/errors/handler.js +17 -0
  26. package/dist/index.js +23 -0
  27. package/dist/inputs.js +208 -0
  28. package/dist/logger.js +34 -0
  29. package/lib/api/financialDocument.js +1 -1
  30. package/lib/api/invoice.js +1 -1
  31. package/lib/api/response.js +1 -1
  32. package/lib/documents/fields/field.js +4 -2
  33. package/lib/documents/financialDocument.js +8 -51
  34. package/lib/documents/invoice.js +9 -48
  35. package/lib/documents/receipt.js +5 -5
  36. package/lib/index.js +29 -30
  37. package/lib/inputs.js +2 -0
  38. package/mindee/api/financialDocument.js +3 -3
  39. package/mindee/api/object.js +1 -1
  40. package/mindee/api/request.js +17 -15
  41. package/mindee/api/response.js +19 -3
  42. package/mindee/documents/financialDocument.js +7 -2
  43. package/mindee/documents/invoice.js +4 -5
  44. package/mindee/documents/receipt.js +4 -4
  45. package/mindee/inputs.js +14 -8
  46. package/package.json +5 -5
@@ -0,0 +1,231 @@
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 __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
12
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
13
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
14
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
15
+ };
16
+ var __importDefault = (this && this.__importDefault) || function (mod) {
17
+ return (mod && mod.__esModule) ? mod : { "default": mod };
18
+ };
19
+ var _Receipt_instances, _Receipt_initFromScratch, _Receipt_initFromApiPrediction, _Receipt_checklist, _Receipt_taxesMatchTotal, _Receipt_reconstruct, _Receipt_reconstructTotalExclFromTCCAndTaxes, _Receipt_reconstructTotalTax;
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.Receipt = void 0;
22
+ const document_1 = require("@documents/document");
23
+ const fields_1 = require("@documents/fields");
24
+ const promises_1 = __importDefault(require("fs/promises"));
25
+ class Receipt extends document_1.Document {
26
+ /**
27
+ * @param {Object} apiPrediction - Json parsed prediction from HTTP response
28
+ * @param {Input} input - Input object
29
+ * @param {Integer} pageNumber - Page number for multi pages pdf input
30
+ * @param {Object} locale - locale value for creating Receipt object from scratch
31
+ * @param {Object} totalIncl - total tax Included value for creating Receipt object from scratch
32
+ * @param {Object} date - date value for creating Receipt object from scratch
33
+ * @param {Object} category - category value for creating Receipt object from scratch
34
+ * @param {Object} merchantName - merchant name value for creating Receipt object from scratch
35
+ * @param {Object} time - time value for creating Receipt object from scratch
36
+ * @param {Object} taxes - taxes value for creating Receipt object from scratch
37
+ * @param {Object} orientation - orientation value for creating Receipt object from scratch
38
+ * @param {Object} totalTax - total taxes value for creating Receipt object from scratch
39
+ * @param {Object} totalExcl - total taxes excluded value for creating Receipt object from scratch
40
+ * @param {String} level - specify whether object is built from "page" level or "document" level prediction
41
+ */
42
+ constructor({ apiPrediction = undefined, inputFile = undefined, locale = undefined, totalIncl = undefined, date = undefined, category = undefined, merchantName = undefined, time = undefined, taxes = undefined, orientation = undefined, totalTax = undefined, totalExcl = undefined, words = undefined, pageNumber = 0, level = "page", }) {
43
+ super(inputFile);
44
+ _Receipt_instances.add(this);
45
+ this.level = level;
46
+ this.constructPrediction = function (item) {
47
+ return { prediction: { value: item }, valueKey: "value", pageNumber };
48
+ };
49
+ if (apiPrediction === undefined) {
50
+ __classPrivateFieldGet(this, _Receipt_instances, "m", _Receipt_initFromScratch).call(this, {
51
+ locale,
52
+ totalExcl,
53
+ totalIncl,
54
+ date,
55
+ category,
56
+ merchantName,
57
+ time,
58
+ taxes,
59
+ orientation,
60
+ totalTax,
61
+ pageNumber,
62
+ });
63
+ }
64
+ else {
65
+ __classPrivateFieldGet(this, _Receipt_instances, "m", _Receipt_initFromApiPrediction).call(this, apiPrediction, pageNumber, words);
66
+ }
67
+ __classPrivateFieldGet(this, _Receipt_instances, "m", _Receipt_checklist).call(this);
68
+ __classPrivateFieldGet(this, _Receipt_instances, "m", _Receipt_reconstruct).call(this);
69
+ }
70
+ toString() {
71
+ return `
72
+ -----Receipt data-----
73
+ Filename: ${this.filename}
74
+ Total amount: ${this.totalIncl.value}
75
+ Date: ${this.date.value}
76
+ Category: ${this.category.value}
77
+ Time: ${this.time.value}
78
+ Merchant name: ${this.merchantName.value}
79
+ Taxes: ${this.taxes.map((tax) => tax.toString()).join(" - ")}
80
+ Total taxes: ${this.totalTax.value}
81
+ `;
82
+ }
83
+ static load(path) {
84
+ return __awaiter(this, void 0, void 0, function* () {
85
+ const file = promises_1.default.readFile(path);
86
+ const args = JSON.parse(file);
87
+ return new Receipt(Object.assign({ reconsctruted: true }, args));
88
+ });
89
+ }
90
+ }
91
+ exports.Receipt = Receipt;
92
+ _Receipt_instances = new WeakSet(), _Receipt_initFromScratch = function _Receipt_initFromScratch({ locale, totalExcl, totalIncl, date, category, merchantName, time, taxes, orientation, totalTax, pageNumber, }) {
93
+ this.locale = new fields_1.Locale(this.constructPrediction(locale));
94
+ this.totalIncl = new fields_1.Amount(this.constructPrediction(totalIncl));
95
+ this.date = new fields_1.DateField(this.constructPrediction(date));
96
+ this.category = new fields_1.Field(this.constructPrediction(category));
97
+ this.merchantName = new fields_1.Field(this.constructPrediction(merchantName));
98
+ this.time = new fields_1.Field(this.constructPrediction(time));
99
+ if (taxes !== undefined) {
100
+ this.taxes = [];
101
+ for (const t of taxes) {
102
+ this.taxes.push(new fields_1.Tax({
103
+ prediction: { value: t[0], rate: t[1] },
104
+ pageNumber,
105
+ valueKey: "value",
106
+ rateKey: "rate",
107
+ }));
108
+ }
109
+ }
110
+ this.orientation = new fields_1.Orientation(this.constructPrediction(orientation));
111
+ this.totalTax = new fields_1.Amount(this.constructPrediction(totalTax));
112
+ this.totalExcl = new fields_1.Amount(this.constructPrediction(totalExcl));
113
+ }, _Receipt_initFromApiPrediction = function _Receipt_initFromApiPrediction(apiPrediction, pageNumber, words) {
114
+ this.locale = new fields_1.Locale({ prediction: apiPrediction.locale, pageNumber });
115
+ this.totalIncl = new fields_1.Amount({
116
+ prediction: apiPrediction.total_incl,
117
+ valueKey: "value",
118
+ pageNumber,
119
+ });
120
+ this.date = new fields_1.DateField({
121
+ prediction: apiPrediction.date,
122
+ valueKey: "value",
123
+ pageNumber,
124
+ });
125
+ this.category = new fields_1.Field({
126
+ prediction: apiPrediction.category,
127
+ pageNumber,
128
+ });
129
+ this.merchantName = new fields_1.Field({
130
+ prediction: apiPrediction.supplier,
131
+ valueKey: "value",
132
+ pageNumber,
133
+ });
134
+ this.time = new fields_1.Field({
135
+ prediction: apiPrediction.time,
136
+ valueKey: "value",
137
+ pageNumber,
138
+ });
139
+ this.taxes = apiPrediction.taxes.map((taxPrediction) => new fields_1.Tax({
140
+ prediction: taxPrediction,
141
+ pageNumber,
142
+ valueKey: "value",
143
+ rateKey: "rate",
144
+ codeKey: "code",
145
+ }));
146
+ this.totalTax = new fields_1.Amount({
147
+ prediction: { value: undefined, confidence: 0 },
148
+ valueKey: "value",
149
+ pageNumber,
150
+ });
151
+ this.totalExcl = new fields_1.Amount({
152
+ prediction: { value: undefined, confidence: 0 },
153
+ valueKey: "value",
154
+ pageNumber,
155
+ });
156
+ if (this.level === "page") {
157
+ this.orientation = new fields_1.Orientation({
158
+ prediction: apiPrediction.orientation,
159
+ pageNumber,
160
+ });
161
+ }
162
+ else {
163
+ this.orientation = new fields_1.Orientation(this.constructPrediction({
164
+ prediction: {
165
+ value: undefined,
166
+ confidence: 0.0,
167
+ degrees: undefined,
168
+ },
169
+ }));
170
+ }
171
+ if (words && words.length > 0)
172
+ this.words = words;
173
+ }, _Receipt_checklist = function _Receipt_checklist() {
174
+ this.checklist = { taxesMatchTotalIncl: __classPrivateFieldGet(this, _Receipt_instances, "m", _Receipt_taxesMatchTotal).call(this) };
175
+ }, _Receipt_taxesMatchTotal = function _Receipt_taxesMatchTotal() {
176
+ // Check taxes and total amount exist
177
+ if (this.taxes.length === 0 || this.totalIncl.value == null)
178
+ return false;
179
+ // Reconstruct total_incl from taxes
180
+ let totalVat = 0;
181
+ let reconstructedTotal = 0;
182
+ this.taxes.forEach((tax) => {
183
+ if (tax.value == null || !tax.rate)
184
+ return false;
185
+ totalVat += tax.value;
186
+ reconstructedTotal += tax.value + (100 * tax.value) / tax.rate;
187
+ });
188
+ // Sanity check
189
+ if (totalVat <= 0)
190
+ return false;
191
+ // Crate epsilon
192
+ const eps = 1 / (100 * totalVat);
193
+ if (this.totalIncl.value * (1 - eps) - 0.02 <= reconstructedTotal &&
194
+ reconstructedTotal <= this.totalIncl.value * (1 + eps) + 0.02) {
195
+ this.taxes = this.taxes.map((tax) => (Object.assign(Object.assign({}, tax), { probability: 1.0 })));
196
+ this.totalTax.probability = 1.0;
197
+ this.totalIncl.probability = 1.0;
198
+ return true;
199
+ }
200
+ return false;
201
+ }, _Receipt_reconstruct = function _Receipt_reconstruct() {
202
+ __classPrivateFieldGet(this, _Receipt_instances, "m", _Receipt_reconstructTotalExclFromTCCAndTaxes).call(this);
203
+ __classPrivateFieldGet(this, _Receipt_instances, "m", _Receipt_reconstructTotalTax).call(this);
204
+ }, _Receipt_reconstructTotalExclFromTCCAndTaxes = function _Receipt_reconstructTotalExclFromTCCAndTaxes() {
205
+ if (this.taxes.length && this.totalIncl.value != null) {
206
+ const totalExcl = {
207
+ value: this.totalIncl.value - fields_1.Field.arraySum(this.taxes),
208
+ confidence: fields_1.Field.arrayProbability(this.taxes) * this.totalIncl.probability,
209
+ };
210
+ this.totalExcl = new fields_1.Amount({
211
+ prediction: totalExcl,
212
+ valueKey: "value",
213
+ reconstructed: true,
214
+ });
215
+ }
216
+ }, _Receipt_reconstructTotalTax = function _Receipt_reconstructTotalTax() {
217
+ if (this.taxes.length && this.totalTax.value == null) {
218
+ const totalTax = {
219
+ value: this.taxes
220
+ .map((tax) => tax.value || 0)
221
+ .reduce((a, b) => a + b, 0),
222
+ confidence: fields_1.Field.arrayProbability(this.taxes),
223
+ };
224
+ if (totalTax.value > 0)
225
+ this.totalTax = new fields_1.Amount({
226
+ prediction: totalTax,
227
+ valueKey: "value",
228
+ reconstructed: true,
229
+ });
230
+ }
231
+ };
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.errorHandler = void 0;
4
+ const logger_1 = require("@mindee/logger");
5
+ class ErrorHandler {
6
+ constructor(throwOnError = true) {
7
+ this.throwOnError = throwOnError;
8
+ this.throwOnError = throwOnError;
9
+ }
10
+ throw(error) {
11
+ if (this.throwOnError || force)
12
+ throw error;
13
+ else
14
+ logger_1.logger.error(error.message);
15
+ }
16
+ }
17
+ exports.errorHandler = new ErrorHandler();
package/dist/index.js ADDED
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Client = void 0;
4
+ const handler_1 = require("@errors/handler");
5
+ const logger_1 = require("@mindee/logger");
6
+ const receipt_1 = require("@mindee/api/receipt");
7
+ const invoice_1 = require("@mindee/api/invoice");
8
+ const financialDocument_1 = require("@mindee/api/financialDocument");
9
+ class Client {
10
+ constructor({ receiptToken, invoiceToken, throwOnError = true, debug, }) {
11
+ this.receiptToken = receiptToken || process.env.MINDEE_RECEIPT_TOKEN;
12
+ this.invoiceToken = invoiceToken || process.env.MINDEE_INVOICE_TOKEN;
13
+ handler_1.errorHandler.throwOnError = throwOnError;
14
+ logger_1.logger.level = (debug !== null && debug !== void 0 ? debug : process.env.MINDEE_DEBUG) ? "debug" : "warn";
15
+ this.receipt = new receipt_1.APIReceipt(this.receiptToken);
16
+ this.invoice = new invoice_1.APIInvoice(this.invoiceToken);
17
+ this.financialDocument = new financialDocument_1.APIFinancialDocument(this.invoiceToken, this.receiptToken);
18
+ }
19
+ }
20
+ exports.Client = Client;
21
+ exports.documents = require("./documents");
22
+ exports.api = require("./api");
23
+ exports.inputs = require("./inputs");
package/dist/inputs.js ADDED
@@ -0,0 +1,208 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __importDefault = (this && this.__importDefault) || function (mod) {
35
+ return (mod && mod.__esModule) ? mod : { "default": mod };
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ exports.Input = void 0;
39
+ // const fs = require("fs").promises;
40
+ // const errorHandler = require("./errors/handler");
41
+ // const path = require("path");
42
+ // const { PDFDocument } = require("pdf-lib");
43
+ // const concat = require("concat-stream");
44
+ // const { Base64Encode } = require("base64-stream");
45
+ // const fileType = require("file-type");
46
+ // const ArrayBufferEncode = require("base64-arraybuffer");
47
+ const promises_1 = __importDefault(require("fs/promises"));
48
+ const path = __importStar(require("path"));
49
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
50
+ // @ts-ignore
51
+ const concat = __importStar(require("concat-stream"));
52
+ const base64_stream_1 = require("base64-stream");
53
+ const fileType = __importStar(require("file-type"));
54
+ const ArrayBufferEncode = __importStar(require("base64-arraybuffer"));
55
+ const handler_1 = require("@errors/handler");
56
+ const pdf_lib_1 = require("pdf-lib");
57
+ class Input {
58
+ /**
59
+ * @param {(String | Buffer)} file - the file that will be read. Either path or base64 string, or a steam
60
+ * @param {String} inputType - the type of input used in file ("base64", "path", "dummy").
61
+ * NB: dummy is only used for tests purposes
62
+ * @param {String} filename - File name of the input
63
+ * @param allowCutPdf
64
+ * NB: Because of async calls, init() should be called after creating the object
65
+ */
66
+ constructor(file, inputType, allowCutPdf = true, filename) {
67
+ this.file = file;
68
+ this.inputType = inputType;
69
+ this.allowCutPdf = allowCutPdf;
70
+ this.filename = filename;
71
+ this.MIMETYPES = {
72
+ png: "image/png",
73
+ jpg: "image/jpg",
74
+ jpeg: "image/jpeg",
75
+ webp: "image/webp",
76
+ pdf: "application/pdf",
77
+ };
78
+ this.ALLOWED_INPUT_TYPE = ["base64", "path", "stream", "dummy"];
79
+ this.CUT_PDF_SIZE = 5;
80
+ // Check if inputType is valid
81
+ if (!this.ALLOWED_INPUT_TYPE.includes(inputType)) {
82
+ handler_1.errorHandler.throw(new Error(`The input type is invalid. It should be \
83
+ ${this.ALLOWED_INPUT_TYPE.toString()}`));
84
+ }
85
+ this.file = file;
86
+ this.filename = filename;
87
+ this.inputType = inputType;
88
+ this.allowCutPdf = allowCutPdf;
89
+ }
90
+ init() {
91
+ return __awaiter(this, void 0, void 0, function* () {
92
+ if (this.inputType === "base64")
93
+ yield this.initBase64();
94
+ else if (this.inputType === "path")
95
+ yield this.initFile();
96
+ else if (this.inputType === "stream")
97
+ yield this.initStream();
98
+ else
99
+ this.initDummy();
100
+ });
101
+ }
102
+ initBase64() {
103
+ return __awaiter(this, void 0, void 0, function* () {
104
+ this.fileObject = this.file;
105
+ this.filepath = undefined;
106
+ if (this.filename === undefined) {
107
+ const mimeType = yield fileType.fromBuffer(Buffer.from(this.fileObject, "base64"));
108
+ if (mimeType !== undefined) {
109
+ this.fileExtension = mimeType.mime;
110
+ this.filename = `from_${this.inputType}.${mimeType.ext}`;
111
+ }
112
+ else {
113
+ throw "Could not determine the MIME type. Please specify the 'filename' option.";
114
+ }
115
+ }
116
+ else {
117
+ const filetype = this.filename.split(".").pop();
118
+ this.fileExtension = this.MIMETYPES[filetype];
119
+ }
120
+ if (this.fileExtension === "application/pdf" && this.allowCutPdf == true) {
121
+ yield this.cutPdf();
122
+ }
123
+ });
124
+ }
125
+ initFile() {
126
+ var _a;
127
+ return __awaiter(this, void 0, void 0, function* () {
128
+ this.fileObject = yield promises_1.default.readFile(this.file);
129
+ this.filepath = this.file;
130
+ if (typeof this.file === "string") {
131
+ this.filename = this.filename || path.basename(this.file);
132
+ }
133
+ // Check if file type is valid
134
+ const filetype = (_a = this.filename) === null || _a === void 0 ? void 0 : _a.split(".").pop();
135
+ if (!filetype || !(filetype in this.MIMETYPES)) {
136
+ handler_1.errorHandler.throw(new Error(`File type is not allowed. It must be ${Object.keys(this.MIMETYPES).toString()}`));
137
+ }
138
+ this.fileExtension = filetype ? this.MIMETYPES[filetype] : "";
139
+ if (this.fileExtension === "application/pdf" && this.allowCutPdf) {
140
+ yield this.cutPdf();
141
+ }
142
+ });
143
+ }
144
+ initStream() {
145
+ return __awaiter(this, void 0, void 0, function* () {
146
+ this.file = (yield this.streamToBase64(this.file));
147
+ this.inputType = "base64";
148
+ yield this.initBase64();
149
+ });
150
+ }
151
+ initDummy() {
152
+ this.fileObject = "";
153
+ this.filename = "";
154
+ this.filepath = "";
155
+ this.fileExtension = "";
156
+ }
157
+ /**
158
+ * Convert ReadableStream to Base64 encoded String
159
+ *
160
+ * @param {*} stream ReadableStream to encode
161
+ * @returns Base64 encoded String
162
+ */
163
+ streamToBase64(stream) {
164
+ return __awaiter(this, void 0, void 0, function* () {
165
+ return new Promise((resolve, reject) => {
166
+ const base64 = new base64_stream_1.Base64Encode();
167
+ const cbConcat = (base64) => {
168
+ resolve(base64);
169
+ };
170
+ stream
171
+ .pipe(base64)
172
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
173
+ // @ts-ignore TO DO : FIX
174
+ .pipe(concat(cbConcat))
175
+ .on("error", (error) => {
176
+ reject(error);
177
+ });
178
+ });
179
+ });
180
+ }
181
+ /** Cut PDF if pages > 5 */
182
+ cutPdf() {
183
+ return __awaiter(this, void 0, void 0, function* () {
184
+ // convert document to PDFDocument & cut CUT_PDF_SIZE - 1 first pages and last page
185
+ const pdfDocument = yield pdf_lib_1.PDFDocument.load(this.fileObject, {
186
+ ignoreEncryption: true,
187
+ });
188
+ const splitedPdfDocument = yield pdf_lib_1.PDFDocument.create();
189
+ const pdfLength = pdfDocument.getPageCount();
190
+ if (pdfLength <= this.CUT_PDF_SIZE)
191
+ return;
192
+ const pagesNumbers = [
193
+ ...Array(this.CUT_PDF_SIZE - 1).keys(),
194
+ pdfLength - 1,
195
+ ];
196
+ const pages = yield splitedPdfDocument.copyPages(pdfDocument, pagesNumbers);
197
+ pages.forEach((page) => splitedPdfDocument.addPage(page));
198
+ const data = yield splitedPdfDocument.save();
199
+ if (this.inputType === "path") {
200
+ this.fileObject = Buffer.from(data);
201
+ }
202
+ else if (this.inputType === "base64") {
203
+ this.fileObject = ArrayBufferEncode.encode(data);
204
+ }
205
+ });
206
+ }
207
+ }
208
+ exports.Input = Input;
package/dist/logger.js ADDED
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.logger = void 0;
4
+ const LOGGER_LEVELS = {
5
+ debug: 0,
6
+ info: 1,
7
+ warn: 2,
8
+ error: 3,
9
+ };
10
+ class Logger {
11
+ constructor(level = "debug") {
12
+ this.level = level;
13
+ if (!(level in LOGGER_LEVELS))
14
+ level = "debug";
15
+ this.level = LOGGER_LEVELS[level];
16
+ }
17
+ debug(...args) {
18
+ if (this.level <= LOGGER_LEVELS["debug"])
19
+ console.debug(args);
20
+ }
21
+ info(...args) {
22
+ if (this.level <= LOGGER_LEVELS["info"])
23
+ console.info(args);
24
+ }
25
+ warn(...args) {
26
+ if (this.level <= LOGGER_LEVELS["warn"])
27
+ console.warn(args);
28
+ }
29
+ error(...args) {
30
+ if (this.level <= LOGGER_LEVELS["error"])
31
+ console.error(args);
32
+ }
33
+ }
34
+ exports.logger = new Logger();
@@ -46,7 +46,7 @@ class APIFinancialDocument extends APIObject {
46
46
  });
47
47
  yield inputFile.init();
48
48
  _this.apiToken = inputFile.fileExtension === "application/pdf" ? _this.invoiceToken : _this.receiptToken;
49
- var url = inputFile.fileExtension === "application/pdf" ? "/invoices/v3/predict" : "/expense_receipts/v3/predict";
49
+ var url = inputFile.fileExtension === "application/pdf" ? "/invoices/v2/predict" : "/expense_receipts/v3/predict";
50
50
 
51
51
  _superprop_getParse().call(_this);
52
52
 
@@ -34,7 +34,7 @@ class APIInvoice extends APIObject {
34
34
  input,
35
35
  inputType = "path",
36
36
  filename = undefined,
37
- version = "3",
37
+ version = "2",
38
38
  cutPdf = true,
39
39
  includeWords = false
40
40
  } = _ref;
@@ -82,7 +82,7 @@ class Response {
82
82
  this[this.documentType] = constructors[this.documentType]({
83
83
  apiPrediction: this.httpResponse.data.document.inference.prediction,
84
84
  inputFile: this.input,
85
- pageNumber: this.httpResponse.data.document.n_pages,
85
+ pageNumber: -1,
86
86
  level: "document"
87
87
  });
88
88
  }
@@ -19,11 +19,13 @@ class Field {
19
19
  this.pageNumber = pageNumber;
20
20
  this.reconstructed = reconstructed;
21
21
  this.value = undefined;
22
- this.probability = prediction.confidence ? prediction.confidence : 0.0;
23
- this.bbox = prediction.polygon ? prediction.polygon : [];
22
+ this.probability = 0.0;
23
+ this.bbox = [];
24
24
 
25
25
  if (valueKey in prediction && prediction[valueKey] !== null) {
26
26
  this.value = prediction[valueKey];
27
+ if (prediction.probability) this.probability = prediction.probability;
28
+ if (prediction.segmentation) this.bbox = prediction.segmentation.bounding_box || [];
27
29
 
28
30
  if (extraFields) {
29
31
  for (var fieldName of extraFields) {