1# -*- coding: utf-8 -*- 2# Copyright 2020 Google LLC 3# 4# Licensed under the Apache License, Version 2.0 (the "License"); 5# you may not use this file except in compliance with the License. 6# You may obtain a copy of the License at 7# 8# http://www.apache.org/licenses/LICENSE-2.0 9# 10# Unless required by applicable law or agreed to in writing, software 11# distributed under the License is distributed on an "AS IS" BASIS, 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13# See the License for the specific language governing permissions and 14# limitations under the License. 15# 16from collections import OrderedDict 17import functools 18import re 19from typing import Dict, Sequence, Tuple, Type, Union 20import pkg_resources 21 22from google.api_core.client_options import ClientOptions # type: ignore 23from google.api_core import exceptions as core_exceptions # type: ignore 24from google.api_core import gapic_v1 # type: ignore 25from google.api_core import retry as retries # type: ignore 26from google.auth import credentials as ga_credentials # type: ignore 27from google.oauth2 import service_account # type: ignore 28 29OptionalRetry = Union[retries.Retry, object] 30 31from google.cloud.vision_v1p1beta1.types import image_annotator 32from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO 33from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport 34from .client import ImageAnnotatorClient 35 36 37class ImageAnnotatorAsyncClient: 38 """Service that performs Google Cloud Vision API detection tasks 39 over client images, such as face, landmark, logo, label, and 40 text detection. The ImageAnnotator service returns detected 41 entities from the images. 42 """ 43 44 _client: ImageAnnotatorClient 45 46 DEFAULT_ENDPOINT = ImageAnnotatorClient.DEFAULT_ENDPOINT 47 DEFAULT_MTLS_ENDPOINT = ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT 48 49 common_billing_account_path = staticmethod( 50 ImageAnnotatorClient.common_billing_account_path 51 ) 52 parse_common_billing_account_path = staticmethod( 53 ImageAnnotatorClient.parse_common_billing_account_path 54 ) 55 common_folder_path = staticmethod(ImageAnnotatorClient.common_folder_path) 56 parse_common_folder_path = staticmethod( 57 ImageAnnotatorClient.parse_common_folder_path 58 ) 59 common_organization_path = staticmethod( 60 ImageAnnotatorClient.common_organization_path 61 ) 62 parse_common_organization_path = staticmethod( 63 ImageAnnotatorClient.parse_common_organization_path 64 ) 65 common_project_path = staticmethod(ImageAnnotatorClient.common_project_path) 66 parse_common_project_path = staticmethod( 67 ImageAnnotatorClient.parse_common_project_path 68 ) 69 common_location_path = staticmethod(ImageAnnotatorClient.common_location_path) 70 parse_common_location_path = staticmethod( 71 ImageAnnotatorClient.parse_common_location_path 72 ) 73 74 @classmethod 75 def from_service_account_info(cls, info: dict, *args, **kwargs): 76 """Creates an instance of this client using the provided credentials 77 info. 78 79 Args: 80 info (dict): The service account private key info. 81 args: Additional arguments to pass to the constructor. 82 kwargs: Additional arguments to pass to the constructor. 83 84 Returns: 85 ImageAnnotatorAsyncClient: The constructed client. 86 """ 87 return ImageAnnotatorClient.from_service_account_info.__func__(ImageAnnotatorAsyncClient, info, *args, **kwargs) # type: ignore 88 89 @classmethod 90 def from_service_account_file(cls, filename: str, *args, **kwargs): 91 """Creates an instance of this client using the provided credentials 92 file. 93 94 Args: 95 filename (str): The path to the service account private key json 96 file. 97 args: Additional arguments to pass to the constructor. 98 kwargs: Additional arguments to pass to the constructor. 99 100 Returns: 101 ImageAnnotatorAsyncClient: The constructed client. 102 """ 103 return ImageAnnotatorClient.from_service_account_file.__func__(ImageAnnotatorAsyncClient, filename, *args, **kwargs) # type: ignore 104 105 from_service_account_json = from_service_account_file 106 107 @property 108 def transport(self) -> ImageAnnotatorTransport: 109 """Returns the transport used by the client instance. 110 111 Returns: 112 ImageAnnotatorTransport: The transport used by the client instance. 113 """ 114 return self._client.transport 115 116 get_transport_class = functools.partial( 117 type(ImageAnnotatorClient).get_transport_class, type(ImageAnnotatorClient) 118 ) 119 120 def __init__( 121 self, 122 *, 123 credentials: ga_credentials.Credentials = None, 124 transport: Union[str, ImageAnnotatorTransport] = "grpc_asyncio", 125 client_options: ClientOptions = None, 126 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 127 ) -> None: 128 """Instantiates the image annotator client. 129 130 Args: 131 credentials (Optional[google.auth.credentials.Credentials]): The 132 authorization credentials to attach to requests. These 133 credentials identify the application to the service; if none 134 are specified, the client will attempt to ascertain the 135 credentials from the environment. 136 transport (Union[str, ~.ImageAnnotatorTransport]): The 137 transport to use. If set to None, a transport is chosen 138 automatically. 139 client_options (ClientOptions): Custom options for the client. It 140 won't take effect if a ``transport`` instance is provided. 141 (1) The ``api_endpoint`` property can be used to override the 142 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT 143 environment variable can also be used to override the endpoint: 144 "always" (always use the default mTLS endpoint), "never" (always 145 use the default regular endpoint) and "auto" (auto switch to the 146 default mTLS endpoint if client certificate is present, this is 147 the default value). However, the ``api_endpoint`` property takes 148 precedence if provided. 149 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 150 is "true", then the ``client_cert_source`` property can be used 151 to provide client certificate for mutual TLS transport. If 152 not provided, the default SSL client certificate will be used if 153 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 154 set, no client certificate will be used. 155 156 Raises: 157 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport 158 creation failed for any reason. 159 """ 160 self._client = ImageAnnotatorClient( 161 credentials=credentials, 162 transport=transport, 163 client_options=client_options, 164 client_info=client_info, 165 ) 166 167 async def batch_annotate_images( 168 self, 169 request: Union[image_annotator.BatchAnnotateImagesRequest, dict] = None, 170 *, 171 requests: Sequence[image_annotator.AnnotateImageRequest] = None, 172 retry: OptionalRetry = gapic_v1.method.DEFAULT, 173 timeout: float = None, 174 metadata: Sequence[Tuple[str, str]] = (), 175 ) -> image_annotator.BatchAnnotateImagesResponse: 176 r"""Run image detection and annotation for a batch of 177 images. 178 179 Args: 180 request (Union[google.cloud.vision_v1p1beta1.types.BatchAnnotateImagesRequest, dict]): 181 The request object. Multiple image annotation requests 182 are batched into a single service call. 183 requests (:class:`Sequence[google.cloud.vision_v1p1beta1.types.AnnotateImageRequest]`): 184 Required. Individual image annotation 185 requests for this batch. 186 187 This corresponds to the ``requests`` field 188 on the ``request`` instance; if ``request`` is provided, this 189 should not be set. 190 retry (google.api_core.retry.Retry): Designation of what errors, if any, 191 should be retried. 192 timeout (float): The timeout for this request. 193 metadata (Sequence[Tuple[str, str]]): Strings which should be 194 sent along with the request as metadata. 195 196 Returns: 197 google.cloud.vision_v1p1beta1.types.BatchAnnotateImagesResponse: 198 Response to a batch image annotation 199 request. 200 201 """ 202 # Create or coerce a protobuf request object. 203 # Sanity check: If we got a request object, we should *not* have 204 # gotten any keyword arguments that map to the request. 205 has_flattened_params = any([requests]) 206 if request is not None and has_flattened_params: 207 raise ValueError( 208 "If the `request` argument is set, then none of " 209 "the individual field arguments should be set." 210 ) 211 212 request = image_annotator.BatchAnnotateImagesRequest(request) 213 214 # If we have keyword arguments corresponding to fields on the 215 # request, apply these. 216 if requests: 217 request.requests.extend(requests) 218 219 # Wrap the RPC method; this adds retry and timeout information, 220 # and friendly error handling. 221 rpc = gapic_v1.method_async.wrap_method( 222 self._client._transport.batch_annotate_images, 223 default_retry=retries.Retry( 224 initial=0.1, 225 maximum=60.0, 226 multiplier=1.3, 227 predicate=retries.if_exception_type( 228 core_exceptions.DeadlineExceeded, 229 core_exceptions.ServiceUnavailable, 230 ), 231 deadline=600.0, 232 ), 233 default_timeout=600.0, 234 client_info=DEFAULT_CLIENT_INFO, 235 ) 236 237 # Send the request. 238 response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) 239 240 # Done; return the response. 241 return response 242 243 async def __aenter__(self): 244 return self 245 246 async def __aexit__(self, exc_type, exc, tb): 247 await self.transport.close() 248 249 250try: 251 DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 252 gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, 253 ) 254except pkg_resources.DistributionNotFound: 255 DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() 256 257 258__all__ = ("ImageAnnotatorAsyncClient",) 259