Skip to content

Commit f7e25db

Browse files
feat: [google-cloud-vision] Added option for user to set labels (#12277)
1 parent 57b5691 commit f7e25db

16 files changed

Lines changed: 1000 additions & 9 deletions

File tree

packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/async_client.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444

4545
from google.api_core import operation # type: ignore
4646
from google.api_core import operation_async # type: ignore
47+
from google.longrunning import operations_pb2 # type: ignore
4748

4849
from google.cloud.vision_v1.types import image_annotator
4950

@@ -773,6 +774,63 @@ async def sample_async_batch_annotate_files():
773774
# Done; return the response.
774775
return response
775776

777+
async def get_operation(
778+
self,
779+
request: Optional[operations_pb2.GetOperationRequest] = None,
780+
*,
781+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
782+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
783+
metadata: Sequence[Tuple[str, str]] = (),
784+
) -> operations_pb2.Operation:
785+
r"""Gets the latest state of a long-running operation.
786+
787+
Args:
788+
request (:class:`~.operations_pb2.GetOperationRequest`):
789+
The request object. Request message for
790+
`GetOperation` method.
791+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
792+
if any, should be retried.
793+
timeout (float): The timeout for this request.
794+
metadata (Sequence[Tuple[str, str]]): Strings which should be
795+
sent along with the request as metadata.
796+
Returns:
797+
~.operations_pb2.Operation:
798+
An ``Operation`` object.
799+
"""
800+
# Create or coerce a protobuf request object.
801+
# The request isn't a proto-plus wrapped type,
802+
# so it must be constructed via keyword expansion.
803+
if isinstance(request, dict):
804+
request = operations_pb2.GetOperationRequest(**request)
805+
806+
# Wrap the RPC method; this adds retry and timeout information,
807+
# and friendly error handling.
808+
rpc = gapic_v1.method_async.wrap_method(
809+
self._client._transport.get_operation,
810+
default_timeout=None,
811+
client_info=DEFAULT_CLIENT_INFO,
812+
)
813+
814+
# Certain fields should be provided within the metadata header;
815+
# add these here.
816+
metadata = tuple(metadata) + (
817+
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
818+
)
819+
820+
# Validate the universe domain.
821+
self._client._validate_universe_domain()
822+
823+
# Send the request.
824+
response = await rpc(
825+
request,
826+
retry=retry,
827+
timeout=timeout,
828+
metadata=metadata,
829+
)
830+
831+
# Done; return the response.
832+
return response
833+
776834
async def __aenter__(self) -> "ImageAnnotatorAsyncClient":
777835
return self
778836

packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/client.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949

5050
from google.api_core import operation # type: ignore
5151
from google.api_core import operation_async # type: ignore
52+
from google.longrunning import operations_pb2 # type: ignore
5253

5354
from google.cloud.vision_v1.types import image_annotator
5455

@@ -1185,6 +1186,63 @@ def __exit__(self, type, value, traceback):
11851186
"""
11861187
self.transport.close()
11871188

1189+
def get_operation(
1190+
self,
1191+
request: Optional[operations_pb2.GetOperationRequest] = None,
1192+
*,
1193+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
1194+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1195+
metadata: Sequence[Tuple[str, str]] = (),
1196+
) -> operations_pb2.Operation:
1197+
r"""Gets the latest state of a long-running operation.
1198+
1199+
Args:
1200+
request (:class:`~.operations_pb2.GetOperationRequest`):
1201+
The request object. Request message for
1202+
`GetOperation` method.
1203+
retry (google.api_core.retry.Retry): Designation of what errors,
1204+
if any, should be retried.
1205+
timeout (float): The timeout for this request.
1206+
metadata (Sequence[Tuple[str, str]]): Strings which should be
1207+
sent along with the request as metadata.
1208+
Returns:
1209+
~.operations_pb2.Operation:
1210+
An ``Operation`` object.
1211+
"""
1212+
# Create or coerce a protobuf request object.
1213+
# The request isn't a proto-plus wrapped type,
1214+
# so it must be constructed via keyword expansion.
1215+
if isinstance(request, dict):
1216+
request = operations_pb2.GetOperationRequest(**request)
1217+
1218+
# Wrap the RPC method; this adds retry and timeout information,
1219+
# and friendly error handling.
1220+
rpc = gapic_v1.method.wrap_method(
1221+
self._transport.get_operation,
1222+
default_timeout=None,
1223+
client_info=DEFAULT_CLIENT_INFO,
1224+
)
1225+
1226+
# Certain fields should be provided within the metadata header;
1227+
# add these here.
1228+
metadata = tuple(metadata) + (
1229+
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1230+
)
1231+
1232+
# Validate the universe domain.
1233+
self._validate_universe_domain()
1234+
1235+
# Send the request.
1236+
response = rpc(
1237+
request,
1238+
retry=retry,
1239+
timeout=timeout,
1240+
metadata=metadata,
1241+
)
1242+
1243+
# Done; return the response.
1244+
return response
1245+
11881246

11891247
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
11901248
gapic_version=package_version.__version__

packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/base.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,15 @@ def async_batch_annotate_files(
248248
]:
249249
raise NotImplementedError()
250250

251+
@property
252+
def get_operation(
253+
self,
254+
) -> Callable[
255+
[operations_pb2.GetOperationRequest],
256+
Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
257+
]:
258+
raise NotImplementedError()
259+
251260
@property
252261
def kind(self) -> str:
253262
raise NotImplementedError()

packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/grpc.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,23 @@ def async_batch_annotate_files(
390390
def close(self):
391391
self.grpc_channel.close()
392392

393+
@property
394+
def get_operation(
395+
self,
396+
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
397+
r"""Return a callable for the get_operation method over gRPC."""
398+
# Generate a "stub function" on-the-fly which will actually make
399+
# the request.
400+
# gRPC handles serialization and deserialization, so we just need
401+
# to pass in the functions for each.
402+
if "get_operation" not in self._stubs:
403+
self._stubs["get_operation"] = self.grpc_channel.unary_unary(
404+
"/google.longrunning.Operations/GetOperation",
405+
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
406+
response_deserializer=operations_pb2.Operation.FromString,
407+
)
408+
return self._stubs["get_operation"]
409+
393410
@property
394411
def kind(self) -> str:
395412
return "grpc"

packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/grpc_asyncio.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -397,5 +397,22 @@ def async_batch_annotate_files(
397397
def close(self):
398398
return self.grpc_channel.close()
399399

400+
@property
401+
def get_operation(
402+
self,
403+
) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]:
404+
r"""Return a callable for the get_operation method over gRPC."""
405+
# Generate a "stub function" on-the-fly which will actually make
406+
# the request.
407+
# gRPC handles serialization and deserialization, so we just need
408+
# to pass in the functions for each.
409+
if "get_operation" not in self._stubs:
410+
self._stubs["get_operation"] = self.grpc_channel.unary_unary(
411+
"/google.longrunning.Operations/GetOperation",
412+
request_serializer=operations_pb2.GetOperationRequest.SerializeToString,
413+
response_deserializer=operations_pb2.Operation.FromString,
414+
)
415+
return self._stubs["get_operation"]
416+
400417

401418
__all__ = ("ImageAnnotatorGrpcAsyncIOTransport",)

packages/google-cloud-vision/google/cloud/vision_v1/services/image_annotator/transports/rest.py

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,29 @@ def post_batch_annotate_images(
205205
"""
206206
return response
207207

208+
def pre_get_operation(
209+
self,
210+
request: operations_pb2.GetOperationRequest,
211+
metadata: Sequence[Tuple[str, str]],
212+
) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]:
213+
"""Pre-rpc interceptor for get_operation
214+
215+
Override in a subclass to manipulate the request or metadata
216+
before they are sent to the ImageAnnotator server.
217+
"""
218+
return request, metadata
219+
220+
def post_get_operation(
221+
self, response: operations_pb2.Operation
222+
) -> operations_pb2.Operation:
223+
"""Post-rpc interceptor for get_operation
224+
225+
Override in a subclass to manipulate the response
226+
after it is returned by the ImageAnnotator server but before
227+
it is returned to user code.
228+
"""
229+
return response
230+
208231

209232
@dataclasses.dataclass
210233
class ImageAnnotatorRestStub:
@@ -833,6 +856,84 @@ def batch_annotate_images(
833856
# In C++ this would require a dynamic_cast
834857
return self._BatchAnnotateImages(self._session, self._host, self._interceptor) # type: ignore
835858

859+
@property
860+
def get_operation(self):
861+
return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore
862+
863+
class _GetOperation(ImageAnnotatorRestStub):
864+
def __call__(
865+
self,
866+
request: operations_pb2.GetOperationRequest,
867+
*,
868+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
869+
timeout: Optional[float] = None,
870+
metadata: Sequence[Tuple[str, str]] = (),
871+
) -> operations_pb2.Operation:
872+
r"""Call the get operation method over HTTP.
873+
874+
Args:
875+
request (operations_pb2.GetOperationRequest):
876+
The request object for GetOperation method.
877+
retry (google.api_core.retry.Retry): Designation of what errors, if any,
878+
should be retried.
879+
timeout (float): The timeout for this request.
880+
metadata (Sequence[Tuple[str, str]]): Strings which should be
881+
sent along with the request as metadata.
882+
883+
Returns:
884+
operations_pb2.Operation: Response from GetOperation method.
885+
"""
886+
887+
http_options: List[Dict[str, str]] = [
888+
{
889+
"method": "get",
890+
"uri": "/v1/{name=projects/*/operations/*}",
891+
},
892+
{
893+
"method": "get",
894+
"uri": "/v1/{name=projects/*/locations/*/operations/*}",
895+
},
896+
{
897+
"method": "get",
898+
"uri": "/v1/{name=operations/*}",
899+
},
900+
{
901+
"method": "get",
902+
"uri": "/v1/{name=locations/*/operations/*}",
903+
},
904+
]
905+
906+
request, metadata = self._interceptor.pre_get_operation(request, metadata)
907+
request_kwargs = json_format.MessageToDict(request)
908+
transcoded_request = path_template.transcode(http_options, **request_kwargs)
909+
910+
uri = transcoded_request["uri"]
911+
method = transcoded_request["method"]
912+
913+
# Jsonify the query params
914+
query_params = json.loads(json.dumps(transcoded_request["query_params"]))
915+
916+
# Send the request
917+
headers = dict(metadata)
918+
headers["Content-Type"] = "application/json"
919+
920+
response = getattr(self._session, method)(
921+
"{host}{uri}".format(host=self._host, uri=uri),
922+
timeout=timeout,
923+
headers=headers,
924+
params=rest_helpers.flatten_query_params(query_params),
925+
)
926+
927+
# In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
928+
# subclass.
929+
if response.status_code >= 400:
930+
raise core_exceptions.from_http_response(response)
931+
932+
resp = operations_pb2.Operation()
933+
resp = json_format.Parse(response.content.decode("utf-8"), resp)
934+
resp = self._interceptor.post_get_operation(resp)
935+
return resp
936+
836937
@property
837938
def kind(self) -> str:
838939
return "rest"

packages/google-cloud-vision/google/cloud/vision_v1/services/product_search/async_client.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444

4545
from google.api_core import operation # type: ignore
4646
from google.api_core import operation_async # type: ignore
47+
from google.longrunning import operations_pb2 # type: ignore
4748
from google.protobuf import empty_pb2 # type: ignore
4849
from google.protobuf import field_mask_pb2 # type: ignore
4950
from google.protobuf import timestamp_pb2 # type: ignore
@@ -2841,6 +2842,63 @@ async def sample_purge_products():
28412842
# Done; return the response.
28422843
return response
28432844

2845+
async def get_operation(
2846+
self,
2847+
request: Optional[operations_pb2.GetOperationRequest] = None,
2848+
*,
2849+
retry: OptionalRetry = gapic_v1.method.DEFAULT,
2850+
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2851+
metadata: Sequence[Tuple[str, str]] = (),
2852+
) -> operations_pb2.Operation:
2853+
r"""Gets the latest state of a long-running operation.
2854+
2855+
Args:
2856+
request (:class:`~.operations_pb2.GetOperationRequest`):
2857+
The request object. Request message for
2858+
`GetOperation` method.
2859+
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
2860+
if any, should be retried.
2861+
timeout (float): The timeout for this request.
2862+
metadata (Sequence[Tuple[str, str]]): Strings which should be
2863+
sent along with the request as metadata.
2864+
Returns:
2865+
~.operations_pb2.Operation:
2866+
An ``Operation`` object.
2867+
"""
2868+
# Create or coerce a protobuf request object.
2869+
# The request isn't a proto-plus wrapped type,
2870+
# so it must be constructed via keyword expansion.
2871+
if isinstance(request, dict):
2872+
request = operations_pb2.GetOperationRequest(**request)
2873+
2874+
# Wrap the RPC method; this adds retry and timeout information,
2875+
# and friendly error handling.
2876+
rpc = gapic_v1.method_async.wrap_method(
2877+
self._client._transport.get_operation,
2878+
default_timeout=None,
2879+
client_info=DEFAULT_CLIENT_INFO,
2880+
)
2881+
2882+
# Certain fields should be provided within the metadata header;
2883+
# add these here.
2884+
metadata = tuple(metadata) + (
2885+
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
2886+
)
2887+
2888+
# Validate the universe domain.
2889+
self._client._validate_universe_domain()
2890+
2891+
# Send the request.
2892+
response = await rpc(
2893+
request,
2894+
retry=retry,
2895+
timeout=timeout,
2896+
metadata=metadata,
2897+
)
2898+
2899+
# Done; return the response.
2900+
return response
2901+
28442902
async def __aenter__(self) -> "ProductSearchAsyncClient":
28452903
return self
28462904

0 commit comments

Comments
 (0)