|
| 1 | +""" |
| 2 | +Tools for interacting with the Vuforia Cloud Recognition Web APIs. |
| 3 | +""" |
| 4 | + |
| 5 | +import io |
| 6 | +from typing import Any, Dict, List |
| 7 | +from urllib.parse import urljoin |
| 8 | + |
| 9 | +import requests |
| 10 | +from urllib3.filepost import encode_multipart_formdata |
| 11 | + |
| 12 | +from ._authorization import authorization_header, rfc_1123_date |
| 13 | + |
| 14 | + |
| 15 | +class CloudRecoService: |
| 16 | + """ |
| 17 | + An interface to the Vuforia Cloud Recognition Web APIs. |
| 18 | + """ |
| 19 | + |
| 20 | + def __init__( |
| 21 | + self, |
| 22 | + client_access_key: str, |
| 23 | + client_secret_key: str, |
| 24 | + ) -> None: |
| 25 | + """ |
| 26 | + Args: |
| 27 | + client_access_key: A VWS client access key. |
| 28 | + client_secret_key: A VWS client secret key. |
| 29 | + """ |
| 30 | + self._client_access_key = client_access_key.encode() |
| 31 | + self._client_secret_key = client_secret_key.encode() |
| 32 | + |
| 33 | + def query(self, image: io.BytesIO) -> List[Dict[str, Any]]: |
| 34 | + """ |
| 35 | + Use the Vuforia Web Query API to make an Image Recognition Query. |
| 36 | +
|
| 37 | + See |
| 38 | + https://library.vuforia.com/articles/Solution/How-To-Perform-an-Image-Recognition-Query |
| 39 | + for parameter details. |
| 40 | +
|
| 41 | + Args: |
| 42 | + image: The image to make a query against. |
| 43 | +
|
| 44 | + Returns: |
| 45 | + An ordered list of target details of matching targets. |
| 46 | + """ |
| 47 | + image_content = image.getvalue() |
| 48 | + body = { |
| 49 | + 'image': ('image.jpeg', image_content, 'image/jpeg'), |
| 50 | + } |
| 51 | + date = rfc_1123_date() |
| 52 | + request_path = '/v1/query' |
| 53 | + content, content_type_header = encode_multipart_formdata(body) |
| 54 | + method = 'POST' |
| 55 | + |
| 56 | + authorization_string = authorization_header( |
| 57 | + access_key=self._client_access_key, |
| 58 | + secret_key=self._client_secret_key, |
| 59 | + method=method, |
| 60 | + content=content, |
| 61 | + # Note that this is not the actual Content-Type header value sent. |
| 62 | + content_type='multipart/form-data', |
| 63 | + date=date, |
| 64 | + request_path=request_path, |
| 65 | + ) |
| 66 | + |
| 67 | + headers = { |
| 68 | + 'Authorization': authorization_string, |
| 69 | + 'Date': date, |
| 70 | + 'Content-Type': content_type_header, |
| 71 | + } |
| 72 | + |
| 73 | + base_vwq_url = 'https://cloudreco.vuforia.com' |
| 74 | + response = requests.request( |
| 75 | + method=method, |
| 76 | + url=urljoin(base=base_vwq_url, url=request_path), |
| 77 | + headers=headers, |
| 78 | + data=content, |
| 79 | + ) |
| 80 | + |
| 81 | + return list(response.json()['results']) |
0 commit comments