-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathvws.py
More file actions
719 lines (627 loc) · 27.9 KB
/
Copy pathvws.py
File metadata and controls
719 lines (627 loc) · 27.9 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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
"""Tools for interacting with Vuforia APIs."""
import base64
import calendar # noqa: TC003
import json
import time
from http import HTTPMethod, HTTPStatus
from beartype import BeartypeConf, beartype
from vws._image_utils import ImageType as _ImageType
from vws._image_utils import get_image_data as _get_image_data
from vws._reco_counts import (
reco_counts_report_body,
reco_counts_report_path,
report_from_download_response,
)
from vws._vws_request import target_api_request
from vws.exceptions.base_exceptions import VWSError
from vws.exceptions.custom_exceptions import (
RecoCountsReportNotReadyError,
RecoCountsReportTimeoutError,
ServerError,
TargetProcessingTimeoutError,
)
from vws.exceptions.vws_exceptions import TooManyRequestsError
from vws.reports import (
DatabaseSummaryReport,
RecoCountsReport,
RecoCountsReportRequest,
TargetStatusAndRecord,
TargetStatuses,
TargetSummaryReport,
)
from vws.response import Response # noqa: TC001
from vws.transports import RequestsTransport, Transport
@beartype(conf=BeartypeConf(is_pep484_tower=True))
class VWS:
"""An interface to Vuforia Web Services APIs."""
def __init__(
self,
*,
server_access_key: str,
server_secret_key: str,
base_vws_url: str = "https://vws.vuforia.com",
database_id: str | None = None,
request_timeout_seconds: float | tuple[float, float] = 30.0,
transport: Transport | None = None,
) -> None:
"""
Args:
server_access_key: A VWS server access key.
server_secret_key: A VWS server secret key.
base_vws_url: The base URL for the VWS API.
database_id: The ID of the database which the
given keys belong to. This is shown in the
target manager. It is needed only by
:meth:`request_database_reco_counts_report`.
request_timeout_seconds: The timeout for each
HTTP request. This can be a float to set both
the connect and read timeouts, or a
(connect, read) tuple.
transport: The HTTP transport to use for
requests. Defaults to
``RequestsTransport()``.
"""
self._server_access_key = server_access_key
self._server_secret_key = server_secret_key
self._base_vws_url = base_vws_url
self._database_id = database_id
self._request_timeout_seconds = request_timeout_seconds
self._transport = (
transport if transport is not None else RequestsTransport()
)
def make_request(
self,
*,
method: str,
data: bytes,
request_path: str,
expected_result_code: str,
content_type: str,
extra_headers: dict[str, str] | None = None,
) -> Response:
"""Make a request to the Vuforia Target API.
Args:
method: The HTTP method which will be used in
the request.
data: The request body which will be used in the
request.
request_path: The path to the endpoint which
will be used in the request.
expected_result_code: See
"VWS API Result Codes" on
https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api.
content_type: The content type of the request.
extra_headers: Additional headers to include in
the request.
Returns:
The response to the request.
Raises:
~vws.exceptions.custom_exceptions.ServerError:
There is an error with Vuforia's servers.
~vws.exceptions.vws_exceptions.TooManyRequestsError:
Vuforia is rate limiting access.
json.JSONDecodeError: The server did not respond
with valid JSON. This may happen if the
server address is not a valid Vuforia server.
"""
response = target_api_request(
content_type=content_type,
server_access_key=self._server_access_key,
server_secret_key=self._server_secret_key,
method=method,
data=data,
request_path=request_path,
base_vws_url=self._base_vws_url,
request_timeout_seconds=self._request_timeout_seconds,
extra_headers=extra_headers or {},
transport=self._transport,
)
if (
response.status_code == HTTPStatus.TOO_MANY_REQUESTS
): # pragma: no cover
# The Vuforia API returns a 429 response with no JSON body.
raise TooManyRequestsError(response=response)
if (
response.status_code >= HTTPStatus.INTERNAL_SERVER_ERROR
): # pragma: no cover
raise ServerError(response=response)
result_code = json.loads(s=response.text)["result_code"]
if result_code == expected_result_code:
return response
raise VWSError.from_result_code(
result_code=result_code,
response=response,
)
def add_target(
self,
*,
name: str,
width: float,
image: _ImageType,
application_metadata: str | None,
active_flag: bool,
) -> str:
"""Add a target to a Vuforia Web Services database.
See
https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#add
for parameter details.
Args:
name: The name of the target.
width: The width of the target.
image: The image of the target.
active_flag: Whether or not the target is active for query.
application_metadata: The application metadata of the target.
This must be base64 encoded, for example by using::
base64.b64encode('input_string').decode('ascii')
Returns:
The target ID of the new target.
Raises:
~vws.exceptions.vws_exceptions.AuthenticationFailureError: The
secret key is not correct.
~vws.exceptions.vws_exceptions.BadImageError: There is a problem
with the given image. For example, it must be a JPEG or PNG
file in the grayscale or RGB color space.
~vws.exceptions.vws_exceptions.FailError: There was an error with
the request. For example, the given access key does not match a
known database.
~vws.exceptions.vws_exceptions.MetadataTooLargeError: The given
metadata is too large. The maximum size is 1 MB of data when
Base64 encoded.
~vws.exceptions.vws_exceptions.ImageTooLargeError: The given image
is too large.
~vws.exceptions.vws_exceptions.TargetNameExistError: A target with
the given ``name`` already exists.
~vws.exceptions.vws_exceptions.ProjectInactiveError: The project is
inactive.
~vws.exceptions.vws_exceptions.RequestTimeTooSkewedError: There is
an error with the time sent to Vuforia.
~vws.exceptions.custom_exceptions.ServerError: There is an error
with Vuforia's servers. This has been seen to happen when the
given name includes a bad character.
~vws.exceptions.vws_exceptions.TooManyRequestsError: Vuforia is
rate limiting access.
"""
image_data = _get_image_data(image=image)
image_data_encoded = base64.b64encode(s=image_data).decode(
encoding="ascii",
)
data = {
"name": name,
"width": width,
"image": image_data_encoded,
"active_flag": active_flag,
"application_metadata": application_metadata,
}
content = json.dumps(obj=data).encode(encoding="utf-8")
response = self.make_request(
method=HTTPMethod.POST,
data=content,
request_path="/targets",
expected_result_code="TargetCreated",
content_type="application/json",
)
return str(object=json.loads(s=response.text)["target_id"])
def get_target_record(self, target_id: str) -> TargetStatusAndRecord:
"""Get a given target's target record from the Target Management
System.
See
https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#target-record.
Args:
target_id: The ID of the target to get details of.
Returns:
Response details of a target from Vuforia.
Raises:
~vws.exceptions.vws_exceptions.AuthenticationFailureError: The
secret key is not correct.
~vws.exceptions.vws_exceptions.FailError: There was an error with
the request. For example, the given access key does not match a
known database.
~vws.exceptions.vws_exceptions.UnknownTargetError: The given target
ID does not match a target in the database.
~vws.exceptions.vws_exceptions.RequestTimeTooSkewedError: There is
an error with the time sent to Vuforia.
~vws.exceptions.custom_exceptions.ServerError: There is an error
with Vuforia's servers.
~vws.exceptions.vws_exceptions.TooManyRequestsError: Vuforia is
rate limiting access.
"""
response = self.make_request(
method=HTTPMethod.GET,
data=b"",
request_path=f"/targets/{target_id}",
expected_result_code="Success",
content_type="application/json",
)
result_data = json.loads(s=response.text)
return TargetStatusAndRecord.from_response_dict(
response_dict=result_data,
)
def wait_for_target_processed(
self,
*,
target_id: str,
seconds_between_requests: float = 0.2,
timeout_seconds: float = 60 * 5,
) -> None:
"""Wait up to five minutes (arbitrary) for a target to get past the
processing stage.
Args:
target_id: The ID of the target to wait for.
seconds_between_requests: The number of seconds to wait between
requests made while polling the target status.
We wait 0.2 seconds by default, rather than less, than that to
decrease the number of calls made to the API, to decrease the
likelihood of hitting the request quota.
timeout_seconds: The maximum number of seconds to wait for the
target to be processed.
Raises:
~vws.exceptions.vws_exceptions.AuthenticationFailureError: The
secret key is not correct.
~vws.exceptions.vws_exceptions.FailError: There was an error with
the request. For example, the given access key does not match a
known database.
~vws.exceptions.custom_exceptions.TargetProcessingTimeoutError: The
target remained in the processing stage for more than
``timeout_seconds`` seconds.
~vws.exceptions.vws_exceptions.UnknownTargetError: The given target
ID does not match a target in the database.
~vws.exceptions.vws_exceptions.RequestTimeTooSkewedError: There is
an error with the time sent to Vuforia.
~vws.exceptions.custom_exceptions.ServerError: There is an error
with Vuforia's servers.
~vws.exceptions.vws_exceptions.TooManyRequestsError: Vuforia is
rate limiting access.
"""
start_time = time.monotonic()
while True:
report = self.get_target_summary_report(target_id=target_id)
if report.status != TargetStatuses.PROCESSING:
# Guard against the target still being seen as
# processing by other endpoints due to eventual
# consistency.
time.sleep(seconds_between_requests)
return
elapsed_time = time.monotonic() - start_time
if elapsed_time > timeout_seconds: # pragma: no cover
raise TargetProcessingTimeoutError
time.sleep(seconds_between_requests)
def list_targets(self) -> list[str]:
"""List target IDs.
See
https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#details-list.
Returns:
The IDs of all targets in the database.
Raises:
~vws.exceptions.vws_exceptions.AuthenticationFailureError: The
secret key is not correct.
~vws.exceptions.vws_exceptions.FailError: There was an error with
the request. For example, the given access key does not match a
known database.
~vws.exceptions.vws_exceptions.RequestTimeTooSkewedError: There is
an error with the time sent to Vuforia.
~vws.exceptions.custom_exceptions.ServerError: There is an error
with Vuforia's servers.
~vws.exceptions.vws_exceptions.TooManyRequestsError: Vuforia is
rate limiting access.
"""
response = self.make_request(
method=HTTPMethod.GET,
data=b"",
request_path="/targets",
expected_result_code="Success",
content_type="application/json",
)
return list(json.loads(s=response.text)["results"])
def get_target_summary_report(self, target_id: str) -> TargetSummaryReport:
"""Get a summary report for a target.
See
https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#summary-report.
Args:
target_id: The ID of the target to get a summary report for.
Returns:
Details of the target.
Raises:
~vws.exceptions.vws_exceptions.AuthenticationFailureError: The
secret key is not correct.
~vws.exceptions.vws_exceptions.FailError: There was an error with
the request. For example, the given access key does not match a
known database.
~vws.exceptions.vws_exceptions.UnknownTargetError: The given target
ID does not match a target in the database.
~vws.exceptions.vws_exceptions.RequestTimeTooSkewedError: There is
an error with the time sent to Vuforia.
~vws.exceptions.custom_exceptions.ServerError: There is an error
with Vuforia's servers.
~vws.exceptions.vws_exceptions.TooManyRequestsError: Vuforia is
rate limiting access.
"""
response = self.make_request(
method=HTTPMethod.GET,
data=b"",
request_path=f"/summary/{target_id}",
expected_result_code="Success",
content_type="application/json",
)
result_data = dict(json.loads(s=response.text))
return TargetSummaryReport.from_response_dict(
response_dict=result_data,
)
def get_database_summary_report(self) -> DatabaseSummaryReport:
"""Get a summary report for the database.
See
https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#summary-report.
Returns:
Details of the database.
Raises:
~vws.exceptions.vws_exceptions.AuthenticationFailureError: The
secret key is not correct.
~vws.exceptions.vws_exceptions.FailError: There was an error with
the request. For example, the given access key does not match a
known database.
~vws.exceptions.vws_exceptions.RequestTimeTooSkewedError: There is
an error with the time sent to Vuforia.
~vws.exceptions.custom_exceptions.ServerError: There is an error
with Vuforia's servers.
~vws.exceptions.vws_exceptions.TooManyRequestsError: Vuforia is
rate limiting access.
"""
response = self.make_request(
method=HTTPMethod.GET,
data=b"",
request_path="/summary",
expected_result_code="Success",
content_type="application/json",
)
response_data = dict(json.loads(s=response.text))
return DatabaseSummaryReport.from_response_dict(
response_dict=response_data,
)
def request_database_reco_counts_report(
self,
*,
year: int,
month: calendar.Month,
) -> RecoCountsReportRequest:
"""Request a per-target recognition count report for the database.
Vuforia generates the report in the background, so the report is not
available to download immediately. Use
:meth:`wait_for_reco_counts_report` to wait for it.
Args:
year: The year to get recognition counts for.
month: The month of the year to get recognition counts for.
Vuforia accepts only the current month and the previous
month. A month taken from a :class:`datetime.datetime` needs
wrapping, as in ``calendar.Month(value=now.month)``.
Returns:
The URL to download the report from, and the transaction ID of
the request.
Raises:
~vws.exceptions.custom_exceptions.DatabaseIdNotSetError: No
``database_id`` was given to the client.
~vws.exceptions.vws_exceptions.AuthenticationFailureError: The
secret key is not correct, or the client's ``database_id`` is
not the ID of the database which the client's keys belong to.
~vws.exceptions.vws_exceptions.FailError: There was an error with
the request. For example, the given year and month are not
the current month or the previous month.
~vws.exceptions.vws_exceptions.RequestTimeTooSkewedError: There is
an error with the time sent to Vuforia.
~vws.exceptions.custom_exceptions.ServerError: There is an error
with Vuforia's servers.
~vws.exceptions.vws_exceptions.TooManyRequestsError: Vuforia is
rate limiting access.
"""
response = self.make_request(
method=HTTPMethod.POST,
data=reco_counts_report_body(year=year, month=month),
request_path=reco_counts_report_path(
database_id=self._database_id,
),
expected_result_code="Success",
content_type="application/json",
)
response_data = dict(json.loads(s=response.text))
return RecoCountsReportRequest.from_response_dict(
response_dict=response_data,
)
def download_reco_counts_report(
self,
*,
presigned_url: str,
) -> RecoCountsReport:
"""Download a requested reco counts report.
The report's URL is not part of the VWS API, so this request is not
authorized with the client's keys.
Args:
presigned_url: The URL of the report, as given by
:meth:`request_database_reco_counts_report`.
Returns:
The downloaded report.
Raises:
~vws.exceptions.custom_exceptions.RecoCountsReportNotReadyError:
Vuforia has not finished generating the report.
~vws.exceptions.custom_exceptions.RecoCountsReportDownloadError:
The report could not be downloaded. For example, the report's
URL may have expired.
"""
response = self._transport(
method=HTTPMethod.GET,
url=presigned_url,
headers={},
data=b"",
request_timeout=self._request_timeout_seconds,
)
return report_from_download_response(response=response)
def wait_for_reco_counts_report(
self,
*,
presigned_url: str,
seconds_between_requests: float = 0.2,
timeout_seconds: float = 60 * 5,
) -> RecoCountsReport:
"""Wait for a requested reco counts report to be generated, then
download it.
Args:
presigned_url: The URL of the report, as given by
:meth:`request_database_reco_counts_report`.
seconds_between_requests: The number of seconds to wait between
requests made while polling the report's URL.
timeout_seconds: The maximum number of seconds to wait for the
report to be generated.
Returns:
The downloaded report.
Raises:
~vws.exceptions.custom_exceptions.RecoCountsReportTimeoutError:
The report was not generated within ``timeout_seconds``
seconds.
~vws.exceptions.custom_exceptions.RecoCountsReportDownloadError:
The report could not be downloaded. For example, the report's
URL may have expired.
"""
start_time = time.monotonic()
while True:
try:
return self.download_reco_counts_report(
presigned_url=presigned_url,
)
except RecoCountsReportNotReadyError:
elapsed_time = time.monotonic() - start_time
if elapsed_time > timeout_seconds:
raise RecoCountsReportTimeoutError from None
time.sleep(seconds_between_requests)
def delete_target(self, target_id: str) -> None:
"""Delete a given target.
See
https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#delete.
Args:
target_id: The ID of the target to delete.
Raises:
~vws.exceptions.vws_exceptions.AuthenticationFailureError: The
secret key is not correct.
~vws.exceptions.vws_exceptions.FailError: There was an error with
the request. For example, the given access key does not match a
known database.
~vws.exceptions.vws_exceptions.UnknownTargetError: The given target
ID does not match a target in the database.
~vws.exceptions.vws_exceptions.TargetStatusProcessingError: The
given target is in the processing state.
~vws.exceptions.vws_exceptions.RequestTimeTooSkewedError: There is
an error with the time sent to Vuforia.
~vws.exceptions.custom_exceptions.ServerError: There is an error
with Vuforia's servers.
~vws.exceptions.vws_exceptions.TooManyRequestsError: Vuforia is
rate limiting access.
"""
self.make_request(
method=HTTPMethod.DELETE,
data=b"",
request_path=f"/targets/{target_id}",
expected_result_code="Success",
content_type="application/json",
)
def get_duplicate_targets(self, target_id: str) -> list[str]:
"""Get targets which may be considered duplicates of a given
target.
See
https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#check.
Args:
target_id: The ID of the target to delete.
Returns:
The target IDs of duplicate targets.
Raises:
~vws.exceptions.vws_exceptions.AuthenticationFailureError: The
secret key is not correct.
~vws.exceptions.vws_exceptions.FailError: There was an error with
the request. For example, the given access key does not match a
known database.
~vws.exceptions.vws_exceptions.UnknownTargetError: The given target
ID does not match a target in the database.
~vws.exceptions.vws_exceptions.ProjectInactiveError: The project is
inactive.
~vws.exceptions.vws_exceptions.RequestTimeTooSkewedError: There is
an error with the time sent to Vuforia.
~vws.exceptions.custom_exceptions.ServerError: There is an error
with Vuforia's servers.
~vws.exceptions.vws_exceptions.TooManyRequestsError: Vuforia is
rate limiting access.
"""
response = self.make_request(
method=HTTPMethod.GET,
data=b"",
request_path=f"/duplicates/{target_id}",
expected_result_code="Success",
content_type="application/json",
)
return list(json.loads(s=response.text)["similar_targets"])
def update_target(
self,
*,
target_id: str,
name: str | None = None,
width: float | None = None,
image: _ImageType | None = None,
active_flag: bool | None = None,
application_metadata: str | None = None,
) -> None:
"""Update a target in a Vuforia Web Services database.
See
https://developer.vuforia.com/library/web-api/cloud-targets-web-services-api#update
for parameter details.
Args:
target_id: The ID of the target to update.
name: The name of the target.
width: The width of the target.
image: The image of the target.
active_flag: Whether or not the target is active for query.
application_metadata: The application metadata of the target.
This must be base64 encoded, for example by using::
base64.b64encode('input_string').decode('ascii')
Giving ``None`` will not change the application metadata.
Raises:
~vws.exceptions.vws_exceptions.AuthenticationFailureError: The
secret key is not correct.
~vws.exceptions.vws_exceptions.BadImageError: There is a problem
with the given image. For example, it must be a JPEG or PNG
file in the grayscale or RGB color space.
~vws.exceptions.vws_exceptions.FailError: There was an error with
the request. For example, the given access key does not match a
known database.
~vws.exceptions.vws_exceptions.MetadataTooLargeError: The given
metadata is too large. The maximum size is 1 MB of data when
Base64 encoded.
~vws.exceptions.vws_exceptions.ImageTooLargeError: The given image
is too large.
~vws.exceptions.vws_exceptions.TargetNameExistError: A target with
the given ``name`` already exists.
~vws.exceptions.vws_exceptions.ProjectInactiveError: The project is
inactive.
~vws.exceptions.vws_exceptions.RequestTimeTooSkewedError: There is
an error with the time sent to Vuforia.
~vws.exceptions.custom_exceptions.ServerError: There is an error
with Vuforia's servers.
~vws.exceptions.vws_exceptions.TooManyRequestsError: Vuforia is
rate limiting access.
"""
data: dict[str, str | bool | float | int] = {}
if name is not None:
data["name"] = name
if width is not None:
data["width"] = width
if image is not None:
image_data = _get_image_data(image=image)
image_data_encoded = base64.b64encode(s=image_data).decode(
encoding="ascii",
)
data["image"] = image_data_encoded
if active_flag is not None:
data["active_flag"] = active_flag
if application_metadata is not None:
data["application_metadata"] = application_metadata
content = json.dumps(obj=data).encode(encoding="utf-8")
self.make_request(
method=HTTPMethod.PUT,
data=content,
request_path=f"/targets/{target_id}",
expected_result_code="Success",
content_type="application/json",
)