-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathClient.php
More file actions
591 lines (555 loc) · 21 KB
/
Copy pathClient.php
File metadata and controls
591 lines (555 loc) · 21 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
581
582
583
584
585
586
587
588
589
590
591
<?php
/**
* Mindee Client.
*
* Handles most basic operations of the library.
*/
namespace Mindee;
use Exception;
use Mindee\Error\ErrorCode;
use Mindee\Error\MindeeApiException;
use Mindee\Error\MindeeClientException;
use Mindee\Error\MindeeException;
use Mindee\Error\MindeeHttpException;
use Mindee\Http\Endpoint;
use Mindee\Http\MindeeApi;
use Mindee\Http\MindeeWorkflowApi;
use Mindee\Http\ResponseValidation;
use Mindee\Http\WorkflowEndpoint;
use Mindee\Input\Base64Input;
use Mindee\Input\BytesInput;
use Mindee\Input\FileInput;
use Mindee\Input\InputSource;
use Mindee\Input\LocalInputSource;
use Mindee\Input\LocalResponse;
use Mindee\Input\PageOptions;
use Mindee\Input\PathInput;
use Mindee\Input\PollingOptions;
use Mindee\Input\PredictMethodOptions;
use Mindee\Input\URLInputSource;
use Mindee\Input\WorkflowOptions;
use Mindee\Parsing\Common\AsyncPredictResponse;
use Mindee\Parsing\Common\PredictResponse;
use Mindee\Parsing\Common\WorkflowResponse;
use Mindee\Product\Generated\GeneratedV1;
use ReflectionClass;
use ReflectionException;
/**
* Main entrypoint for Mindee operations.
*/
class Client
{
use CustomSleepMixin;
/**
* Default owner for API products.
*
* Do not change unless you know what you are doing.
*/
public const DEFAULT_OWNER = 'mindee';
/**
* @var string API key for a given client.
*/
private string $apiKey;
/**
* Mindee Client.
*
* @param string|null $apiKey Optional API key. Will fall back to environment variable if not provided.
*/
public function __construct(?string $apiKey = null)
{
$this->apiKey = $apiKey ?: getenv('MINDEE_API_KEY');
}
/**
* Load a document from an absolute path, as a string.
*
* @param string $filePath Path of the file.
* @param boolean $fixPDF Whether the PDF should be fixed or not.
* @return PathInput
*/
public function sourceFromPath(string $filePath, bool $fixPDF = false): PathInput
{
$input = new PathInput($filePath);
if ($fixPDF) {
$input->fixPDF();
}
return $input;
}
/**
* Load a document from a normal PHP file object.
*
* @param mixed $file File object as created from the file() function.
* @param boolean $fixPDF Whether the PDF should be fixed or not.
* @return FileInput
*/
public function sourceFromFile(mixed $file, bool $fixPDF = false): FileInput
{
$input = new FileInput($file);
if ($fixPDF) {
$input->fixPDF();
}
return $input;
}
/**
* Load a document from raw bytes.
*
* @param string $fileBytes File object in raw bytes.
* @param string $fileName File name, mandatory.
* @param boolean $fixPDF Whether the PDF should be fixed or not.
* @return BytesInput
*/
public function sourceFromBytes(string $fileBytes, string $fileName, bool $fixPDF = false): BytesInput
{
$input = new BytesInput($fileBytes, $fileName);
if ($fixPDF) {
$input->fixPDF();
}
return $input;
}
/**
* Load a document from a base64 encoded string.
*
* @param string $fileB64 File object in Base64.
* @param string $fileName File name, mandatory.
* @param boolean $fixPDF Whether the PDF should be fixed or not.
* @return Base64Input
*/
public function sourceFromB64String(string $fileB64, string $fileName, bool $fixPDF = false): Base64Input
{
$input = new Base64Input($fileB64, $fileName);
if ($fixPDF) {
$input->fixPDF();
}
return $input;
}
/**
* Load a document from an URL.
*
* @param string $url File URL. Must start with "https://".
* @return URLInputSource
*/
public function sourceFromUrl(string $url): URLInputSource
{
return new URLInputSource($url);
}
/**
* Builds a custom endpoint.
*
* @param string $endpointName URL of the endpoint.
* @param string $endpointOwner Name of the endpoint's owner.
* @param string $endpointVersion Version of the endpoint.
* @return Endpoint
*/
private function constructEndpoint(
string $endpointName,
string $endpointOwner,
string $endpointVersion
): Endpoint {
$endpointVersion = $endpointVersion != null && strlen($endpointVersion) > 0 ? $endpointVersion : '1';
$endpointSettings = new MindeeApi($this->apiKey, $endpointName, $endpointOwner, $endpointVersion);
return new Endpoint($endpointName, $endpointOwner, $endpointVersion, $endpointSettings);
}
/**
* Cleans the account name.
*
* @param string $accountName Name of the endpoint's owner. Replaced by self::DEFAULT_OWNER if absent.
* @return string
*/
private function cleanAccountName(string $accountName): string
{
if (!$accountName || mb_strlen(trim($accountName), "UTF-8") < 1) {
error_log(
"No account name provided for custom build. " . self::DEFAULT_OWNER . " will be used by default."
);
return self::DEFAULT_OWNER;
}
return $accountName;
}
/**
* Builds an off-the-shelf endpoint.
*
* @param string $product Name of the product's class.
* @return Endpoint
* @throws MindeeApiException Throws if the product isn't recognized.
*/
private function constructOTSEndpoint(string $product): Endpoint
{
try {
$reflection = new ReflectionClass($product);
$endpointName = $reflection->getStaticPropertyValue("endpointName");
$endpointVersion = $reflection->getStaticPropertyValue("endpointVersion");
} catch (ReflectionException $e) {
throw new MindeeApiException(
"Unable to create custom product " . $product,
ErrorCode::INTERNAL_LIBRARY_ERROR
);
}
if ($endpointName == 'custom') {
throw new MindeeApiException(
'Please create an endpoint manually before sending requests to a custom build.',
ErrorCode::USER_INPUT_ERROR
);
}
$endpointOwner = self::DEFAULT_OWNER;
return $this->constructEndpoint($endpointName, $endpointOwner, $endpointVersion);
}
/**
* Adds a custom endpoint, created using the Mindee API Builder.
*
* @param string $endpointName URL of the endpoint.
* @param string $accountName Name of the endpoint's owner.
* @param string|null $version Version of the endpoint.
* @return Endpoint
* @throws MindeeClientException Throws if a custom endpoint name isn't provided.
*/
public function createEndpoint(string $endpointName, string $accountName, ?string $version = null): Endpoint
{
if (mb_strlen($endpointName, "UTF-8") == 0) {
throw new MindeeClientException(
"Custom endpoint requires a valid 'endpoint_name'.",
ErrorCode::USER_INPUT_ERROR
);
}
$accountName = $this->cleanAccountName($accountName);
if (!$version || strlen($version) < 1) {
error_log("Notice: no version provided for a custom build, will attempt to poll version 1 by default.");
$version = "1";
}
return $this->constructEndpoint($endpointName, $accountName, $version);
}
/**
* Cut the pages of a PDF following the detailed operations.
*
* @param LocalInputSource $inputDoc Input PDF file.
* @param PageOptions $pageOptions Options to apply to the PDF file.
* @return void
*/
private function cutDocPages(LocalInputSource $inputDoc, PageOptions $pageOptions)
{
$inputDoc->applyPageOptions($pageOptions);
}
/**
* Makes the request to retrieve an async document.
*
* @param string $predictionType Name of the product's class.
* @param string $queueId ID of the queue.
* @param Endpoint $endpoint Endpoint to poll.
* @return AsyncPredictResponse
* @throws MindeeHttpException Throws if the API sent an error.
*/
private function makeParseQueuedRequest(
string $predictionType,
string $queueId,
Endpoint $endpoint
): AsyncPredictResponse {
$queuedResponse = ResponseValidation::cleanRequestData($endpoint->documentQueueReqGet($queueId));
if (!ResponseValidation::isValidAsyncResponse($queuedResponse)) {
throw MindeeHttpException::handleError(
$endpoint->settings->endpointName,
$queuedResponse
);
}
return new AsyncPredictResponse($predictionType, $queuedResponse['data']);
}
/**
* Makes the request to send a document to an asynchronous endpoint.
*
* @param string $predictionType Name of the product's class.
* @param InputSource $inputDoc Input file.
* @param PredictMethodOptions $options Prediction Options.
* @return AsyncPredictResponse
* @throws MindeeHttpException Throws if the API sent an error.
* @throws MindeeApiException Throws if one attempts to edit remote resources.
*/
private function makeEnqueueRequest(
string $predictionType,
InputSource $inputDoc,
PredictMethodOptions $options
): AsyncPredictResponse {
if (!$options->pageOptions->isEmpty()) {
if ($inputDoc instanceof LocalInputSource) {
$this->cutDocPages($inputDoc, $options->pageOptions);
} else {
throw new MindeeApiException(
"Cannot edit non-local input sources.",
ErrorCode::USER_OPERATION_ERROR
);
}
}
$response = ResponseValidation::cleanRequestData(
$options->endpoint->predictAsyncRequestPost(
$inputDoc,
$options
)
);
if (!ResponseValidation::isValidAsyncResponse($response)) {
throw MindeeHttpException::handleError(
$options->endpoint->settings->endpointName,
$response
);
}
return new AsyncPredictResponse($predictionType, $response['data']);
}
/**
* Makes the request to send a document to a workflow.
*
* @param string $predictionType Name of the product's class.
* @param InputSource $inputDoc Input file.
* @param string $workflowId ID of the workflow.
* @param PredictMethodOptions $options Prediction Options.
* @return WorkflowResponse
* @throws MindeeHttpException Throws if the API sent an error.
* @throws MindeeApiException Throws if the API sent an error,
* or if the prediction type isn't recognized or if a field can't be deserialized.
*/
private function makeWorkflowExecutionRequest(
string $predictionType,
InputSource $inputDoc,
string $workflowId,
PredictMethodOptions $options
): WorkflowResponse {
$workflowRouterSettings = new MindeeWorkflowApi($this->apiKey, $workflowId);
$options->endpoint = new WorkflowEndpoint($workflowRouterSettings);
if (!$options->pageOptions->isEmpty()) {
if ($inputDoc instanceof LocalInputSource) {
$this->cutDocPages($inputDoc, $options->pageOptions);
} else {
throw new MindeeApiException(
"Cannot edit non-local input sources.",
ErrorCode::USER_OPERATION_ERROR
);
}
}
$response = ResponseValidation::cleanRequestData($options->endpoint->executeWorkflowRequestPost(
$inputDoc,
$options->workflowOptions
));
if (!ResponseValidation::isValidWorkflowResponse($response)) {
throw MindeeHttpException::handleError(
"workflows/$workflowId/executions",
$response
);
}
try {
return new WorkflowResponse($predictionType, $response['data']);
} catch (Exception $e) {
throw new MindeeApiException(
"Unable to create workflow response for $predictionType",
ErrorCode::API_UNPROCESSABLE_ENTITY
);
}
}
/**
* Makes the request to send a document to a synchronous endpoint.
*
* @param string $predictionType Name of the product's class.
* @param InputSource $inputDoc Input file.
* @param PredictMethodOptions $options Prediction Options.
* @return PredictResponse
* @throws MindeeHttpException Throws if the API sent an error.
* @throws MindeeApiException Throws if one attempts to edit remote resources.
*/
private function makeParseRequest(
string $predictionType,
InputSource $inputDoc,
PredictMethodOptions $options
): PredictResponse {
if (!$options->pageOptions->isEmpty()) {
if ($inputDoc instanceof LocalInputSource) {
$this->cutDocPages($inputDoc, $options->pageOptions);
} else {
throw new MindeeApiException(
"Cannot edit non-local input sources.",
ErrorCode::USER_OPERATION_ERROR
);
}
}
$response = ResponseValidation::cleanRequestData($options->endpoint->predictRequestPost(
$inputDoc,
$options,
));
if (!ResponseValidation::isValidSyncResponse($response)) {
throw MindeeHttpException::handleError(
$options->endpoint->settings->endpointName,
$response
);
}
return new PredictResponse($predictionType, $response["data"]);
}
/**
* Call prediction API on the document and parse the results.
*
* @param string $predictionType Name of the product's class.
* @param InputSource $inputDoc Input file.
* @param PredictMethodOptions|null $options Prediction options.
* @param PageOptions|null $pageOptions Options to apply to the PDF file.
* @return PredictResponse
*/
public function parse(
string $predictionType,
InputSource $inputDoc,
?PredictMethodOptions $options = null,
?PageOptions $pageOptions = null
): PredictResponse {
if ($options == null) {
$options = new PredictMethodOptions();
}
if ($pageOptions != null && $inputDoc instanceof LocalInputSource && $inputDoc->isPDF()) {
$this->cutDocPages($inputDoc, $pageOptions);
}
$options->endpoint = $options->endpoint ?? $this->constructOTSEndpoint(
$predictionType,
);
return $this->makeParseRequest($predictionType, $inputDoc, $options);
}
/**
* Enqueues a document and automatically polls the response. Asynchronous calls only.
*
* @param string $predictionType Name of the product's class.
* @param InputSource $inputDoc Input file.
* @param PredictMethodOptions|null $options Prediction Options.
* @param PollingOptions|null $asyncOptions Async Options. Manages timers.
* @param PageOptions|null $pageOptions Options to apply to the PDF file.
* @return AsyncPredictResponse
* @throws MindeeApiException Throws if the document couldn't be retrieved in time.
*/
public function enqueueAndParse(
string $predictionType,
InputSource $inputDoc,
?PredictMethodOptions $options = null,
?PollingOptions $asyncOptions = null,
?PageOptions $pageOptions = null
): AsyncPredictResponse {
if ($options == null) {
$options = new PredictMethodOptions();
}
if ($asyncOptions == null) {
$asyncOptions = new PollingOptions();
}
$options->endpoint = $options->endpoint ?? $this->constructOTSEndpoint(
$predictionType,
);
$enqueueResponse = $this->enqueue(
$predictionType,
$inputDoc,
$options,
$pageOptions
);
error_log("Successfully enqueued document with job id: " . $enqueueResponse->job->id);
$this->customSleep($asyncOptions->initialDelaySec);
$retryCounter = 1;
$pollResults = $this->parseQueued($predictionType, $enqueueResponse->job->id, $options->endpoint);
while ($retryCounter < $asyncOptions->maxRetries) {
if ($pollResults->job->status == "completed") {
break;
}
error_log("Polling server for parsing result with job id: " . $enqueueResponse->job->id);
$retryCounter++;
$this->customSleep($asyncOptions->delaySec);
$pollResults = $this->parseQueued($predictionType, $enqueueResponse->job->id, $options->endpoint);
}
if ($pollResults->job->status != "completed") {
throw new MindeeApiException(
"Couldn't retrieve document " . $enqueueResponse->job->id . " after $retryCounter tries.",
ErrorCode::API_TIMEOUT,
);
}
return $pollResults;
}
/**
* Enqueue a document to an asynchronous endpoint.
*
* @param string $predictionType Name of the product's class.
* @param InputSource $inputDoc Input File.
* @param PredictMethodOptions|null $options Prediction Options.
* @param PageOptions|null $pageOptions Options to apply to the PDF file.
* @return AsyncPredictResponse
*/
public function enqueue(
string $predictionType,
InputSource $inputDoc,
?PredictMethodOptions $options = null,
?PageOptions $pageOptions = null
): AsyncPredictResponse {
if ($options == null) {
$options = new PredictMethodOptions();
}
if ($pageOptions != null && $inputDoc instanceof LocalInputSource && $inputDoc->isPDF()) {
$this->cutDocPages($inputDoc, $pageOptions);
}
$options->endpoint = $options->endpoint ?? $this->constructOTSEndpoint(
$predictionType,
);
return $this->makeEnqueueRequest($predictionType, $inputDoc, $options);
}
/**
* Parses a queued document.
*
* @param string $predictionType Name of the product's class.
* @param string $queueId ID of the queue.
* @param Endpoint|null $endpoint Endpoint to poll.
* @return AsyncPredictResponse
*/
public function parseQueued(
string $predictionType,
string $queueId,
?Endpoint $endpoint = null
): AsyncPredictResponse {
$endpoint = $endpoint ?? $this->constructOTSEndpoint(
$predictionType,
);
return $this->makeParseQueuedRequest($predictionType, $queueId, $endpoint);
}
/**
* @param string $predictionType Name of the product's class.
* @param LocalResponse $localResponse Local response to load.
* @return AsyncPredictResponse|PredictResponse A valid prediction response.
* @throws MindeeException Throws if the loaded response isn't a valid prediction.
*/
public function loadPrediction(
string $predictionType,
LocalResponse $localResponse
): AsyncPredictResponse|PredictResponse {
try {
$json = $localResponse->toArray();
if (isset($json['job'])) {
return new AsyncPredictResponse($predictionType, $json);
}
return new PredictResponse($predictionType, $json);
} catch (Exception $e) {
throw new MindeeException(
"Local response is not a valid prediction.",
ErrorCode::USER_INPUT_ERROR
);
}
}
/**
* Sends a document to a workflow.
*
* @param InputSource $inputDoc Input File.
* @param string $workflowId ID of the workflow.
* @param WorkflowOptions|null $options Prediction Options.
* @param PageOptions|null $pageOptions Options to apply to the PDF file.
* @return WorkflowResponse
*/
public function executeWorkflow(
InputSource $inputDoc,
string $workflowId,
?WorkflowOptions $options = null,
?PageOptions $pageOptions = null
): WorkflowResponse {
if ($options == null) {
$options = new WorkflowOptions();
}
if ($pageOptions != null && $inputDoc instanceof LocalInputSource && $inputDoc->isPDF()) {
$this->cutDocPages($inputDoc, $pageOptions);
}
$predictMethodOptions = new PredictMethodOptions();
$predictMethodOptions->setWorkflowOptions($options);
return $this->makeWorkflowExecutionRequest(
GeneratedV1::class,
$inputDoc,
$workflowId,
$predictMethodOptions
);
}
}