-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMindeeApiV2.php
More file actions
349 lines (313 loc) · 11.5 KB
/
MindeeApiV2.php
File metadata and controls
349 lines (313 loc) · 11.5 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
<?php
/**
* Settings and variables linked to endpoint calling & API usage.
*/
namespace Mindee\Http;
use Exception;
use Mindee\Error\ErrorCode;
use Mindee\Error\MindeeException;
// phpcs:disable
include_once(dirname(__DIR__) . '/version.php');
// phpcs:enable
use Mindee\Error\MindeeV2HttpException;
use Mindee\Error\MindeeV2HttpUnknownError;
use Mindee\Input\InferenceParameters;
use Mindee\Input\InputSource;
use Mindee\Input\LocalInputSource;
use Mindee\Input\URLInputSource;
use Mindee\Parsing\V2\ErrorResponse;
use Mindee\Parsing\V2\InferenceResponse;
use Mindee\Parsing\V2\JobResponse;
use const Mindee\VERSION;
/**
* Default key name for the API key entry in environment variables.
*/
const API_V2_KEY_ENV_NAME = 'MINDEE_V2_API_KEY';
/**
* Default key name for the Base URL in environment variables.
*/
const API_V2_BASE_URL_ENV_NAME = 'MINDEE_V2_BASE_URL';
/**
* Default URL prefix for API calls.
*/
const API_V2_BASE_URL_DEFAULT = 'https://api-v2.mindee.net/v2';
/**
* Default key name for CURL request timeout in environment variables.
*/
const API_V2_REQUEST_TIMEOUT_ENV_NAME = 'MINDEE_V2_REQUEST_TIMEOUT';
/**
* Default timeout value for curl requests.
*/
const API_V2_TIMEOUT_DEFAULT = 120;
/**
* Data class containing settings for endpoints.
*/
class MindeeApiV2
{
/**
* Get the User Agent to send for API calls.
* @return string
*/
private function getUserAgent(): string
{
switch (PHP_OS_FAMILY) {
case "Darwin":
$os = "macos";
break;
default:
$os = strtolower(PHP_OS_FAMILY);
}
return 'mindee-api-php@v' . VERSION . ' php-v' . PHP_VERSION . ' ' . $os;
}
/**
* @var string|null API key.
*/
public ?string $apiKey;
/**
* @var integer Timeout for the request, in ms.
*/
public int $requestTimeout;
/**
* @var string Base for the root url. Used for testing purposes.
*/
public string $baseUrl;
/**
* @param string|null $apiKey API key.
* @return void
* @throws MindeeException Throws if the API key specified is invalid.
*/
public function __construct(?string $apiKey)
{
$this->setApiKey($apiKey);
$this->baseUrl = API_V2_BASE_URL_DEFAULT;
$this->requestTimeout = API_V2_TIMEOUT_DEFAULT;
$this->setFromEnv();
if (!$this->apiKey || strlen($this->apiKey) == 0) {
throw new MindeeException(
"Missing API key for call," .
" check your Client configuration.You can set this using the " .
API_KEY_ENV_NAME . ' environment variable.',
ErrorCode::USER_INPUT_ERROR
);
}
}
/**
* Sets values from environment, if needed.
*
* @return void
*/
private function setFromEnv(): void
{
$envVars = [
API_V2_BASE_URL_ENV_NAME => [$this, 'setBaseUrl'],
API_V2_REQUEST_TIMEOUT_ENV_NAME => [$this, 'setTimeout'],
];
foreach ($envVars as $key => $func) {
$envVal = getenv($key) ? getenv($key) : '';
if ($envVal) {
call_user_func($func, $envVal);
error_log('Value ' . $key . ' was set from env.');
}
}
}
/**
* Sets the API key.
*
* @param string|null $apiKey Optional API key.
* @return void
*/
protected function setApiKey(?string $apiKey = null): void
{
$envVal = !getenv(API_V2_KEY_ENV_NAME) ? '' : getenv(API_V2_KEY_ENV_NAME);
if (!$apiKey) {
error_log('API key set from environment');
$this->apiKey = $envVal;
} else {
$this->apiKey = $apiKey;
}
}
/**
* @param InputSource $inputDoc Input document.
* @param InferenceParameters $params Parameters for the inference.
* @return JobResponse Server response wrapped in a JobResponse object.
* @throws MindeeException Throws if the model ID is not provided.
*/
public function reqPostInferenceEnqueue(InputSource $inputDoc, InferenceParameters $params): JobResponse
{
if (!isset($params->modelId)) {
throw new MindeeException("Model ID must be provided.", ErrorCode::USER_INPUT_ERROR);
}
$response = $this->documentEnqueuePost($inputDoc, $params);
return $this->processResponse($response, JobResponse::class);
}
/**
* Process the HTTP response and return the appropriate response object.
*
* @param array $result Raw HTTP response array with 'data' and 'code' keys.
* @param string $responseType Class name of the response type to instantiate.
* @return JobResponse|InferenceResponse The processed response object.
* @throws MindeeException Throws if HTTP status indicates an error or deserialization fails.
* @throws MindeeV2HttpException Throws if the HTTP status indicates an error.
* @throws MindeeV2HttpUnknownError Throws if the server sends an unexpected reply.
*/
private function processResponse(array $result, string $responseType): InferenceResponse|JobResponse
{
$statusCode = $result['code'] ?? -1;
if ($statusCode > 399 || $statusCode < 200) {
$responseData = json_decode($result['data'], true);
if ($responseData && isset($responseData['status'])) {
throw new MindeeV2HttpException(new ErrorResponse($responseData));
}
throw new MindeeV2HttpUnknownError(json_encode($result, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}
try {
$responseData = json_decode($result['data'], true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new MindeeException('JSON decode error: ' . json_last_error_msg());
}
return new $responseType($responseData);
} catch (Exception $e) {
error_log("Raised '{$e->getMessage()}' Couldn't deserialize response object:\n" . $result['data']);
throw new MindeeException("Couldn't deserialize response object.", ErrorCode::API_UNPROCESSABLE_ENTITY);
}
}
/**
* Requests the job of a queued document from the API.
* Throws an error if the server's response contains one.
* @param string $inferenceId ID of the inference.
* @return InferenceResponse
* @throws MindeeException Throws if the server's response contains an error.
* @throws MindeeException Throws if the inference ID is not provided.
*/
public function reqGetInference(string $inferenceId): InferenceResponse
{
if (!isset($inferenceId)) {
throw new MindeeException("Inference ID must be provided.", ErrorCode::USER_INPUT_ERROR);
}
$response = $this->inferenceGetRequest($inferenceId);
return $this->processResponse($response, InferenceResponse::class);
}
/**
* Requests the job of a queued document from the API.
* Throws an error if the server's response contains one.
* @param string $jobId ID of the inference.
* @return JobResponse Server response wrapped in a JobResponse object.
* @throws MindeeException Throws if the server's response contains an error.
* @throws MindeeException Throws if the inference ID is not provided.
*/
public function reqGetJob(string $jobId): JobResponse
{
if (!isset($jobId)) {
throw new MindeeException("Inference ID must be provided.", ErrorCode::USER_INPUT_ERROR);
}
$response = $this->jobGetRequest($jobId);
return $this->processResponse($response, JobResponse::class);
}
/**
* Init a CURL channel with common params.
* @return false|resource Returns a valid CURL channel.
*/
private function initChannel()
{
$ch = curl_init();
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
[
'Authorization: ' . $this->apiKey,
]
);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->requestTimeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, $this->getUserAgent());
return $ch;
}
/**
* Makes a GET call to retrieve a job.
* @param string $jobId ID of the job.
* @return array Server response.
*/
private function jobGetRequest(string $jobId): array
{
$ch = $this->initChannel();
curl_setopt($ch, CURLOPT_URL, $this->baseUrl . "/jobs/$jobId");
$resp = [
'data' => curl_exec($ch),
'code' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
];
curl_close($ch);
return $resp;
}
/**
* Makes a GET call to retrieve an inference.
* @param string $inferenceId ID of the inference.
* @return array Server response.
*/
private function inferenceGetRequest(string $inferenceId): array
{
$ch = $this->initChannel();
curl_setopt($ch, CURLOPT_URL, $this->baseUrl . "/inferences/$inferenceId");
$resp = [
'data' => curl_exec($ch),
'code' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
];
curl_close($ch);
return $resp;
}
/**
* Starts a CURL session using POST.
*
* @param InputSource $inputSource File to upload.
* @param InferenceParameters $params Inference parameters.
* @return array
*/
private function documentEnqueuePost(
InputSource $inputSource,
InferenceParameters $params
): array {
$ch = $this->initChannel();
$postFields = ['model_id' => $params->modelId];
if ($inputSource instanceof URLInputSource) {
$postFields['url'] = $inputSource->url;
} elseif ($inputSource instanceof LocalInputSource) {
$inputSource->checkNeedsFix();
$postFields['file'] = $inputSource->fileObject;
}
if (isset($params->rawText)) {
$postFields['raw_text'] = $params->rawText ? 'true' : 'false';
}
if (isset($params->polygon)) {
$postFields['polygon'] = $params->polygon ? 'true' : 'false';
}
if (isset($params->confidence)) {
$postFields['confidence'] = $params->confidence ? 'true' : 'false';
}
if (isset($params->rag)) {
$postFields['rag'] = $params->rag ? 'true' : 'false';
}
if (isset($params->webhooksIds) && count($params->webhooksIds) > 0) {
if (PHP_VERSION_ID < 80200 && count($params->webhooksIds) > 1) {
# NOTE: see https://bugs.php.net/bug.php?id=51634
error_log("PHP version is too low to support webbook array destructuring.
\nOnly the first webhook ID will be sent to the server.");
$postFields['webhook_ids'] = $params->webhooksIds[0];
} else {
$postFields['webhook_ids'] = $params->webhooksIds;
}
}
if (isset($params->alias)) {
$postFields['alias'] = $params->alias;
}
$url = $this->baseUrl . '/inferences/enqueue';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
$resp = [
'data' => curl_exec($ch),
'code' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
];
curl_close($ch);
return $resp;
}
}