-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcli.py
More file actions
548 lines (511 loc) · 18.4 KB
/
cli.py
File metadata and controls
548 lines (511 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
import json
from argparse import ArgumentParser, Namespace
from dataclasses import dataclass
from typing import Dict, Generic, Optional, Type, Union
from mindee import product
from mindee.client import Client, Endpoint
from mindee.error.mindee_error import MindeeClientError
from mindee.input.page_options import PageOptions
from mindee.input.sources import LocalInputSource, UrlInputSource
from mindee.parsing.common.async_predict_response import AsyncPredictResponse
from mindee.parsing.common.document import Document, serialize_for_json
from mindee.parsing.common.feedback_response import FeedbackResponse
from mindee.parsing.common.inference import Inference, TypeInference
from mindee.parsing.common.predict_response import PredictResponse
from mindee.parsing.common.string_dict import StringDict
@dataclass
class CommandConfig(Generic[TypeInference]):
"""Configuration for a command."""
help: str
doc_class: Type[TypeInference]
is_sync: bool
is_async: bool
DOCUMENTS: Dict[str, CommandConfig] = {
# "address-proof": CommandConfig(
# help="Address Proof",
# doc_class=product.AddressProofV1,
# is_sync=False,
# is_async=True,
# ),
"barcode-reader": CommandConfig(
help="Barcode-reader tool",
doc_class=product.BarcodeReaderV1,
is_sync=True,
is_async=False,
),
"cropper": CommandConfig(
help="Cropper tool",
doc_class=product.CropperV1,
is_sync=True,
is_async=False,
),
"custom": CommandConfig(
help="Custom document type from API builder",
doc_class=product.CustomV1,
is_sync=True,
is_async=False,
),
"eu-license-plate": CommandConfig(
help="EU License Plate",
doc_class=product.eu.LicensePlateV1,
is_sync=True,
is_async=False,
),
"driver-license": CommandConfig(
help="Driver License",
doc_class=product.DriverLicenseV1,
is_sync=False,
is_async=True,
),
"financial-document": CommandConfig(
help="Financial Document (receipt or invoice)",
doc_class=product.FinancialDocumentV1,
is_sync=True,
is_async=True,
),
"fr-bank-account-details": CommandConfig(
help="FR Bank Account Details",
doc_class=product.fr.BankAccountDetailsV2,
is_sync=True,
is_async=False,
),
"fr-carte-grise": CommandConfig(
help="FR Carte Grise",
doc_class=product.fr.CarteGriseV1,
is_sync=True,
is_async=False,
),
"fr-health-card": CommandConfig(
help="FR Health Card",
doc_class=product.fr.HealthCardV1,
is_sync=False,
is_async=True,
),
"fr-id-card": CommandConfig(
help="FR ID Card",
doc_class=product.fr.IdCardV2,
is_sync=True,
is_async=False,
),
"fr-payslip": CommandConfig(
help="FR Payslip",
doc_class=product.fr.PayslipV3,
is_sync=False,
is_async=True,
),
"fr-petrol-receipt": CommandConfig(
help="FR Petrol Receipt",
doc_class=product.fr.PetrolReceiptV1,
is_sync=True,
is_async=False,
),
"generated": CommandConfig(
help="Generated",
doc_class=product.GeneratedV1,
is_sync=True,
is_async=True,
),
"invoice": CommandConfig(
help="Invoice",
doc_class=product.InvoiceV4,
is_sync=True,
is_async=True,
),
"international-id": CommandConfig(
help="International ID",
doc_class=product.InternationalIdV2,
is_sync=False,
is_async=True,
),
"invoice-splitter": CommandConfig(
help="Invoice Splitter",
doc_class=product.InvoiceSplitterV1,
is_sync=False,
is_async=True,
),
"material-certificate": CommandConfig(
help="Material Certificate",
doc_class=product.MaterialCertificateV1,
is_sync=False,
is_async=True,
),
"multi-receipts": CommandConfig(
help="Multi-receipts detector",
doc_class=product.MultiReceiptsDetectorV1,
is_sync=True,
is_async=False,
),
"passport": CommandConfig(
help="Passport",
doc_class=product.PassportV1,
is_sync=True,
is_async=False,
),
"receipt": CommandConfig(
help="Expense Receipt",
doc_class=product.ReceiptV5,
is_sync=True,
is_async=False,
),
"resume": CommandConfig(
help="Resume",
doc_class=product.ResumeV1,
is_sync=False,
is_async=True,
),
"us-bank-check": CommandConfig(
help="US Bank Check",
doc_class=product.us.BankCheckV1,
is_sync=True,
is_async=False,
),
"us-mail": CommandConfig(
help="US Mail",
doc_class=product.us.UsMailV3,
is_sync=False,
is_async=True,
),
"us-healthcare-card": CommandConfig(
help="US Healthcare Card",
doc_class=product.us.HealthcareCardV1,
is_sync=False,
is_async=True,
),
"us-w9": CommandConfig(
help="US W9",
doc_class=product.us.W9V1,
is_sync=True,
is_async=False,
),
}
class MindeeArgumentParser(ArgumentParser):
"""Custom parser to simplify adding various options."""
def add_main_options(self) -> None:
"""Adds main options for most parsings."""
self.add_argument(
"-k",
"--key",
dest="api_key",
help="API key for the account",
required=False,
default=None,
)
def add_display_options(self) -> None:
"""Adds options related to output/display of a document (parse, parse-queued)."""
self.add_argument(
"-o",
"--output-type",
dest="output_type",
choices=["summary", "raw", "parsed"],
default="summary",
help="Specify how to output the data.\n"
"- summary: a basic summary (default)\n"
"- raw: the raw HTTP response\n"
"- parsed: the validated and parsed data fields\n",
)
def add_sending_options(self) -> None:
"""Adds options for sending requests (parse, enqueue)."""
self.add_argument(
"-i",
"--input-type",
dest="input_type",
choices=["path", "file", "base64", "bytes", "url"],
default="path",
help="Specify how to handle the input.\n"
"- path: open a path (default).\n"
"- file: open as a file handle.\n"
"- base64: open a base64 encoded text file.\n"
"- bytes: open the contents as raw bytes.\n"
"- url: open an URL.",
)
self.add_argument(
"-c",
"--cut-doc",
dest="cut_doc",
action="store_true",
help="Cut document pages",
)
self.add_argument(
"-p",
"--pages-keep",
dest="doc_pages",
type=int,
default=5,
help="Number of document pages to keep, default: 5",
)
self.add_argument(dest="path", help="Full path to the file")
def add_feedback_options(self) -> None:
"""Adds the option to give feedback manually."""
self.add_argument(
dest="document_id",
help="Mindee UUID of the document.",
type=str,
)
self.add_argument(
dest="feedback",
type=json.loads,
help='Feedback JSON string to send, ex \'{"key": "value"}\'.',
)
def add_custom_options(self) -> None:
"""Adds options to custom-type documents."""
self.add_argument(
"-a",
"--account",
dest="account_name",
required=True,
help="API account name for the endpoint (required)",
)
self.add_argument(
"-e",
"--endpoint",
dest="endpoint_name",
help="API endpoint name (required)",
required=True,
)
self.add_argument(
"-v",
"--version",
default="1",
dest="api_version",
help="Version for the endpoint. If not set, use the latest version of the model.",
)
class MindeeParser:
"""Custom parser for the Mindee CLI."""
parser: MindeeArgumentParser
"""Parser options."""
parsed_args: Namespace
"""Stores attributes relating to parsing."""
client: Client
"""Mindee client"""
document_info: CommandConfig
"""Config of the document."""
input_doc: Union[LocalInputSource, UrlInputSource]
"""Document to be parsed."""
product_class: Type[Inference]
"""Product to parse."""
feedback: Optional[StringDict]
"""Dict representation of a feedback."""
def __init__(
self,
parser: Optional[MindeeArgumentParser] = None,
parsed_args: Optional[Namespace] = None,
client: Optional[Client] = None,
document_info: Optional[CommandConfig] = None,
) -> None:
self.parser = (
parser if parser else MindeeArgumentParser(description="Mindee_API")
)
self.parsed_args = parsed_args if parsed_args else self._set_args()
self.client = (
client
if client
else Client(
api_key=(
self.parsed_args.api_key if "api_key" in self.parsed_args else None
)
)
)
self._set_input()
self.document_info = (
document_info if document_info else DOCUMENTS[self.parsed_args.product_name]
)
def call_endpoint(self) -> None:
"""Calls the proper type of endpoint according to given command."""
if self.parsed_args.parse_type == "parse":
self.call_parse()
else:
self.call_feedback()
def call_feedback(self) -> None:
"""Sends feedback to an API."""
custom_endpoint: Optional[Endpoint] = None
if self.parsed_args.product_name in ("custom", "generated"):
custom_endpoint = self.client.create_endpoint(
self.parsed_args.endpoint_name,
self.parsed_args.account_name,
self.parsed_args.api_version,
)
if self.feedback is None:
raise MindeeClientError("Invalid feedback provided.")
response: FeedbackResponse = self.client.send_feedback(
self.document_info.doc_class,
self.parsed_args.document_id,
{"feedback": self.feedback},
custom_endpoint,
)
print(json.dumps(response.feedback, indent=2))
def call_parse(self) -> None:
"""Calls an endpoint with the appropriate method, and displays the results."""
response: Union[PredictResponse, AsyncPredictResponse]
if self.document_info.is_sync:
if self.document_info.is_async:
if (
self.parsed_args.async_parse is not None
and self.parsed_args.async_parse
):
response = self._parse_async()
else:
response = self._parse_sync()
else:
response = self._parse_sync()
else:
if self.document_info.is_async:
response = self._parse_async()
else:
response = self._parse_sync()
if self.parsed_args.output_type == "raw":
print(response.raw_http)
else:
if response.document is None:
raise MindeeClientError("Something went wrong during async parsing.")
# print the OCR
if self.parsed_args.include_words:
print("#############\nDocument Text\n#############\n::\n")
print(" " + str(response.document.ocr).replace("\n", "\n "))
# print the response as rST
print(self._doc_str(self.parsed_args.output_type, response.document))
def _parse_sync(self) -> PredictResponse:
"""Processes the results of a synchronous request."""
page_options: Optional[PageOptions] = None
if self.parsed_args.cut_doc and self.parsed_args.doc_pages:
page_options = PageOptions(
range(self.parsed_args.doc_pages), on_min_pages=0
)
custom_endpoint: Optional[Endpoint] = None
if self.parsed_args.product_name in ("custom", "generated"):
include_words = False
custom_endpoint = self.client.create_endpoint(
self.parsed_args.endpoint_name,
self.parsed_args.account_name,
self.parsed_args.api_version,
)
else:
include_words = self.parsed_args.include_words
return self.client.parse(
product_class=self.document_info.doc_class,
input_source=self.input_doc,
include_words=include_words,
page_options=page_options,
endpoint=custom_endpoint,
)
def _parse_async(self) -> AsyncPredictResponse:
"""Enqueues and processes the results of an asynchronous request."""
page_options: Optional[PageOptions] = None
if self.parsed_args.cut_doc and self.parsed_args.doc_pages:
page_options = PageOptions(
range(self.parsed_args.doc_pages), on_min_pages=0
)
custom_endpoint: Optional[Endpoint] = None
if self.parsed_args.product_name in ("custom", "generated"):
include_words = False
custom_endpoint = self.client.create_endpoint(
self.parsed_args.endpoint_name,
self.parsed_args.account_name,
self.parsed_args.api_version,
)
else:
include_words = self.parsed_args.include_words
return self.client.enqueue_and_parse(
product_class=self.document_info.doc_class,
input_source=self.input_doc,
include_words=include_words,
page_options=page_options,
endpoint=custom_endpoint,
)
@staticmethod
def _doc_str(output_type: str, doc_response: Document) -> str:
if output_type == "parsed":
return json.dumps(doc_response, indent=2, default=serialize_for_json)
return str(doc_response)
def _set_args(self) -> Namespace:
"""Parse command line arguments."""
parse_product_subparsers = self.parser.add_subparsers(
dest="product_name",
required=True,
)
for name, info in DOCUMENTS.items():
parse_subparser = parse_product_subparsers.add_parser(name, help=info.help)
call_parser = parse_subparser.add_subparsers(
dest="parse_type", required=True
)
parse_subp = call_parser.add_parser("parse")
feedback_subp = call_parser.add_parser("feedback")
parse_subp.add_main_options()
parse_subp.add_sending_options()
parse_subp.add_display_options()
if name in ("custom", "generated"):
parse_subp.add_custom_options()
else:
parse_subp.add_argument(
"-t",
"--full-text",
dest="include_words",
action="store_true",
help="include full document text in response",
)
if info.is_async and info.is_sync:
parse_subp.add_argument(
"-A",
"--asynchronous",
dest="async_parse",
help="Parse asynchronously",
action="store_true",
required=False,
default=False,
)
feedback_subp.add_main_options()
feedback_subp.add_feedback_options()
parsed_args = self.parser.parse_args()
return parsed_args
def _get_input_doc(self) -> Union[LocalInputSource, UrlInputSource]:
"""Loads an input document."""
if self.parsed_args.input_type == "file":
with open(self.parsed_args.path, "rb", buffering=30) as file_handle:
return self.client.source_from_file(file_handle)
elif self.parsed_args.input_type == "base64":
with open(self.parsed_args.path, "rt", encoding="ascii") as base64_handle:
return self.client.source_from_b64string(
base64_handle.read(), "test.jpg"
)
elif self.parsed_args.input_type == "bytes":
with open(self.parsed_args.path, "rb") as bytes_handle:
return self.client.source_from_bytes(
bytes_handle.read(), bytes_handle.name
)
elif self.parsed_args.input_type == "url":
return self.client.source_from_url(self.parsed_args.path)
return self.client.source_from_path(self.parsed_args.path)
def _get_feedback_doc(self) -> StringDict:
"""Loads a feedback."""
json_doc: StringDict = {}
if self.parsed_args.input_type == "file":
with open(self.parsed_args.path, "rb", buffering=30) as f_f:
json_doc = json.loads(f_f.read())
elif self.parsed_args.input_type == "base64":
with open(self.parsed_args.path, "rt", encoding="ascii") as f_b64:
json_doc = json.loads(f_b64.read())
elif self.parsed_args.input_type == "bytes":
with open(self.parsed_args.path, "rb") as f_b:
json_doc = json.loads(f_b.read())
else:
if (
not self.parsed_args.feedback
or "feedback" not in self.parsed_args.feedback
):
raise MindeeClientError("Invalid feedback.")
if not json_doc or "feedback" not in json_doc:
raise MindeeClientError("Invalid feedback.")
return json_doc
def _set_input(self) -> None:
"""Loads an input document, or a feedback document."""
self.feedback = None
if self.parsed_args.parse_type == "feedback":
if not self.parsed_args.feedback:
self.feedback = self._get_feedback_doc()
else:
self.feedback = self.parsed_args.feedback
else:
self.input_doc = self._get_input_doc()
def main() -> None:
"""Run the Command Line Interface."""
parser = MindeeParser()
parser.call_endpoint()