-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMindeeCliCommand.php
More file actions
580 lines (536 loc) · 19.8 KB
/
Copy pathMindeeCliCommand.php
File metadata and controls
580 lines (536 loc) · 19.8 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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
<?php
declare(strict_types=1);
namespace Mindee\Cli;
use Exception;
use Mindee\Input\InputSource;
use Mindee\Input\PageOptions;
use Mindee\Input\PathInput;
use Mindee\Input\UrlInputSource;
use Mindee\V1\Client;
use Mindee\V1\ClientOptions\PredictMethodOptions;
use Mindee\V1\ClientOptions\PredictOptions;
use Mindee\V1\Error\MindeeV1HttpException;
use Mindee\V1\Parsing\Common\AsyncPredictResponse;
use Mindee\V1\Parsing\Common\PredictResponse;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use function count;
use function in_array;
use const Mindee\Input\KEEP_ONLY;
use const Mindee\Input\REMOVE;
use const Mindee\VERSION;
const JSON_PRINT_RECURSION_DEPTH = 20;
/**
* Configuration Class for CLI.
*/
class MindeeCliCommand extends Command
{
/**
* @var array $documentList Array of document configurations.
*/
private array $documentList;
/**
* @var array $acceptableDocuments Array of acceptable documents.
*/
private array $acceptableDocuments;
/**
* @param array $documentList Array of document configurations.
*/
public function __construct(array $documentList)
{
require __DIR__ . '/../src/version.php';
$this->documentList = $documentList;
$this->acceptableDocuments = [];
foreach ($this->documentList as $documentName => $document) {
$this->acceptableDocuments[] = $documentName;
}
parent::__construct('mindee');
}
/**
* @param string|null $product Selected product, for customisation of the help section.
*/
protected function formatHelp(string $product = null): string
{
$helpCondensed = "";
if (!$product) {
$helpCondensed = "Mindee Command-Line interface.
Usage:
mindee [options] [--] <product> <method> <file_path_or_url>
Available products:";
foreach ($this->documentList as $documentName => $document) {
$helpCondensed .= "\n " . mb_str_pad(
$documentName,
65 - mb_strlen($document->help, "UTF-8"),
' ',
STR_PAD_RIGHT,
"UTF-8"
) . $document->help;
}
} else {
$helpCondensed .= $this->documentList[$product]->help;
}
return $helpCondensed;
}
/**
* @return void sets the main CLI properties.
*/
protected function configure(): void
{
$this
->setName('mindee')
->setDescription('Mindee client.')
->addArgument(
'product',
InputArgument::REQUIRED,
'Specify which product to use. Available products are :' . implode("\n ", $this->acceptableDocuments)
)
->addArgument(
'file_path_or_url',
InputArgument::REQUIRED,
'Path or URL of the file to be processed.'
);
$this->configureMainOptions();
$this->configureCustomOptions();
}
/**
* @return void Sets main properties regarding polling/parsing.
*/
private function configureMainOptions(): void
{
$this->addOption(
'async',
'A',
InputOption::VALUE_NONE,
'When enabled, enqueues and parses the document asynchronously.'
)
->addOption(
'pages_remove',
'r',
InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
'Indexes of the pages to remove from the document.'
)
->addOption(
'pages_keep',
'p',
InputOption::VALUE_REQUIRED,
'Indexes of the pages to keep in the document.'
)
->addOption(
'key',
'k',
InputOption::VALUE_OPTIONAL,
'API key for the account. Is retrieved from environment if not provided.'
)
->addOption(
'output_type',
'o',
InputOption::VALUE_REQUIRED,
'Specify how to output the data.
- summary: a basic summary (default)
- raw: the raw HTTP response
- parsed: the validated and parsed data fields
'
)
->addOption(
'full_text',
't',
InputOption::VALUE_NONE,
"Include full document text in response."
)
->addOption(
'full_text_ocr',
'f',
InputOption::VALUE_NONE,
"Include full text ocr in response."
)
->addOption(
'cropper',
'c',
InputOption::VALUE_NONE,
"Apply cropper operation to the document (if available)."
)
->addOption(
'debug',
'D',
InputOption::VALUE_NONE,
'Debug mode (dry-run).'
);
}
/**
* @return void Sets custom options.
*/
private function configureCustomOptions(): void
{
$this
->addOption(
'account_name',
'a',
InputOption::VALUE_REQUIRED,
'API account name for the endpoint'
)
->addOption(
'endpoint_name',
'e',
InputOption::VALUE_REQUIRED,
'API endpoint name for the endpoint'
)
->addOption(
'endpoint_version',
'd',
InputOption::VALUE_OPTIONAL,
'Version for the endpoint. If not set, use the latest version of the model'
);
}
/**
* Initializes the CLI runner, writes the help section if no argument nor option is given.
*
* @param InputInterface $input Input interface given to the CLI.
* @param OutputInterface $output Output interface.
*/
protected function initialize(InputInterface $input, OutputInterface $output): void
{
$args = $input->getArguments();
$opts = $input->getOptions();
if (count(array_filter($args)) <= 0 && count(array_filter($opts)) <= 0) {
$output->writeln($this->formatHelp(), OutputInterface::OUTPUT_NORMAL);
exit(Command::FAILURE);
}
}
/**
* Runs a command (overload).
*
* @param InputInterface $input Input interface given to the CLI.
* @param OutputInterface $output Output interface.
* @return integer Command execution code return.
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
if ($this->handleVersionOption($input, $output)) {
return Command::SUCCESS;
}
$product = $input->getArgument('product');
if (!$this->isValidProduct($product, $output)) {
return Command::FAILURE;
}
$outputType = $input->getOption('output_type');
$client = new Client($input->getOption('key'));
if ($this->documentList[$product]->isAsync && !$this->documentList[$product]->isSync) {
$isAsync = true;
} else {
$isAsync = $input->getOption('async');
}
if (!$this->isValidPollingMethod($product, $isAsync, $output)) {
return Command::FAILURE;
}
if ($this->areMutuallyExclusivePagesOptions($input, $output)) {
return Command::FAILURE;
}
$filePathOrUrl = $input->getArgument('file_path_or_url');
$file = $this->getFileSource($filePathOrUrl, $output);
if (!$file) {
return Command::FAILURE;
}
$pageOptions = $this->getPageOptions($input);
$predictOptions = $this->getPredictOptions($input);
$predictMethodOptions = $this->getPredictMethodOptions($predictOptions, $pageOptions);
if (!$this->handleCustomOrGeneratedProduct($input, $output, $client, $predictMethodOptions, $product)) {
return Command::FAILURE;
}
return $this->executePrediction(
$client,
$product,
$file,
$predictMethodOptions,
$isAsync,
$input,
$output,
$outputType
);
}
/**
* Checks whether the version was requested.
*
* @param InputInterface $input Input interface of the CLI.
* @param OutputInterface $output Output interface of the CLI.
* @return boolean True if options are valid.
*/
private function handleVersionOption(InputInterface $input, OutputInterface $output): bool
{
if ($input->getOption('version')) {
$output->writeln(VERSION);
return true;
}
return false;
}
/**
* Checks whether a given product is valid for CLI use.
*
* @param string $product Product class used.
* @param OutputInterface $output Output interface of the CLI.
* @return boolean True if a product is valid.
*/
private function isValidProduct(string $product, OutputInterface $output): bool
{
if (!in_array($product, $this->acceptableDocuments, true)) {
$output->writeln("<error>Invalid product: $product</error>");
$output->writeln('<error>Available products are: '
. implode(', ', $this->acceptableDocuments) . '</error>');
return false;
}
return true;
}
/**
* Checks whether a polling method is valid for the current poll.
*
* @param string $product Product class used.
* @param boolean $isAsync Whether the polling will be asynchronous.
* @param OutputInterface $output Output interface of the CLI.
* @return boolean True if the polling method exists for a given product.
*/
private function isValidPollingMethod(string $product, bool $isAsync, OutputInterface $output): bool
{
if ($isAsync && !$this->documentList[$product]->isAsync) {
$output->writeln("<error>Invalid polling method for $product</error>");
$output->writeln("<comment>Asynchronous mode is not supported.</comment>");
return false;
}
if (!$isAsync && !$this->documentList[$product]->isSync) {
$output->writeln("<error>Invalid polling method for $product</error>");
$output->writeln("<comment>Synchronous mode is not supported.</comment>");
return false;
}
return true;
}
/**
* Checks whether PageOptions for the current polling are possible.
*
* @param InputInterface $input Input interface of the CLI.
* @param OutputInterface $output Output interface of the CLI.
* @return boolean True if the operations are possible.
*/
private function areMutuallyExclusivePagesOptions(InputInterface $input, OutputInterface $output): bool
{
$pagesRemove = $input->getOption('pages_remove');
$pagesKeep = $input->getOption('pages_keep');
if ($pagesKeep && $pagesRemove) {
$output->writeln("<error>Page cut and page keep operations are mutually exclusive.</error>");
return true;
}
return false;
}
/**
* Retrieves a source file from a URL or a path.
*
* @param string $filePathOrUrl Path of the file, or URL if it's remote.
* @param OutputInterface $output Output interface of the CLI.
* @return PathInput|UrlInputSource|null A valid InputSource.
*/
private function getFileSource(string $filePathOrUrl, OutputInterface $output): PathInput|UrlInputSource|null
{
if (!str_starts_with($filePathOrUrl, 'https://')) {
if (@file_exists($filePathOrUrl) || @file_get_contents($filePathOrUrl)) {
return new PathInput($filePathOrUrl);
} else {
$output->writeln("<error>Invalid path or url provided '$filePathOrUrl'.</error>");
return null;
}
}
return new UrlInputSource($filePathOrUrl);
}
/**
* Retrieves the PageOptions for the current poll.
*
* @param InputInterface $input Input interface of the CLI.
* @return PageOptions Valid PageOptions.
*/
private function getPageOptions(InputInterface $input): PageOptions
{
$pagesRemove = $input->getOption('pages_remove');
$pagesKeep = $input->getOption('pages_keep');
if ($pagesRemove) {
return new PageOptions($pagesRemove, REMOVE, 0);
}
if ($pagesKeep) {
return new PageOptions($pagesKeep, KEEP_ONLY, 0);
}
return new PageOptions();
}
/**
* Retrieves the PredictOptions for the current poll.
*
* @param InputInterface $input Input interface of the CLI.
* @return PredictOptions Valid PredictOptions.
*/
private function getPredictOptions(InputInterface $input): PredictOptions
{
$predictOptions = new PredictOptions();
if ($input->getOption('full_text')) {
$predictOptions->setIncludeWords(true);
}
if ($input->getOption('full_text_ocr')) {
$predictOptions->setFullText(true);
}
return $predictOptions;
}
/**
* Generates a valid PredictMethodOptions object for parsing.
*
* @param PredictOptions $predictOptions Valid PredictOptions.
* @param PageOptions $pageOptions Valid PageOptions.
* @return PredictMethodOptions Valid PredictMethod Options.
*/
private function getPredictMethodOptions(
PredictOptions $predictOptions,
PageOptions $pageOptions
): PredictMethodOptions {
$predictMethodOptions = new PredictMethodOptions();
$predictMethodOptions->setPredictOptions($predictOptions);
$predictMethodOptions->setPageOptions($pageOptions);
return $predictMethodOptions;
}
/**
* Handles options specific to Custom & Generated Products.
*
* @param InputInterface $input Input interface of the CLI.
* @param OutputInterface $output Output interface of the CLI.
* @param Client $client Mindee Client.
* @param PredictMethodOptions $predictMethodOptions Valid PredictMethodOptions.
* @param string $product Product class used.
* @return boolean Whether the setting of options for custom/generated are valid.
*/
private function handleCustomOrGeneratedProduct(
InputInterface $input,
OutputInterface $output,
Client $client,
PredictMethodOptions $predictMethodOptions,
string $product
): bool {
if ($product === "generated") {
$accountName = $input->getOption('account_name');
$endpointName = $input->getOption('endpoint_name');
$endpointVersion = $input->getOption('endpoint_version') ?? '1';
if (!$accountName) {
$output->writeln("<error>Please specify the name of the account for $product endpoint.</error>");
return false;
}
if (!$endpointName) {
$output->writeln("<error>Please specify the name of $product endpoint.</error>");
return false;
}
if (!$endpointVersion) {
$output->writeln(
"<comment>No version provided for \"$endpointName\", version 1 will be used by default.</comment>"
);
}
$endpoint = $client->createEndpoint($endpointName, $accountName, $endpointVersion);
$predictMethodOptions->setEndpoint($endpoint);
}
return true;
}
/**
* @param Client $client Mindee Client.
* @param string $product Product class used.
* @param InputSource $file Input File.
* @param PredictMethodOptions $predictMethodOptions Options for the polling.
* @param boolean $isAsync Whether the polling will be asynchronous.
* @param InputInterface $input Input interface of the CLI.
* @param OutputInterface $output Output interface of the CLI.
* @param string|null $outputType Type of output (raw, parsed or summary).
* @return integer Return code for the CLI
*/
private function executePrediction(
Client $client,
string $product,
InputSource $file,
PredictMethodOptions $predictMethodOptions,
bool $isAsync,
InputInterface $input,
OutputInterface $output,
?string $outputType
): int {
$debug = $input->getOption('debug');
try {
$result = $this->runClientPrediction($client, $product, $file, $predictMethodOptions, $isAsync, $debug);
} catch (MindeeV1HttpException $e) {
$output->writeln($e->getMessage());
return Command::FAILURE;
} catch (Exception $e) {
$output->writeln("Something went wrong, '" . $e->getMessage() . "' was raised.");
return Command::FAILURE;
}
return $this->outputResult($result, $outputType, $output);
}
/**
* Runs the prediction call.
*
* @param Client $client Mindee client.
* @param string $product Product class used.
* @param InputSource $file Input File.
* @param PredictMethodOptions $predictMethodOptions Prediction method options.
* @param boolean $isAsync Whether the polling is asynchronous.
* @param boolean $debug Whether the command is running in debug mode.
*
* @return AsyncPredictResponse|PredictResponse|string Either a valid prediction response, or a message if the
* command is in debug mode.
*/
private function runClientPrediction(
Client $client,
string $product,
InputSource $file,
PredictMethodOptions $predictMethodOptions,
bool $isAsync,
bool $debug
): AsyncPredictResponse|PredictResponse|string {
if ($debug) {
return "Command executed successfully.";
}
if ($isAsync) {
return $client->enqueueAndParse($this->documentList[$product]->docClass, $file, $predictMethodOptions);
}
return $client->parse($this->documentList[$product]->docClass, $file, $predictMethodOptions);
}
/**
* @param PredictResponse|AsyncPredictResponse|string $result Result of the parsing (or message if in debug
* mode).
* @param string|null $outputType Type of output (raw, parsed or summary).
* @param OutputInterface $output Output interface for the CLI.
* @return integer Command execution code return.
*/
private function outputResult(
PredictResponse|AsyncPredictResponse|string $result,
?string $outputType,
OutputInterface $output
): int {
if ($outputType === "raw") {
$output->writeln(
json_encode(
json_decode(
$result->getRawHttp(),
true,
JSON_PRINT_RECURSION_DEPTH,
JSON_UNESCAPED_SLASHES
),
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
)
);
} elseif ($outputType === "parsed") {
$output->writeln(
json_encode(
json_decode(
$result->getRawHttp(),
true,
JSON_PRINT_RECURSION_DEPTH,
JSON_UNESCAPED_SLASHES
)['document'],
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
)
);
} else {
echo $result->document;
}
return Command::SUCCESS;
}
}