From cf3d35306c3a8f6d32cc7ce1eb436c965acc30fe Mon Sep 17 00:00:00 2001 From: arithmetic1728 <58957152+arithmetic1728@users.noreply.github.com> Date: Tue, 29 Sep 2020 11:49:43 -0700 Subject: [PATCH] feat!: migrate to use microgen (#52) * feat!: migrate to use microgen * chore: update code * chore: lint --- .coveragerc | 13 +- .kokoro/populate-secrets.sh | 43 + .kokoro/release/common.cfg | 50 +- .kokoro/trampoline.sh | 15 +- CONTRIBUTING.rst | 19 - README.rst | 6 +- UPGRADING.md | 162 + docs/UPGRADING.md | 1 + docs/conf.py | 1 + docs/gapic/v1/api.rst | 6 - docs/gapic/v1/types.rst | 5 - docs/gapic/v1p2beta1/api.rst | 6 - docs/gapic/v1p2beta1/types.rst | 5 - docs/gapic/v1p3beta1/api.rst | 6 - docs/gapic/v1p3beta1/types.rst | 5 - docs/gapic/v1p4beta1/api.rst | 6 - docs/gapic/v1p4beta1/types.rst | 5 - docs/index.rst | 28 +- docs/vision_v1/services.rst | 9 + docs/vision_v1/types.rst | 5 + docs/vision_v1p2beta1/services.rst | 6 + docs/vision_v1p2beta1/types.rst | 5 + docs/vision_v1p3beta1/services.rst | 9 + docs/vision_v1p3beta1/types.rst | 5 + docs/vision_v1p4beta1/services.rst | 9 + docs/vision_v1p4beta1/types.rst | 5 + google/cloud/vision/__init__.py | 222 + google/cloud/vision/py.typed | 2 + google/cloud/vision_helpers/__init__.py | 58 +- google/cloud/vision_helpers/decorators.py | 31 +- google/cloud/vision_v1/__init__.py | 204 +- google/cloud/vision_v1/gapic/__init__.py | 0 google/cloud/vision_v1/gapic/enums.py | 255 - .../vision_v1/gapic/image_annotator_client.py | 599 -- .../gapic/image_annotator_client_config.py | 52 - .../vision_v1/gapic/product_search_client.py | 2026 ------ .../gapic/product_search_client_config.py | 137 - .../vision_v1/gapic/transports/__init__.py | 0 .../image_annotator_grpc_transport.py | 194 - .../product_search_grpc_transport.py | 510 -- google/cloud/vision_v1/proto/__init__.py | 0 google/cloud/vision_v1/proto/geometry_pb2.py | 373 -- .../vision_v1/proto/geometry_pb2_grpc.py | 3 - .../vision_v1/proto/image_annotator_pb2.py | 5188 ---------------- .../proto/image_annotator_pb2_grpc.py | 243 - .../vision_v1/proto/product_search_pb2.py | 655 -- .../proto/product_search_pb2_grpc.py | 3 - .../proto/product_search_service_pb2.py | 3368 ---------- .../proto/product_search_service_pb2_grpc.py | 1055 ---- .../vision_v1/proto/text_annotation_pb2.py | 1224 ---- .../proto/text_annotation_pb2_grpc.py | 3 - .../vision_v1/proto/web_detection_pb2.py | 629 -- .../vision_v1/proto/web_detection_pb2_grpc.py | 3 - google/cloud/vision_v1/py.typed | 2 + .../{ => vision_v1/services}/__init__.py | 14 +- .../services/image_annotator/__init__.py} | 20 +- .../services/image_annotator/async_client.py | 464 ++ .../services/image_annotator/client.py | 604 ++ .../image_annotator/transports/__init__.py | 36 + .../image_annotator/transports/base.py | 214 + .../image_annotator/transports/grpc.py | 393 ++ .../transports/grpc_asyncio.py | 395 ++ .../services/product_search/__init__.py | 24 + .../services/product_search/async_client.py | 1995 ++++++ .../services/product_search/client.py | 2093 +++++++ .../services/product_search/pagers.py | 546 ++ .../product_search/transports/__init__.py | 36 + .../product_search/transports/base.py | 565 ++ .../product_search/transports/grpc.py | 954 +++ .../product_search/transports/grpc_asyncio.py | 970 +++ google/cloud/vision_v1/types.py | 74 - google/cloud/vision_v1/types/__init__.py | 195 + google/cloud/vision_v1/types/geometry.py | 100 + .../cloud/vision_v1/types/image_annotator.py | 1266 ++++ .../cloud/vision_v1/types/product_search.py | 185 + .../vision_v1/types/product_search_service.py | 891 +++ .../cloud/vision_v1/types/text_annotation.py | 320 + google/cloud/vision_v1/types/web_detection.py | 163 + google/cloud/vision_v1p1beta1/__init__.py | 95 +- .../cloud/vision_v1p1beta1/gapic/__init__.py | 0 google/cloud/vision_v1p1beta1/gapic/enums.py | 204 - .../gapic/image_annotator_client.py | 247 - .../gapic/image_annotator_client_config.py | 37 - .../gapic/transports/__init__.py | 0 .../image_annotator_grpc_transport.py | 126 - .../cloud/vision_v1p1beta1/proto/__init__.py | 0 .../vision_v1p1beta1/proto/geometry_pb2.py | 269 - .../proto/geometry_pb2_grpc.py | 3 - .../proto/image_annotator_pb2.py | 3178 ---------- .../proto/image_annotator_pb2_grpc.py | 89 - .../proto/product_search.proto | 161 - .../proto/product_search_service.proto | 825 --- .../proto/text_annotation_pb2.py | 1221 ---- .../proto/text_annotation_pb2_grpc.py | 3 - .../proto/web_detection_pb2.py | 628 -- .../proto/web_detection_pb2_grpc.py | 3 - google/cloud/vision_v1p1beta1/py.typed | 2 + .../vision_v1p1beta1/services}/__init__.py | 16 +- .../services/image_annotator/__init__.py | 24 + .../services/image_annotator/async_client.py | 188 + .../services/image_annotator/client.py | 333 + .../image_annotator/transports/__init__.py | 36 + .../image_annotator/transports/base.py | 138 + .../image_annotator/transports/grpc.py | 266 + .../transports/grpc_asyncio.py | 266 + google/cloud/vision_v1p1beta1/types.py | 62 - .../cloud/vision_v1p1beta1/types/__init__.py | 89 + .../cloud/vision_v1p1beta1/types/geometry.py | 77 + .../vision_v1p1beta1/types/image_annotator.py | 735 +++ .../vision_v1p1beta1/types/text_annotation.py | 305 + .../vision_v1p1beta1/types/web_detection.py | 161 + google/cloud/vision_v1p2beta1/__init__.py | 119 +- .../cloud/vision_v1p2beta1/gapic/__init__.py | 0 google/cloud/vision_v1p2beta1/gapic/enums.py | 228 - .../gapic/image_annotator_client.py | 330 - .../gapic/image_annotator_client_config.py | 42 - .../gapic/transports/__init__.py | 0 .../image_annotator_grpc_transport.py | 152 - .../cloud/vision_v1p2beta1/proto/__init__.py | 0 .../vision_v1p2beta1/proto/geometry_pb2.py | 369 -- .../proto/geometry_pb2_grpc.py | 3 - .../proto/image_annotator_pb2.py | 4175 ------------- .../proto/image_annotator_pb2_grpc.py | 141 - .../proto/product_search.proto | 161 - .../proto/product_search_service.proto | 825 --- .../proto/text_annotation_pb2.py | 1224 ---- .../proto/text_annotation_pb2_grpc.py | 3 - .../proto/web_detection_pb2.py | 628 -- .../proto/web_detection_pb2_grpc.py | 3 - google/cloud/vision_v1p2beta1/py.typed | 2 + .../vision_v1p2beta1/services/__init__.py | 16 + .../services/image_annotator/__init__.py | 24 + .../services/image_annotator/async_client.py | 280 + .../services/image_annotator/client.py | 424 ++ .../image_annotator/transports/__init__.py | 36 + .../image_annotator/transports/base.py | 167 + .../image_annotator/transports/grpc.py | 318 + .../transports/grpc_asyncio.py | 319 + google/cloud/vision_v1p2beta1/types.py | 66 - .../cloud/vision_v1p2beta1/types/__init__.py | 113 + .../cloud/vision_v1p2beta1/types/geometry.py | 100 + .../vision_v1p2beta1/types/image_annotator.py | 983 +++ .../vision_v1p2beta1/types/text_annotation.py | 320 + .../vision_v1p2beta1/types/web_detection.py | 161 + google/cloud/vision_v1p3beta1/__init__.py | 196 +- .../cloud/vision_v1p3beta1/gapic/__init__.py | 0 google/cloud/vision_v1p3beta1/gapic/enums.py | 285 - .../gapic/image_annotator_client.py | 331 - .../gapic/image_annotator_client_config.py | 52 - .../gapic/product_search_client.py | 1908 ------ .../gapic/product_search_client_config.py | 132 - .../gapic/transports/__init__.py | 0 .../image_annotator_grpc_transport.py | 152 - .../product_search_grpc_transport.py | 490 -- .../cloud/vision_v1p3beta1/proto/__init__.py | 0 .../vision_v1p3beta1/proto/geometry_pb2.py | 433 -- .../proto/geometry_pb2_grpc.py | 3 - .../proto/image_annotator_pb2.py | 4426 ------------- .../proto/image_annotator_pb2_grpc.py | 141 - .../proto/product_search_pb2.py | 753 --- .../proto/product_search_pb2_grpc.py | 3 - .../proto/product_search_service_pb2.py | 3133 ---------- .../proto/product_search_service_pb2_grpc.py | 1003 --- .../proto/text_annotation_pb2.py | 1224 ---- .../proto/text_annotation_pb2_grpc.py | 3 - .../proto/web_detection_pb2.py | 628 -- .../proto/web_detection_pb2_grpc.py | 3 - google/cloud/vision_v1p3beta1/py.typed | 2 + .../vision_v1p3beta1/services/__init__.py | 16 + .../services/image_annotator/__init__.py | 24 + .../services/image_annotator/async_client.py | 278 + .../services/image_annotator/client.py | 424 ++ .../image_annotator/transports/__init__.py | 36 + .../image_annotator/transports/base.py | 165 + .../image_annotator/transports/grpc.py | 318 + .../transports/grpc_asyncio.py | 319 + .../services/product_search/__init__.py | 24 + .../services/product_search/async_client.py | 1878 ++++++ .../services/product_search/client.py | 1988 ++++++ .../services/product_search/pagers.py | 546 ++ .../product_search/transports/__init__.py | 36 + .../product_search/transports/base.py | 537 ++ .../product_search/transports/grpc.py | 922 +++ .../product_search/transports/grpc_asyncio.py | 936 +++ google/cloud/vision_v1p3beta1/types.py | 74 - .../cloud/vision_v1p3beta1/types/__init__.py | 183 + .../cloud/vision_v1p3beta1/types/geometry.py | 117 + .../vision_v1p3beta1/types/image_annotator.py | 1039 ++++ .../vision_v1p3beta1/types/product_search.py | 203 + .../types/product_search_service.py | 825 +++ .../vision_v1p3beta1/types/text_annotation.py | 320 + .../vision_v1p3beta1/types/web_detection.py | 161 + google/cloud/vision_v1p4beta1/__init__.py | 210 +- .../cloud/vision_v1p4beta1/gapic/__init__.py | 0 google/cloud/vision_v1p4beta1/gapic/enums.py | 255 - .../gapic/image_annotator_client.py | 498 -- .../gapic/image_annotator_client_config.py | 49 - .../gapic/product_search_client.py | 2026 ------ .../gapic/product_search_client_config.py | 137 - .../gapic/transports/__init__.py | 0 .../image_annotator_grpc_transport.py | 194 - .../product_search_grpc_transport.py | 510 -- .../cloud/vision_v1p4beta1/proto/__init__.py | 0 .../cloud/vision_v1p4beta1/proto/face_pb2.py | 286 - .../vision_v1p4beta1/proto/face_pb2_grpc.py | 3 - .../vision_v1p4beta1/proto/geometry_pb2.py | 373 -- .../proto/geometry_pb2_grpc.py | 3 - .../proto/image_annotator_pb2.py | 5016 --------------- .../proto/image_annotator_pb2_grpc.py | 243 - .../proto/product_search_pb2.py | 654 -- .../proto/product_search_pb2_grpc.py | 3 - .../proto/product_search_service_pb2.py | 3367 ---------- .../proto/product_search_service_pb2_grpc.py | 1067 ---- .../proto/text_annotation_pb2.py | 1224 ---- .../proto/text_annotation_pb2_grpc.py | 3 - .../proto/web_detection_pb2.py | 629 -- .../proto/web_detection_pb2_grpc.py | 3 - google/cloud/vision_v1p4beta1/py.typed | 2 + .../vision_v1p4beta1/services/__init__.py | 16 + .../services/image_annotator/__init__.py | 24 + .../services/image_annotator/async_client.py | 456 ++ .../services/image_annotator/client.py | 604 ++ .../image_annotator/transports/__init__.py | 36 + .../image_annotator/transports/base.py | 206 + .../image_annotator/transports/grpc.py | 393 ++ .../transports/grpc_asyncio.py | 395 ++ .../services/product_search/__init__.py | 24 + .../services/product_search/async_client.py | 1983 ++++++ .../services/product_search/client.py | 2095 +++++++ .../services/product_search/pagers.py | 546 ++ .../product_search/transports/__init__.py | 36 + .../product_search/transports/base.py | 549 ++ .../product_search/transports/grpc.py | 956 +++ .../product_search/transports/grpc_asyncio.py | 972 +++ google/cloud/vision_v1p4beta1/types.py | 76 - .../cloud/vision_v1p4beta1/types/__init__.py | 203 + google/cloud/vision_v1p4beta1/types/face.py | 79 + .../cloud/vision_v1p4beta1/types/geometry.py | 100 + .../vision_v1p4beta1/types/image_annotator.py | 1196 ++++ .../vision_v1p4beta1/types/product_search.py | 185 + .../types/product_search_service.py | 891 +++ .../vision_v1p4beta1/types/text_annotation.py | 320 + .../vision_v1p4beta1/types/web_detection.py | 163 + mypy.ini | 3 + noxfile.py | 6 +- samples/snippets/crop_hints/crop_hints.py | 7 +- samples/snippets/detect/beta_snippets.py | 51 +- samples/snippets/detect/detect.py | 92 +- samples/snippets/detect/set_endpoint.py | 4 +- .../vision_async_batch_annotate_images.py | 7 +- .../detect/vision_batch_annotate_files.py | 5 +- .../detect/vision_batch_annotate_files_gcs.py | 5 +- samples/snippets/document_text/doctext.py | 3 +- samples/snippets/face_detection/faces.py | 3 +- .../product_search/import_product_sets.py | 7 +- .../product_in_product_set_management.py | 14 +- .../product_search/product_management.py | 25 +- .../snippets/product_search/product_search.py | 24 +- .../product_search/product_set_management.py | 18 +- .../reference_image_management.py | 2 +- samples/snippets/quickstart/quickstart.py | 3 +- samples/snippets/web/web_detect.py | 5 +- scripts/fixup_vision_v1_keywords.py | 200 + scripts/fixup_vision_v1p1beta1_keywords.py | 178 + scripts/fixup_vision_v1p2beta1_keywords.py | 179 + scripts/fixup_vision_v1p3beta1_keywords.py | 197 + scripts/fixup_vision_v1p4beta1_keywords.py | 200 + setup.py | 22 +- synth.metadata | 239 +- synth.py | 94 +- tests/system.py | 75 +- .../v1/test_image_annotator_client_v1.py | 256 - .../gapic/v1/test_product_search_client_v1.py | 895 --- .../test_image_annotator_client_v1p1beta1.py | 102 - .../test_image_annotator_client_v1p2beta1.py | 159 - .../test_image_annotator_client_v1p3beta1.py | 151 - .../test_product_search_client_v1p3beta1.py | 843 --- .../test_image_annotator_client_v1p4beta1.py | 256 - .../test_product_search_client_v1p4beta1.py | 895 --- tests/unit/gapic/vision_v1/__init__.py | 1 + .../gapic/vision_v1/test_image_annotator.py | 1510 +++++ .../gapic/vision_v1/test_product_search.py | 5488 ++++++++++++++++ tests/unit/gapic/vision_v1p1beta1/__init__.py | 1 + .../vision_v1p1beta1/test_image_annotator.py | 927 +++ tests/unit/gapic/vision_v1p2beta1/__init__.py | 1 + .../vision_v1p2beta1/test_image_annotator.py | 1143 ++++ tests/unit/gapic/vision_v1p3beta1/__init__.py | 1 + .../vision_v1p3beta1/test_image_annotator.py | 1145 ++++ .../vision_v1p3beta1/test_product_search.py | 5304 ++++++++++++++++ tests/unit/gapic/vision_v1p4beta1/__init__.py | 1 + .../vision_v1p4beta1/test_image_annotator.py | 1513 +++++ .../vision_v1p4beta1/test_product_search.py | 5490 +++++++++++++++++ tests/unit/test_decorators.py | 16 +- tests/unit/test_helpers.py | 41 +- 294 files changed, 67081 insertions(+), 68165 deletions(-) create mode 100755 .kokoro/populate-secrets.sh create mode 100644 UPGRADING.md create mode 120000 docs/UPGRADING.md delete mode 100644 docs/gapic/v1/api.rst delete mode 100644 docs/gapic/v1/types.rst delete mode 100644 docs/gapic/v1p2beta1/api.rst delete mode 100644 docs/gapic/v1p2beta1/types.rst delete mode 100644 docs/gapic/v1p3beta1/api.rst delete mode 100644 docs/gapic/v1p3beta1/types.rst delete mode 100644 docs/gapic/v1p4beta1/api.rst delete mode 100644 docs/gapic/v1p4beta1/types.rst create mode 100644 docs/vision_v1/services.rst create mode 100644 docs/vision_v1/types.rst create mode 100644 docs/vision_v1p2beta1/services.rst create mode 100644 docs/vision_v1p2beta1/types.rst create mode 100644 docs/vision_v1p3beta1/services.rst create mode 100644 docs/vision_v1p3beta1/types.rst create mode 100644 docs/vision_v1p4beta1/services.rst create mode 100644 docs/vision_v1p4beta1/types.rst create mode 100644 google/cloud/vision/__init__.py create mode 100644 google/cloud/vision/py.typed delete mode 100644 google/cloud/vision_v1/gapic/__init__.py delete mode 100644 google/cloud/vision_v1/gapic/enums.py delete mode 100644 google/cloud/vision_v1/gapic/image_annotator_client.py delete mode 100644 google/cloud/vision_v1/gapic/image_annotator_client_config.py delete mode 100644 google/cloud/vision_v1/gapic/product_search_client.py delete mode 100644 google/cloud/vision_v1/gapic/product_search_client_config.py delete mode 100644 google/cloud/vision_v1/gapic/transports/__init__.py delete mode 100644 google/cloud/vision_v1/gapic/transports/image_annotator_grpc_transport.py delete mode 100644 google/cloud/vision_v1/gapic/transports/product_search_grpc_transport.py delete mode 100644 google/cloud/vision_v1/proto/__init__.py delete mode 100644 google/cloud/vision_v1/proto/geometry_pb2.py delete mode 100644 google/cloud/vision_v1/proto/geometry_pb2_grpc.py delete mode 100644 google/cloud/vision_v1/proto/image_annotator_pb2.py delete mode 100644 google/cloud/vision_v1/proto/image_annotator_pb2_grpc.py delete mode 100644 google/cloud/vision_v1/proto/product_search_pb2.py delete mode 100644 google/cloud/vision_v1/proto/product_search_pb2_grpc.py delete mode 100644 google/cloud/vision_v1/proto/product_search_service_pb2.py delete mode 100644 google/cloud/vision_v1/proto/product_search_service_pb2_grpc.py delete mode 100644 google/cloud/vision_v1/proto/text_annotation_pb2.py delete mode 100644 google/cloud/vision_v1/proto/text_annotation_pb2_grpc.py delete mode 100644 google/cloud/vision_v1/proto/web_detection_pb2.py delete mode 100644 google/cloud/vision_v1/proto/web_detection_pb2_grpc.py create mode 100644 google/cloud/vision_v1/py.typed rename google/cloud/{ => vision_v1/services}/__init__.py (73%) rename google/cloud/{vision.py => vision_v1/services/image_annotator/__init__.py} (56%) create mode 100644 google/cloud/vision_v1/services/image_annotator/async_client.py create mode 100644 google/cloud/vision_v1/services/image_annotator/client.py create mode 100644 google/cloud/vision_v1/services/image_annotator/transports/__init__.py create mode 100644 google/cloud/vision_v1/services/image_annotator/transports/base.py create mode 100644 google/cloud/vision_v1/services/image_annotator/transports/grpc.py create mode 100644 google/cloud/vision_v1/services/image_annotator/transports/grpc_asyncio.py create mode 100644 google/cloud/vision_v1/services/product_search/__init__.py create mode 100644 google/cloud/vision_v1/services/product_search/async_client.py create mode 100644 google/cloud/vision_v1/services/product_search/client.py create mode 100644 google/cloud/vision_v1/services/product_search/pagers.py create mode 100644 google/cloud/vision_v1/services/product_search/transports/__init__.py create mode 100644 google/cloud/vision_v1/services/product_search/transports/base.py create mode 100644 google/cloud/vision_v1/services/product_search/transports/grpc.py create mode 100644 google/cloud/vision_v1/services/product_search/transports/grpc_asyncio.py delete mode 100644 google/cloud/vision_v1/types.py create mode 100644 google/cloud/vision_v1/types/__init__.py create mode 100644 google/cloud/vision_v1/types/geometry.py create mode 100644 google/cloud/vision_v1/types/image_annotator.py create mode 100644 google/cloud/vision_v1/types/product_search.py create mode 100644 google/cloud/vision_v1/types/product_search_service.py create mode 100644 google/cloud/vision_v1/types/text_annotation.py create mode 100644 google/cloud/vision_v1/types/web_detection.py delete mode 100644 google/cloud/vision_v1p1beta1/gapic/__init__.py delete mode 100644 google/cloud/vision_v1p1beta1/gapic/enums.py delete mode 100644 google/cloud/vision_v1p1beta1/gapic/image_annotator_client.py delete mode 100644 google/cloud/vision_v1p1beta1/gapic/image_annotator_client_config.py delete mode 100644 google/cloud/vision_v1p1beta1/gapic/transports/__init__.py delete mode 100644 google/cloud/vision_v1p1beta1/gapic/transports/image_annotator_grpc_transport.py delete mode 100644 google/cloud/vision_v1p1beta1/proto/__init__.py delete mode 100644 google/cloud/vision_v1p1beta1/proto/geometry_pb2.py delete mode 100644 google/cloud/vision_v1p1beta1/proto/geometry_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p1beta1/proto/image_annotator_pb2.py delete mode 100644 google/cloud/vision_v1p1beta1/proto/image_annotator_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p1beta1/proto/product_search.proto delete mode 100644 google/cloud/vision_v1p1beta1/proto/product_search_service.proto delete mode 100644 google/cloud/vision_v1p1beta1/proto/text_annotation_pb2.py delete mode 100644 google/cloud/vision_v1p1beta1/proto/text_annotation_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p1beta1/proto/web_detection_pb2.py delete mode 100644 google/cloud/vision_v1p1beta1/proto/web_detection_pb2_grpc.py create mode 100644 google/cloud/vision_v1p1beta1/py.typed rename google/{ => cloud/vision_v1p1beta1/services}/__init__.py (66%) create mode 100644 google/cloud/vision_v1p1beta1/services/image_annotator/__init__.py create mode 100644 google/cloud/vision_v1p1beta1/services/image_annotator/async_client.py create mode 100644 google/cloud/vision_v1p1beta1/services/image_annotator/client.py create mode 100644 google/cloud/vision_v1p1beta1/services/image_annotator/transports/__init__.py create mode 100644 google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py create mode 100644 google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py create mode 100644 google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc_asyncio.py delete mode 100644 google/cloud/vision_v1p1beta1/types.py create mode 100644 google/cloud/vision_v1p1beta1/types/__init__.py create mode 100644 google/cloud/vision_v1p1beta1/types/geometry.py create mode 100644 google/cloud/vision_v1p1beta1/types/image_annotator.py create mode 100644 google/cloud/vision_v1p1beta1/types/text_annotation.py create mode 100644 google/cloud/vision_v1p1beta1/types/web_detection.py delete mode 100644 google/cloud/vision_v1p2beta1/gapic/__init__.py delete mode 100644 google/cloud/vision_v1p2beta1/gapic/enums.py delete mode 100644 google/cloud/vision_v1p2beta1/gapic/image_annotator_client.py delete mode 100644 google/cloud/vision_v1p2beta1/gapic/image_annotator_client_config.py delete mode 100644 google/cloud/vision_v1p2beta1/gapic/transports/__init__.py delete mode 100644 google/cloud/vision_v1p2beta1/gapic/transports/image_annotator_grpc_transport.py delete mode 100644 google/cloud/vision_v1p2beta1/proto/__init__.py delete mode 100644 google/cloud/vision_v1p2beta1/proto/geometry_pb2.py delete mode 100644 google/cloud/vision_v1p2beta1/proto/geometry_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p2beta1/proto/image_annotator_pb2.py delete mode 100644 google/cloud/vision_v1p2beta1/proto/image_annotator_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p2beta1/proto/product_search.proto delete mode 100644 google/cloud/vision_v1p2beta1/proto/product_search_service.proto delete mode 100644 google/cloud/vision_v1p2beta1/proto/text_annotation_pb2.py delete mode 100644 google/cloud/vision_v1p2beta1/proto/text_annotation_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p2beta1/proto/web_detection_pb2.py delete mode 100644 google/cloud/vision_v1p2beta1/proto/web_detection_pb2_grpc.py create mode 100644 google/cloud/vision_v1p2beta1/py.typed create mode 100644 google/cloud/vision_v1p2beta1/services/__init__.py create mode 100644 google/cloud/vision_v1p2beta1/services/image_annotator/__init__.py create mode 100644 google/cloud/vision_v1p2beta1/services/image_annotator/async_client.py create mode 100644 google/cloud/vision_v1p2beta1/services/image_annotator/client.py create mode 100644 google/cloud/vision_v1p2beta1/services/image_annotator/transports/__init__.py create mode 100644 google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py create mode 100644 google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py create mode 100644 google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc_asyncio.py delete mode 100644 google/cloud/vision_v1p2beta1/types.py create mode 100644 google/cloud/vision_v1p2beta1/types/__init__.py create mode 100644 google/cloud/vision_v1p2beta1/types/geometry.py create mode 100644 google/cloud/vision_v1p2beta1/types/image_annotator.py create mode 100644 google/cloud/vision_v1p2beta1/types/text_annotation.py create mode 100644 google/cloud/vision_v1p2beta1/types/web_detection.py delete mode 100644 google/cloud/vision_v1p3beta1/gapic/__init__.py delete mode 100644 google/cloud/vision_v1p3beta1/gapic/enums.py delete mode 100644 google/cloud/vision_v1p3beta1/gapic/image_annotator_client.py delete mode 100644 google/cloud/vision_v1p3beta1/gapic/image_annotator_client_config.py delete mode 100644 google/cloud/vision_v1p3beta1/gapic/product_search_client.py delete mode 100644 google/cloud/vision_v1p3beta1/gapic/product_search_client_config.py delete mode 100644 google/cloud/vision_v1p3beta1/gapic/transports/__init__.py delete mode 100644 google/cloud/vision_v1p3beta1/gapic/transports/image_annotator_grpc_transport.py delete mode 100644 google/cloud/vision_v1p3beta1/gapic/transports/product_search_grpc_transport.py delete mode 100644 google/cloud/vision_v1p3beta1/proto/__init__.py delete mode 100644 google/cloud/vision_v1p3beta1/proto/geometry_pb2.py delete mode 100644 google/cloud/vision_v1p3beta1/proto/geometry_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p3beta1/proto/image_annotator_pb2.py delete mode 100644 google/cloud/vision_v1p3beta1/proto/image_annotator_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p3beta1/proto/product_search_pb2.py delete mode 100644 google/cloud/vision_v1p3beta1/proto/product_search_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p3beta1/proto/product_search_service_pb2.py delete mode 100644 google/cloud/vision_v1p3beta1/proto/product_search_service_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p3beta1/proto/text_annotation_pb2.py delete mode 100644 google/cloud/vision_v1p3beta1/proto/text_annotation_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p3beta1/proto/web_detection_pb2.py delete mode 100644 google/cloud/vision_v1p3beta1/proto/web_detection_pb2_grpc.py create mode 100644 google/cloud/vision_v1p3beta1/py.typed create mode 100644 google/cloud/vision_v1p3beta1/services/__init__.py create mode 100644 google/cloud/vision_v1p3beta1/services/image_annotator/__init__.py create mode 100644 google/cloud/vision_v1p3beta1/services/image_annotator/async_client.py create mode 100644 google/cloud/vision_v1p3beta1/services/image_annotator/client.py create mode 100644 google/cloud/vision_v1p3beta1/services/image_annotator/transports/__init__.py create mode 100644 google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py create mode 100644 google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py create mode 100644 google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc_asyncio.py create mode 100644 google/cloud/vision_v1p3beta1/services/product_search/__init__.py create mode 100644 google/cloud/vision_v1p3beta1/services/product_search/async_client.py create mode 100644 google/cloud/vision_v1p3beta1/services/product_search/client.py create mode 100644 google/cloud/vision_v1p3beta1/services/product_search/pagers.py create mode 100644 google/cloud/vision_v1p3beta1/services/product_search/transports/__init__.py create mode 100644 google/cloud/vision_v1p3beta1/services/product_search/transports/base.py create mode 100644 google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py create mode 100644 google/cloud/vision_v1p3beta1/services/product_search/transports/grpc_asyncio.py delete mode 100644 google/cloud/vision_v1p3beta1/types.py create mode 100644 google/cloud/vision_v1p3beta1/types/__init__.py create mode 100644 google/cloud/vision_v1p3beta1/types/geometry.py create mode 100644 google/cloud/vision_v1p3beta1/types/image_annotator.py create mode 100644 google/cloud/vision_v1p3beta1/types/product_search.py create mode 100644 google/cloud/vision_v1p3beta1/types/product_search_service.py create mode 100644 google/cloud/vision_v1p3beta1/types/text_annotation.py create mode 100644 google/cloud/vision_v1p3beta1/types/web_detection.py delete mode 100644 google/cloud/vision_v1p4beta1/gapic/__init__.py delete mode 100644 google/cloud/vision_v1p4beta1/gapic/enums.py delete mode 100644 google/cloud/vision_v1p4beta1/gapic/image_annotator_client.py delete mode 100644 google/cloud/vision_v1p4beta1/gapic/image_annotator_client_config.py delete mode 100644 google/cloud/vision_v1p4beta1/gapic/product_search_client.py delete mode 100644 google/cloud/vision_v1p4beta1/gapic/product_search_client_config.py delete mode 100644 google/cloud/vision_v1p4beta1/gapic/transports/__init__.py delete mode 100644 google/cloud/vision_v1p4beta1/gapic/transports/image_annotator_grpc_transport.py delete mode 100644 google/cloud/vision_v1p4beta1/gapic/transports/product_search_grpc_transport.py delete mode 100644 google/cloud/vision_v1p4beta1/proto/__init__.py delete mode 100644 google/cloud/vision_v1p4beta1/proto/face_pb2.py delete mode 100644 google/cloud/vision_v1p4beta1/proto/face_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p4beta1/proto/geometry_pb2.py delete mode 100644 google/cloud/vision_v1p4beta1/proto/geometry_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p4beta1/proto/image_annotator_pb2.py delete mode 100644 google/cloud/vision_v1p4beta1/proto/image_annotator_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p4beta1/proto/product_search_pb2.py delete mode 100644 google/cloud/vision_v1p4beta1/proto/product_search_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p4beta1/proto/product_search_service_pb2.py delete mode 100644 google/cloud/vision_v1p4beta1/proto/product_search_service_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p4beta1/proto/text_annotation_pb2.py delete mode 100644 google/cloud/vision_v1p4beta1/proto/text_annotation_pb2_grpc.py delete mode 100644 google/cloud/vision_v1p4beta1/proto/web_detection_pb2.py delete mode 100644 google/cloud/vision_v1p4beta1/proto/web_detection_pb2_grpc.py create mode 100644 google/cloud/vision_v1p4beta1/py.typed create mode 100644 google/cloud/vision_v1p4beta1/services/__init__.py create mode 100644 google/cloud/vision_v1p4beta1/services/image_annotator/__init__.py create mode 100644 google/cloud/vision_v1p4beta1/services/image_annotator/async_client.py create mode 100644 google/cloud/vision_v1p4beta1/services/image_annotator/client.py create mode 100644 google/cloud/vision_v1p4beta1/services/image_annotator/transports/__init__.py create mode 100644 google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py create mode 100644 google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py create mode 100644 google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc_asyncio.py create mode 100644 google/cloud/vision_v1p4beta1/services/product_search/__init__.py create mode 100644 google/cloud/vision_v1p4beta1/services/product_search/async_client.py create mode 100644 google/cloud/vision_v1p4beta1/services/product_search/client.py create mode 100644 google/cloud/vision_v1p4beta1/services/product_search/pagers.py create mode 100644 google/cloud/vision_v1p4beta1/services/product_search/transports/__init__.py create mode 100644 google/cloud/vision_v1p4beta1/services/product_search/transports/base.py create mode 100644 google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py create mode 100644 google/cloud/vision_v1p4beta1/services/product_search/transports/grpc_asyncio.py delete mode 100644 google/cloud/vision_v1p4beta1/types.py create mode 100644 google/cloud/vision_v1p4beta1/types/__init__.py create mode 100644 google/cloud/vision_v1p4beta1/types/face.py create mode 100644 google/cloud/vision_v1p4beta1/types/geometry.py create mode 100644 google/cloud/vision_v1p4beta1/types/image_annotator.py create mode 100644 google/cloud/vision_v1p4beta1/types/product_search.py create mode 100644 google/cloud/vision_v1p4beta1/types/product_search_service.py create mode 100644 google/cloud/vision_v1p4beta1/types/text_annotation.py create mode 100644 google/cloud/vision_v1p4beta1/types/web_detection.py create mode 100644 mypy.ini create mode 100644 scripts/fixup_vision_v1_keywords.py create mode 100644 scripts/fixup_vision_v1p1beta1_keywords.py create mode 100644 scripts/fixup_vision_v1p2beta1_keywords.py create mode 100644 scripts/fixup_vision_v1p3beta1_keywords.py create mode 100644 scripts/fixup_vision_v1p4beta1_keywords.py delete mode 100644 tests/unit/gapic/v1/test_image_annotator_client_v1.py delete mode 100644 tests/unit/gapic/v1/test_product_search_client_v1.py delete mode 100644 tests/unit/gapic/v1p1beta1/test_image_annotator_client_v1p1beta1.py delete mode 100644 tests/unit/gapic/v1p2beta1/test_image_annotator_client_v1p2beta1.py delete mode 100644 tests/unit/gapic/v1p3beta1/test_image_annotator_client_v1p3beta1.py delete mode 100644 tests/unit/gapic/v1p3beta1/test_product_search_client_v1p3beta1.py delete mode 100644 tests/unit/gapic/v1p4beta1/test_image_annotator_client_v1p4beta1.py delete mode 100644 tests/unit/gapic/v1p4beta1/test_product_search_client_v1p4beta1.py create mode 100644 tests/unit/gapic/vision_v1/__init__.py create mode 100644 tests/unit/gapic/vision_v1/test_image_annotator.py create mode 100644 tests/unit/gapic/vision_v1/test_product_search.py create mode 100644 tests/unit/gapic/vision_v1p1beta1/__init__.py create mode 100644 tests/unit/gapic/vision_v1p1beta1/test_image_annotator.py create mode 100644 tests/unit/gapic/vision_v1p2beta1/__init__.py create mode 100644 tests/unit/gapic/vision_v1p2beta1/test_image_annotator.py create mode 100644 tests/unit/gapic/vision_v1p3beta1/__init__.py create mode 100644 tests/unit/gapic/vision_v1p3beta1/test_image_annotator.py create mode 100644 tests/unit/gapic/vision_v1p3beta1/test_product_search.py create mode 100644 tests/unit/gapic/vision_v1p4beta1/__init__.py create mode 100644 tests/unit/gapic/vision_v1p4beta1/test_image_annotator.py create mode 100644 tests/unit/gapic/vision_v1p4beta1/test_product_search.py diff --git a/.coveragerc b/.coveragerc index dd39c854..010550c3 100644 --- a/.coveragerc +++ b/.coveragerc @@ -21,15 +21,14 @@ branch = True [report] fail_under = 100 show_missing = True +omit = google/cloud/vision/__init__.py exclude_lines = # Re-enable the standard pragma pragma: NO COVER # Ignore debug-only repr def __repr__ - # Ignore abstract methods - raise NotImplementedError -omit = - */gapic/*.py - */proto/*.py - */core/*.py - */site-packages/*.py \ No newline at end of file + # Ignore pkg_resources exceptions. + # This is added at the module level as a safeguard for if someone + # generates the code and tries to run it without pip installing. This + # makes it virtually impossible to test properly. + except pkg_resources.DistributionNotFound \ No newline at end of file diff --git a/.kokoro/populate-secrets.sh b/.kokoro/populate-secrets.sh new file mode 100755 index 00000000..f5251425 --- /dev/null +++ b/.kokoro/populate-secrets.sh @@ -0,0 +1,43 @@ +#!/bin/bash +# Copyright 2020 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -eo pipefail + +function now { date +"%Y-%m-%d %H:%M:%S" | tr -d '\n' ;} +function msg { println "$*" >&2 ;} +function println { printf '%s\n' "$(now) $*" ;} + + +# Populates requested secrets set in SECRET_MANAGER_KEYS from service account: +# kokoro-trampoline@cloud-devrel-kokoro-resources.iam.gserviceaccount.com +SECRET_LOCATION="${KOKORO_GFILE_DIR}/secret_manager" +msg "Creating folder on disk for secrets: ${SECRET_LOCATION}" +mkdir -p ${SECRET_LOCATION} +for key in $(echo ${SECRET_MANAGER_KEYS} | sed "s/,/ /g") +do + msg "Retrieving secret ${key}" + docker run --entrypoint=gcloud \ + --volume=${KOKORO_GFILE_DIR}:${KOKORO_GFILE_DIR} \ + gcr.io/google.com/cloudsdktool/cloud-sdk \ + secrets versions access latest \ + --project cloud-devrel-kokoro-resources \ + --secret ${key} > \ + "${SECRET_LOCATION}/${key}" + if [[ $? == 0 ]]; then + msg "Secret written to ${SECRET_LOCATION}/${key}" + else + msg "Error retrieving secret ${key}" + fi +done diff --git a/.kokoro/release/common.cfg b/.kokoro/release/common.cfg index dfeb9397..f30aa774 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,42 +23,18 @@ env_vars: { value: "github/python-vision/.kokoro/release.sh" } -# Fetch the token needed for reporting release status to GitHub -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "yoshi-automation-github-key" - } - } -} - -# Fetch PyPI password -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "google_cloud_pypi_password" - } - } -} - -# Fetch magictoken to use with Magic Github Proxy -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "releasetool-magictoken" - } - } +# Fetch PyPI password +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "google_cloud_pypi_password" + } + } } -# Fetch api key to use with Magic Github Proxy -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "magic-github-proxy-api-key" - } - } -} +# Tokens needed to report release status back to GitHub +env_vars: { + key: "SECRET_MANAGER_KEYS" + value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem" +} \ No newline at end of file diff --git a/.kokoro/trampoline.sh b/.kokoro/trampoline.sh index e8c4251f..f39236e9 100755 --- a/.kokoro/trampoline.sh +++ b/.kokoro/trampoline.sh @@ -15,9 +15,14 @@ set -eo pipefail -python3 "${KOKORO_GFILE_DIR}/trampoline_v1.py" || ret_code=$? +# Always run the cleanup script, regardless of the success of bouncing into +# the container. +function cleanup() { + chmod +x ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh + ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh + echo "cleanup"; +} +trap cleanup EXIT -chmod +x ${KOKORO_GFILE_DIR}/trampoline_cleanup.sh -${KOKORO_GFILE_DIR}/trampoline_cleanup.sh || true - -exit ${ret_code} +$(dirname $0)/populate-secrets.sh # Secret Manager secrets. +python3 "${KOKORO_GFILE_DIR}/trampoline_v1.py" \ No newline at end of file diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 2682b821..01292ca5 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -80,25 +80,6 @@ We use `nox `__ to instrument our tests. .. nox: https://pypi.org/project/nox/ -Note on Editable Installs / Develop Mode -======================================== - -- As mentioned previously, using ``setuptools`` in `develop mode`_ - or a ``pip`` `editable install`_ is not possible with this - library. This is because this library uses `namespace packages`_. - For context see `Issue #2316`_ and the relevant `PyPA issue`_. - - Since ``editable`` / ``develop`` mode can't be used, packages - need to be installed directly. Hence your changes to the source - tree don't get incorporated into the **already installed** - package. - -.. _namespace packages: https://www.python.org/dev/peps/pep-0420/ -.. _Issue #2316: https://github.com/GoogleCloudPlatform/google-cloud-python/issues/2316 -.. _PyPA issue: https://github.com/pypa/packaging-problems/issues/12 -.. _develop mode: https://setuptools.readthedocs.io/en/latest/setuptools.html#development-mode -.. _editable install: https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs - ***************************************** I'm getting weird errors... Can you help? ***************************************** diff --git a/README.rst b/README.rst index 1f64c1da..7a0104ba 100644 --- a/README.rst +++ b/README.rst @@ -61,11 +61,13 @@ dependencies. Supported Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^ -Python >= 3.5 +Python >= 3.6 Deprecated Python Versions ^^^^^^^^^^^^^^^^^^^^^^^^^^ -Python == 2.7. Python 2.7 support will be removed on January 1, 2020. +Python == 2.7. + +The last version of this library compatible with Python 2.7 is google-cloud-vision==1.0.0. RaspberryPi ARM devices ^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/UPGRADING.md b/UPGRADING.md new file mode 100644 index 00000000..c630a3b4 --- /dev/null +++ b/UPGRADING.md @@ -0,0 +1,162 @@ +# 2.0.0 Migration Guide + +The 2.0 release of the `google-cloud-vision` client is a significant upgrade based on a [next-gen code generator](https://github.com/googleapis/gapic-generator-python), and includes substantial interface changes. Existing code written for earlier versions of this library will likely require updates to use this version. This document describes the changes that have been made, and what you need to do to update your usage. + +If you experience issues or have questions, please file an [issue](https://github.com/googleapis/python-vision/issues). + +## Supported Python Versions + +> **WARNING**: Breaking change + +The 2.0.0 release requires Python 3.6+. + + +## Method Calls + +> **WARNING**: Breaking change + +Methods expect request objects. We provide a script that will convert most common use cases. + +* Install the library + +```py +python3 -m pip install google-cloud-vision +``` + +* The script `fixup_vision_v1_keywords.py` is shipped with the library. It expects +an input directory (with the code to convert) and an empty destination directory. + +```sh +$ fixup_vision_v1_keywords.py --input-directory .samples/ --output-directory samples/ +``` + +**Before:** +```py +from google.cloud import vision_v1 + +client = vision_v1.ProductSearchClient() + +product_set = client.get_product_set("name") +``` + + +**After:** +```py +from google.cloud import vision_v1 + +client = vision_v1.ProductSearchClient() + +product_set = client.get_product_set(request={"name": "name"}) +``` + +### More Details + +In `google-cloud-vision<2.0.0`, parameters required by the API were positional parameters and optional parameters were keyword parameters. + +**Before:** +```py + def create_product_set( + self, + parent, + product_set, + product_set_id=None, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT, + metadata=None, + ): +``` + +In the 2.0.0 release, all methods have a single positional parameter `request`. Method docstrings indicate whether a parameter is required or optional. + +Some methods have additional keyword only parameters. The available parameters depend on the `google.api.method_signature` annotation specified by the API producer. + + +**After:** +```py + def create_product_set( + self, + request: product_search_service.CreateProductSetRequest = None, + *, + parent: str = None, + product_set: product_search_service.ProductSet = None, + product_set_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: +``` + +> **NOTE:** The `request` parameter and flattened keyword parameters for the API are mutually exclusive. +> Passing both will result in an error. + + +Both of these calls are valid: + +```py +response = client.create_product_set( + request={ + "parent": parent, + "product_set_id": product_set_id, + "product_set": product_set + } +) +``` + +```py +response = client.create_product_set( + parent=parent, + product_set_id=product_set_id, + product_set=product_set +) +``` + +This call is invalid because it mixes `request` with a keyword argument `product_set`. Executing this code +will result in an error. + +```py +response = client.create_product_set( + request={ + "parent": parent, + "product_set_id": product_set_id + }, + product_set=product_set +) +``` + + + +## Enums and Types + + +> **WARNING**: Breaking change + +The submodules `enums` and `types` have been removed. + +**Before:** +```py +from google.cloud import vision_v1 + +likelihood = vision_v1.enums.Likelihood.UNKNOWN +request = vision_v1.types.GetProductSetRequest(name="name") +``` + + +**After:** +```py +from google.cloud import vision_v1 + +likelihood = vision_v1.Likelihood.UNKNOWN +request = vision_v1.GetProductSetRequest(name="name") +``` + +## Location Path Helper Method + +Loation path helper method has been removed. Please construct +the path manually. + +```py +project = "my-project" +location = "location" + +location_path = f"projects/{project}/locations/{location}" +``` \ No newline at end of file diff --git a/docs/UPGRADING.md b/docs/UPGRADING.md new file mode 120000 index 00000000..01097c8c --- /dev/null +++ b/docs/UPGRADING.md @@ -0,0 +1 @@ +../UPGRADING.md \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py index 1d281a4e..44eaa3ec 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -39,6 +39,7 @@ "sphinx.ext.autosummary", "sphinx.ext.intersphinx", "sphinx.ext.coverage", + "sphinx.ext.doctest", "sphinx.ext.napoleon", "sphinx.ext.todo", "sphinx.ext.viewcode", diff --git a/docs/gapic/v1/api.rst b/docs/gapic/v1/api.rst deleted file mode 100644 index 85835a0f..00000000 --- a/docs/gapic/v1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud Vision API -=========================== - -.. automodule:: google.cloud.vision_v1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1/types.rst b/docs/gapic/v1/types.rst deleted file mode 100644 index 9d8a9cce..00000000 --- a/docs/gapic/v1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud Vision API Client -================================= - -.. automodule:: google.cloud.vision_v1.types - :members: \ No newline at end of file diff --git a/docs/gapic/v1p2beta1/api.rst b/docs/gapic/v1p2beta1/api.rst deleted file mode 100644 index 1214abc9..00000000 --- a/docs/gapic/v1p2beta1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Google Cloud Vision API -================================== - -.. automodule:: google.cloud.vision_v1p2beta1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1p2beta1/types.rst b/docs/gapic/v1p2beta1/types.rst deleted file mode 100644 index 5099b68a..00000000 --- a/docs/gapic/v1p2beta1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Google Cloud Vision API Client -======================================== - -.. automodule:: google.cloud.vision_v1p2beta1.types - :members: \ No newline at end of file diff --git a/docs/gapic/v1p3beta1/api.rst b/docs/gapic/v1p3beta1/api.rst deleted file mode 100644 index d04d9d99..00000000 --- a/docs/gapic/v1p3beta1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud Vision API -=========================== - -.. automodule:: google.cloud.vision_v1p3beta1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1p3beta1/types.rst b/docs/gapic/v1p3beta1/types.rst deleted file mode 100644 index 3658d2d4..00000000 --- a/docs/gapic/v1p3beta1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud Vision API Client -================================= - -.. automodule:: google.cloud.vision_v1p3beta1.types - :members: \ No newline at end of file diff --git a/docs/gapic/v1p4beta1/api.rst b/docs/gapic/v1p4beta1/api.rst deleted file mode 100644 index b04fc7ea..00000000 --- a/docs/gapic/v1p4beta1/api.rst +++ /dev/null @@ -1,6 +0,0 @@ -Client for Cloud Vision API -=========================== - -.. automodule:: google.cloud.vision_v1p4beta1 - :members: - :inherited-members: \ No newline at end of file diff --git a/docs/gapic/v1p4beta1/types.rst b/docs/gapic/v1p4beta1/types.rst deleted file mode 100644 index 43f20e9d..00000000 --- a/docs/gapic/v1p4beta1/types.rst +++ /dev/null @@ -1,5 +0,0 @@ -Types for Cloud Vision API Client -================================= - -.. automodule:: google.cloud.vision_v1p4beta1.types - :members: \ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst index 5e21d999..931ad5fb 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -82,10 +82,10 @@ This package includes clients for multiple versions of the Vision API. By default, you will get ``v1``, the latest stable version. .. toctree:: - :maxdepth: 2 + :maxdepth: 2 - gapic/v1/api - gapic/v1/types + vision_v1/services + vision_v1/types A new beta release with additional features over the current stable version, @@ -96,8 +96,8 @@ usual beta admonishment (changes are possible, etc.) applies. .. toctree:: :maxdepth: 2 - gapic/v1p4beta1/api - gapic/v1p4beta1/types + vision_v1p4beta1/services + vision_v1p4beta1/types Previous beta releases ``v1p3beta1`` and ``v1p2beta1`` are provided as well. @@ -106,8 +106,8 @@ An API and type reference is provided for ``v1p3beta1``: .. toctree:: :maxdepth: 2 - gapic/v1p3beta1/api - gapic/v1p3beta1/types + vision_v1p3beta1/services + vision_v1p3beta1/types An API and type reference is provided for ``v1p2beta1``: @@ -115,8 +115,18 @@ An API and type reference is provided for ``v1p2beta1``: .. toctree:: :maxdepth: 2 - gapic/v1p2beta1/api - gapic/v1p2beta1/types + vision_v1p2beta1/services + vision_v1p2beta1/types + +Migration Guide +--------------- + +See the guide below for instructions on migrating to the 2.x release of this library. + +.. toctree:: + :maxdepth: 2 + + UPGRADING Changelog --------- diff --git a/docs/vision_v1/services.rst b/docs/vision_v1/services.rst new file mode 100644 index 00000000..0331ec53 --- /dev/null +++ b/docs/vision_v1/services.rst @@ -0,0 +1,9 @@ +Services for Google Cloud Vision v1 API +======================================= + +.. automodule:: google.cloud.vision_v1.services.image_annotator + :members: + :inherited-members: +.. automodule:: google.cloud.vision_v1.services.product_search + :members: + :inherited-members: diff --git a/docs/vision_v1/types.rst b/docs/vision_v1/types.rst new file mode 100644 index 00000000..8c7b8d86 --- /dev/null +++ b/docs/vision_v1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Vision v1 API +==================================== + +.. automodule:: google.cloud.vision_v1.types + :members: diff --git a/docs/vision_v1p2beta1/services.rst b/docs/vision_v1p2beta1/services.rst new file mode 100644 index 00000000..55dc030c --- /dev/null +++ b/docs/vision_v1p2beta1/services.rst @@ -0,0 +1,6 @@ +Services for Google Cloud Vision v1p2beta1 API +============================================== + +.. automodule:: google.cloud.vision_v1p2beta1.services.image_annotator + :members: + :inherited-members: diff --git a/docs/vision_v1p2beta1/types.rst b/docs/vision_v1p2beta1/types.rst new file mode 100644 index 00000000..cdc363d1 --- /dev/null +++ b/docs/vision_v1p2beta1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Vision v1p2beta1 API +=========================================== + +.. automodule:: google.cloud.vision_v1p2beta1.types + :members: diff --git a/docs/vision_v1p3beta1/services.rst b/docs/vision_v1p3beta1/services.rst new file mode 100644 index 00000000..591da113 --- /dev/null +++ b/docs/vision_v1p3beta1/services.rst @@ -0,0 +1,9 @@ +Services for Google Cloud Vision v1p3beta1 API +============================================== + +.. automodule:: google.cloud.vision_v1p3beta1.services.image_annotator + :members: + :inherited-members: +.. automodule:: google.cloud.vision_v1p3beta1.services.product_search + :members: + :inherited-members: diff --git a/docs/vision_v1p3beta1/types.rst b/docs/vision_v1p3beta1/types.rst new file mode 100644 index 00000000..b5a9253d --- /dev/null +++ b/docs/vision_v1p3beta1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Vision v1p3beta1 API +=========================================== + +.. automodule:: google.cloud.vision_v1p3beta1.types + :members: diff --git a/docs/vision_v1p4beta1/services.rst b/docs/vision_v1p4beta1/services.rst new file mode 100644 index 00000000..e8da2e62 --- /dev/null +++ b/docs/vision_v1p4beta1/services.rst @@ -0,0 +1,9 @@ +Services for Google Cloud Vision v1p4beta1 API +============================================== + +.. automodule:: google.cloud.vision_v1p4beta1.services.image_annotator + :members: + :inherited-members: +.. automodule:: google.cloud.vision_v1p4beta1.services.product_search + :members: + :inherited-members: diff --git a/docs/vision_v1p4beta1/types.rst b/docs/vision_v1p4beta1/types.rst new file mode 100644 index 00000000..1ebaa8bb --- /dev/null +++ b/docs/vision_v1p4beta1/types.rst @@ -0,0 +1,5 @@ +Types for Google Cloud Vision v1p4beta1 API +=========================================== + +.. automodule:: google.cloud.vision_v1p4beta1.types + :members: diff --git a/google/cloud/vision/__init__.py b/google/cloud/vision/__init__.py new file mode 100644 index 00000000..3058f7f6 --- /dev/null +++ b/google/cloud/vision/__init__.py @@ -0,0 +1,222 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.cloud.vision_v1.services.image_annotator.async_client import ( + ImageAnnotatorAsyncClient, +) +from google.cloud.vision_v1 import ImageAnnotatorClient +from google.cloud.vision_v1.services.product_search.async_client import ( + ProductSearchAsyncClient, +) +from google.cloud.vision_v1.services.product_search.client import ProductSearchClient +from google.cloud.vision_v1.types.geometry import BoundingPoly +from google.cloud.vision_v1.types.geometry import NormalizedVertex +from google.cloud.vision_v1.types.geometry import Position +from google.cloud.vision_v1.types.geometry import Vertex +from google.cloud.vision_v1.types.image_annotator import AnnotateFileRequest +from google.cloud.vision_v1.types.image_annotator import AnnotateFileResponse +from google.cloud.vision_v1.types.image_annotator import AnnotateImageRequest +from google.cloud.vision_v1.types.image_annotator import AnnotateImageResponse +from google.cloud.vision_v1.types.image_annotator import AsyncAnnotateFileRequest +from google.cloud.vision_v1.types.image_annotator import AsyncAnnotateFileResponse +from google.cloud.vision_v1.types.image_annotator import AsyncBatchAnnotateFilesRequest +from google.cloud.vision_v1.types.image_annotator import AsyncBatchAnnotateFilesResponse +from google.cloud.vision_v1.types.image_annotator import AsyncBatchAnnotateImagesRequest +from google.cloud.vision_v1.types.image_annotator import ( + AsyncBatchAnnotateImagesResponse, +) +from google.cloud.vision_v1.types.image_annotator import BatchAnnotateFilesRequest +from google.cloud.vision_v1.types.image_annotator import BatchAnnotateFilesResponse +from google.cloud.vision_v1.types.image_annotator import BatchAnnotateImagesRequest +from google.cloud.vision_v1.types.image_annotator import BatchAnnotateImagesResponse +from google.cloud.vision_v1.types.image_annotator import ColorInfo +from google.cloud.vision_v1.types.image_annotator import CropHint +from google.cloud.vision_v1.types.image_annotator import CropHintsAnnotation +from google.cloud.vision_v1.types.image_annotator import CropHintsParams +from google.cloud.vision_v1.types.image_annotator import DominantColorsAnnotation +from google.cloud.vision_v1.types.image_annotator import EntityAnnotation +from google.cloud.vision_v1.types.image_annotator import FaceAnnotation +from google.cloud.vision_v1.types.image_annotator import Feature +from google.cloud.vision_v1.types.image_annotator import GcsDestination +from google.cloud.vision_v1.types.image_annotator import GcsSource +from google.cloud.vision_v1.types.image_annotator import Image +from google.cloud.vision_v1.types.image_annotator import ImageAnnotationContext +from google.cloud.vision_v1.types.image_annotator import ImageContext +from google.cloud.vision_v1.types.image_annotator import ImageProperties +from google.cloud.vision_v1.types.image_annotator import ImageSource +from google.cloud.vision_v1.types.image_annotator import InputConfig +from google.cloud.vision_v1.types.image_annotator import LatLongRect +from google.cloud.vision_v1.types.image_annotator import Likelihood +from google.cloud.vision_v1.types.image_annotator import LocalizedObjectAnnotation +from google.cloud.vision_v1.types.image_annotator import LocationInfo +from google.cloud.vision_v1.types.image_annotator import OperationMetadata +from google.cloud.vision_v1.types.image_annotator import OutputConfig +from google.cloud.vision_v1.types.image_annotator import Property +from google.cloud.vision_v1.types.image_annotator import SafeSearchAnnotation +from google.cloud.vision_v1.types.image_annotator import WebDetectionParams +from google.cloud.vision_v1.types.product_search import ProductSearchParams +from google.cloud.vision_v1.types.product_search import ProductSearchResults +from google.cloud.vision_v1.types.product_search_service import ( + AddProductToProductSetRequest, +) +from google.cloud.vision_v1.types.product_search_service import BatchOperationMetadata +from google.cloud.vision_v1.types.product_search_service import CreateProductRequest +from google.cloud.vision_v1.types.product_search_service import CreateProductSetRequest +from google.cloud.vision_v1.types.product_search_service import ( + CreateReferenceImageRequest, +) +from google.cloud.vision_v1.types.product_search_service import DeleteProductRequest +from google.cloud.vision_v1.types.product_search_service import DeleteProductSetRequest +from google.cloud.vision_v1.types.product_search_service import ( + DeleteReferenceImageRequest, +) +from google.cloud.vision_v1.types.product_search_service import GetProductRequest +from google.cloud.vision_v1.types.product_search_service import GetProductSetRequest +from google.cloud.vision_v1.types.product_search_service import GetReferenceImageRequest +from google.cloud.vision_v1.types.product_search_service import ( + ImportProductSetsGcsSource, +) +from google.cloud.vision_v1.types.product_search_service import ( + ImportProductSetsInputConfig, +) +from google.cloud.vision_v1.types.product_search_service import ImportProductSetsRequest +from google.cloud.vision_v1.types.product_search_service import ( + ImportProductSetsResponse, +) +from google.cloud.vision_v1.types.product_search_service import ListProductSetsRequest +from google.cloud.vision_v1.types.product_search_service import ListProductSetsResponse +from google.cloud.vision_v1.types.product_search_service import ( + ListProductsInProductSetRequest, +) +from google.cloud.vision_v1.types.product_search_service import ( + ListProductsInProductSetResponse, +) +from google.cloud.vision_v1.types.product_search_service import ListProductsRequest +from google.cloud.vision_v1.types.product_search_service import ListProductsResponse +from google.cloud.vision_v1.types.product_search_service import ( + ListReferenceImagesRequest, +) +from google.cloud.vision_v1.types.product_search_service import ( + ListReferenceImagesResponse, +) +from google.cloud.vision_v1.types.product_search_service import Product +from google.cloud.vision_v1.types.product_search_service import ProductSet +from google.cloud.vision_v1.types.product_search_service import ProductSetPurgeConfig +from google.cloud.vision_v1.types.product_search_service import PurgeProductsRequest +from google.cloud.vision_v1.types.product_search_service import ReferenceImage +from google.cloud.vision_v1.types.product_search_service import ( + RemoveProductFromProductSetRequest, +) +from google.cloud.vision_v1.types.product_search_service import UpdateProductRequest +from google.cloud.vision_v1.types.product_search_service import UpdateProductSetRequest +from google.cloud.vision_v1.types.text_annotation import Block +from google.cloud.vision_v1.types.text_annotation import Page +from google.cloud.vision_v1.types.text_annotation import Paragraph +from google.cloud.vision_v1.types.text_annotation import Symbol +from google.cloud.vision_v1.types.text_annotation import TextAnnotation +from google.cloud.vision_v1.types.text_annotation import Word +from google.cloud.vision_v1.types.web_detection import WebDetection + +__all__ = ( + "AddProductToProductSetRequest", + "AnnotateFileRequest", + "AnnotateFileResponse", + "AnnotateImageRequest", + "AnnotateImageResponse", + "AsyncAnnotateFileRequest", + "AsyncAnnotateFileResponse", + "AsyncBatchAnnotateFilesRequest", + "AsyncBatchAnnotateFilesResponse", + "AsyncBatchAnnotateImagesRequest", + "AsyncBatchAnnotateImagesResponse", + "BatchAnnotateFilesRequest", + "BatchAnnotateFilesResponse", + "BatchAnnotateImagesRequest", + "BatchAnnotateImagesResponse", + "BatchOperationMetadata", + "Block", + "BoundingPoly", + "ColorInfo", + "CreateProductRequest", + "CreateProductSetRequest", + "CreateReferenceImageRequest", + "CropHint", + "CropHintsAnnotation", + "CropHintsParams", + "DeleteProductRequest", + "DeleteProductSetRequest", + "DeleteReferenceImageRequest", + "DominantColorsAnnotation", + "EntityAnnotation", + "FaceAnnotation", + "Feature", + "GcsDestination", + "GcsSource", + "GetProductRequest", + "GetProductSetRequest", + "GetReferenceImageRequest", + "Image", + "ImageAnnotationContext", + "ImageAnnotatorAsyncClient", + "ImageAnnotatorClient", + "ImageContext", + "ImageProperties", + "ImageSource", + "ImportProductSetsGcsSource", + "ImportProductSetsInputConfig", + "ImportProductSetsRequest", + "ImportProductSetsResponse", + "InputConfig", + "LatLongRect", + "Likelihood", + "ListProductSetsRequest", + "ListProductSetsResponse", + "ListProductsInProductSetRequest", + "ListProductsInProductSetResponse", + "ListProductsRequest", + "ListProductsResponse", + "ListReferenceImagesRequest", + "ListReferenceImagesResponse", + "LocalizedObjectAnnotation", + "LocationInfo", + "NormalizedVertex", + "OperationMetadata", + "OutputConfig", + "Page", + "Paragraph", + "Position", + "Product", + "ProductSearchAsyncClient", + "ProductSearchClient", + "ProductSearchParams", + "ProductSearchResults", + "ProductSet", + "ProductSetPurgeConfig", + "Property", + "PurgeProductsRequest", + "ReferenceImage", + "RemoveProductFromProductSetRequest", + "SafeSearchAnnotation", + "Symbol", + "TextAnnotation", + "UpdateProductRequest", + "UpdateProductSetRequest", + "Vertex", + "WebDetection", + "WebDetectionParams", + "Word", +) diff --git a/google/cloud/vision/py.typed b/google/cloud/vision/py.typed new file mode 100644 index 00000000..8cb07491 --- /dev/null +++ b/google/cloud/vision/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-vision package uses inline types. diff --git a/google/cloud/vision_helpers/__init__.py b/google/cloud/vision_helpers/__init__.py index b8916647..7733c6df 100644 --- a/google/cloud/vision_helpers/__init__.py +++ b/google/cloud/vision_helpers/__init__.py @@ -13,7 +13,7 @@ # limitations under the License. from __future__ import absolute_import -import io +import proto from google.api_core import protobuf_helpers as protobuf @@ -26,7 +26,7 @@ class VisionHelpers(object): See the :class:`~google.cloud.vision_v1.ImageAnnotatorClient`. """ - def annotate_image(self, request, retry=None, timeout=None): + def annotate_image(self, request, *, retry=None, timeout=None, metadata=()): """Run image detection and annotation for an image. Example: @@ -40,36 +40,42 @@ def annotate_image(self, request, retry=None, timeout=None): >>> response = client.annotate_image(request) Args: - request (:class:`~.vision_v1.types.AnnotateImageRequest`) - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will not - be retried. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. + request (:class:`~.vision_v1.AnnotateImageRequest`) + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. Returns: - :class:`~.vision_v1.types.AnnotateImageResponse` The API response. + :class:`~.vision_v1.AnnotateImageResponse` The API response. """ - # If the image is a file handler, set the content. - image = protobuf.get(request, "image") - if hasattr(image, "read"): - img_bytes = image.read() - protobuf.set(request, "image", {}) - protobuf.set(request, "image.content", img_bytes) + if not isinstance(request, proto.Message): + # If the image is a file handler, set the content. image = protobuf.get(request, "image") + if not isinstance(image, proto.Message): + if hasattr(image, "read"): + img_bytes = image.read() + protobuf.set(request, "image", {}) + protobuf.set(request, "image.content", img_bytes) + image = protobuf.get(request, "image") - # If a filename is provided, read the file. - filename = protobuf.get(image, "source.filename", default=None) - if filename: - with io.open(filename, "rb") as img_file: - protobuf.set(request, "image.content", img_file.read()) - protobuf.set(request, "image.source", None) + # If a filename is provided, read the file. + filename = protobuf.get(image, "source.filename", default=None) + if filename: + with open(filename, "rb") as img_file: + protobuf.set(request, "image.content", img_file.read()) + protobuf.set(request, "image.source", None) # This method allows features not to be specified, and you get all # of them. - protobuf.setdefault(request, "features", self._get_all_features()) - r = self.batch_annotate_images([request], retry=retry, timeout=timeout) + if not isinstance(request, proto.Message): + protobuf.setdefault(request, "features", self._get_all_features()) + elif len(request.features) == 0: + request.features = self._get_all_features() + r = self.batch_annotate_images( + requests=[request], retry=retry, timeout=timeout, metadata=metadata + ) return r.responses[0] def _get_all_features(self): @@ -78,6 +84,4 @@ def _get_all_features(self): Returns: list: A list of all available features. """ - return [ - {"type": feature} for feature in self.enums.Feature.Type if feature != 0 - ] + return [{"type_": feature} for feature in self.Feature.Type if feature != 0] diff --git a/google/cloud/vision_helpers/decorators.py b/google/cloud/vision_helpers/decorators.py index 804a171c..7c00e921 100644 --- a/google/cloud/vision_helpers/decorators.py +++ b/google/cloud/vision_helpers/decorators.py @@ -22,12 +22,12 @@ def add_single_feature_methods(cls): defined on the Feature enum. """ # Sanity check: This only makes sense if we are building the GAPIC - # subclass and have enums already attached. - if not hasattr(cls, "enums"): + # subclass and have Feature enums already attached. + if not hasattr(cls, "Feature"): return cls # Add each single-feature method to the class. - for feature in cls.enums.Feature.Type: + for feature in cls.Feature.Type: # Sanity check: Do not make a method for the falsy feature. if feature.name == "TYPE_UNSPECIFIED": continue @@ -54,7 +54,7 @@ def _create_single_feature_method(feature): Args: feature (enum): A specific feature defined as a member of - :class:`~enums.Feature.Type`. + :class:`~Feature.Type`. Returns: function: A helper function to detect just that feature. @@ -71,24 +71,35 @@ def _create_single_feature_method(feature): fx_doc += """ Args: - image (:class:`~.{module}.types.Image`): The image to analyze. + image (:class:`~.{module}.Image`): The image to analyze. max_results (int): Number of results to return, does not apply for TEXT_DETECTION, DOCUMENT_TEXT_DETECTION, or CROP_HINTS. retry (int): Number of retries to do before giving up. timeout (int): Number of seconds before timing out. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. kwargs (dict): Additional properties to be set on the :class:`~.{module}.types.AnnotateImageRequest`. Returns: - :class:`~.{module}.types.AnnotateImageResponse`: The API response. + :class:`~.{module}.AnnotateImageResponse`: The API response. """ # Get the actual feature value to send. - feature_value = {"type": feature} + feature_value = {"type_": feature} # Define the function to be returned. - def inner(self, image, max_results=None, retry=None, timeout=None, **kwargs): + def inner( + self, + image, + *, + max_results=None, + retry=None, + timeout=None, + metadata=(), + **kwargs + ): """Return a single feature annotation for the given image. Intended for use with functools.partial, to create the particular @@ -98,7 +109,9 @@ def inner(self, image, max_results=None, retry=None, timeout=None, **kwargs): if max_results is not None: copied_features["max_results"] = max_results request = dict(image=image, features=[copied_features], **kwargs) - response = self.annotate_image(request, retry=retry, timeout=timeout) + response = self.annotate_image( + request, retry=retry, timeout=timeout, metadata=metadata + ) return response # Set the appropriate function metadata. diff --git a/google/cloud/vision_v1/__init__.py b/google/cloud/vision_v1/__init__.py index 7714adb4..fb4ce6e2 100644 --- a/google/cloud/vision_v1/__init__.py +++ b/google/cloud/vision_v1/__init__.py @@ -1,56 +1,200 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - - -from __future__ import absolute_import +# from google.cloud.vision_helpers.decorators import add_single_feature_methods from google.cloud.vision_helpers import VisionHelpers -import sys -import warnings - -from google.cloud.vision_v1 import types -from google.cloud.vision_v1.gapic import enums -from google.cloud.vision_v1.gapic import image_annotator_client as iac -from google.cloud.vision_v1.gapic import product_search_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - -class ProductSearchClient(product_search_client.ProductSearchClient): - __doc__ = product_search_client.ProductSearchClient.__doc__ - enums = enums +from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient +from .services.product_search import ProductSearchClient +from .types.geometry import BoundingPoly +from .types.geometry import NormalizedVertex +from .types.geometry import Position +from .types.geometry import Vertex +from .types.image_annotator import AnnotateFileRequest +from .types.image_annotator import AnnotateFileResponse +from .types.image_annotator import AnnotateImageRequest +from .types.image_annotator import AnnotateImageResponse +from .types.image_annotator import AsyncAnnotateFileRequest +from .types.image_annotator import AsyncAnnotateFileResponse +from .types.image_annotator import AsyncBatchAnnotateFilesRequest +from .types.image_annotator import AsyncBatchAnnotateFilesResponse +from .types.image_annotator import AsyncBatchAnnotateImagesRequest +from .types.image_annotator import AsyncBatchAnnotateImagesResponse +from .types.image_annotator import BatchAnnotateFilesRequest +from .types.image_annotator import BatchAnnotateFilesResponse +from .types.image_annotator import BatchAnnotateImagesRequest +from .types.image_annotator import BatchAnnotateImagesResponse +from .types.image_annotator import ColorInfo +from .types.image_annotator import CropHint +from .types.image_annotator import CropHintsAnnotation +from .types.image_annotator import CropHintsParams +from .types.image_annotator import DominantColorsAnnotation +from .types.image_annotator import EntityAnnotation +from .types.image_annotator import FaceAnnotation +from .types.image_annotator import Feature +from .types.image_annotator import GcsDestination +from .types.image_annotator import GcsSource +from .types.image_annotator import Image +from .types.image_annotator import ImageAnnotationContext +from .types.image_annotator import ImageContext +from .types.image_annotator import ImageProperties +from .types.image_annotator import ImageSource +from .types.image_annotator import InputConfig +from .types.image_annotator import LatLongRect +from .types.image_annotator import Likelihood +from .types.image_annotator import LocalizedObjectAnnotation +from .types.image_annotator import LocationInfo +from .types.image_annotator import OperationMetadata +from .types.image_annotator import OutputConfig +from .types.image_annotator import Property +from .types.image_annotator import SafeSearchAnnotation +from .types.image_annotator import WebDetectionParams +from .types.product_search import ProductSearchParams +from .types.product_search import ProductSearchResults +from .types.product_search_service import AddProductToProductSetRequest +from .types.product_search_service import BatchOperationMetadata +from .types.product_search_service import CreateProductRequest +from .types.product_search_service import CreateProductSetRequest +from .types.product_search_service import CreateReferenceImageRequest +from .types.product_search_service import DeleteProductRequest +from .types.product_search_service import DeleteProductSetRequest +from .types.product_search_service import DeleteReferenceImageRequest +from .types.product_search_service import GetProductRequest +from .types.product_search_service import GetProductSetRequest +from .types.product_search_service import GetReferenceImageRequest +from .types.product_search_service import ImportProductSetsGcsSource +from .types.product_search_service import ImportProductSetsInputConfig +from .types.product_search_service import ImportProductSetsRequest +from .types.product_search_service import ImportProductSetsResponse +from .types.product_search_service import ListProductSetsRequest +from .types.product_search_service import ListProductSetsResponse +from .types.product_search_service import ListProductsInProductSetRequest +from .types.product_search_service import ListProductsInProductSetResponse +from .types.product_search_service import ListProductsRequest +from .types.product_search_service import ListProductsResponse +from .types.product_search_service import ListReferenceImagesRequest +from .types.product_search_service import ListReferenceImagesResponse +from .types.product_search_service import Product +from .types.product_search_service import ProductSet +from .types.product_search_service import ProductSetPurgeConfig +from .types.product_search_service import PurgeProductsRequest +from .types.product_search_service import ReferenceImage +from .types.product_search_service import RemoveProductFromProductSetRequest +from .types.product_search_service import UpdateProductRequest +from .types.product_search_service import UpdateProductSetRequest +from .types.text_annotation import Block +from .types.text_annotation import Page +from .types.text_annotation import Paragraph +from .types.text_annotation import Symbol +from .types.text_annotation import TextAnnotation +from .types.text_annotation import Word +from .types.web_detection import WebDetection @add_single_feature_methods -class ImageAnnotatorClient(VisionHelpers, iac.ImageAnnotatorClient): - __doc__ = iac.ImageAnnotatorClient.__doc__ - enums = enums +class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): + __doc__ = IacImageAnnotatorClient.__doc__ + Feature = Feature __all__ = ( - "enums", - "types", + "AddProductToProductSetRequest", + "AnnotateFileRequest", + "AnnotateFileResponse", + "AnnotateImageRequest", + "AnnotateImageResponse", + "AsyncAnnotateFileRequest", + "AsyncAnnotateFileResponse", + "AsyncBatchAnnotateFilesRequest", + "AsyncBatchAnnotateFilesResponse", + "AsyncBatchAnnotateImagesRequest", + "AsyncBatchAnnotateImagesResponse", + "BatchAnnotateFilesRequest", + "BatchAnnotateFilesResponse", + "BatchAnnotateImagesRequest", + "BatchAnnotateImagesResponse", + "BatchOperationMetadata", + "Block", + "BoundingPoly", + "ColorInfo", + "CreateProductRequest", + "CreateProductSetRequest", + "CreateReferenceImageRequest", + "CropHint", + "CropHintsAnnotation", + "CropHintsParams", + "DeleteProductRequest", + "DeleteProductSetRequest", + "DeleteReferenceImageRequest", + "DominantColorsAnnotation", + "EntityAnnotation", + "FaceAnnotation", + "Feature", + "GcsDestination", + "GcsSource", + "GetProductRequest", + "GetProductSetRequest", + "GetReferenceImageRequest", + "Image", + "ImageAnnotationContext", + "ImageContext", + "ImageProperties", + "ImageSource", + "ImportProductSetsGcsSource", + "ImportProductSetsInputConfig", + "ImportProductSetsRequest", + "ImportProductSetsResponse", + "InputConfig", + "LatLongRect", + "Likelihood", + "ListProductSetsRequest", + "ListProductSetsResponse", + "ListProductsInProductSetRequest", + "ListProductsInProductSetResponse", + "ListProductsRequest", + "ListProductsResponse", + "ListReferenceImagesRequest", + "ListReferenceImagesResponse", + "LocalizedObjectAnnotation", + "LocationInfo", + "NormalizedVertex", + "OperationMetadata", + "OutputConfig", + "Page", + "Paragraph", + "Position", + "Product", "ProductSearchClient", + "ProductSearchParams", + "ProductSearchResults", + "ProductSet", + "ProductSetPurgeConfig", + "Property", + "PurgeProductsRequest", + "ReferenceImage", + "RemoveProductFromProductSetRequest", + "SafeSearchAnnotation", + "Symbol", + "TextAnnotation", + "UpdateProductRequest", + "UpdateProductSetRequest", + "Vertex", + "WebDetection", + "WebDetectionParams", + "Word", "ImageAnnotatorClient", ) diff --git a/google/cloud/vision_v1/gapic/__init__.py b/google/cloud/vision_v1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/vision_v1/gapic/enums.py b/google/cloud/vision_v1/gapic/enums.py deleted file mode 100644 index 911d2e7c..00000000 --- a/google/cloud/vision_v1/gapic/enums.py +++ /dev/null @@ -1,255 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class Likelihood(enum.IntEnum): - """ - A bucketized representation of likelihood, which is intended to give clients - highly stable results across model upgrades. - - Attributes: - UNKNOWN (int): Unknown likelihood. - VERY_UNLIKELY (int): It is very unlikely. - UNLIKELY (int): It is unlikely. - POSSIBLE (int): It is possible. - LIKELY (int): It is likely. - VERY_LIKELY (int): It is very likely. - """ - - UNKNOWN = 0 - VERY_UNLIKELY = 1 - UNLIKELY = 2 - POSSIBLE = 3 - LIKELY = 4 - VERY_LIKELY = 5 - - -class BatchOperationMetadata(object): - class State(enum.IntEnum): - """ - Enumerates the possible states that the batch request can be in. - - Attributes: - STATE_UNSPECIFIED (int): Invalid. - PROCESSING (int): Request is actively being processed. - SUCCESSFUL (int): The request is done and at least one item has been successfully - processed. - FAILED (int): The request is done and no item has been successfully processed. - CANCELLED (int): The request is done after the longrunning.Operations.CancelOperation has - been called by the user. Any records that were processed before the - cancel command are output as specified in the request. - """ - - STATE_UNSPECIFIED = 0 - PROCESSING = 1 - SUCCESSFUL = 2 - FAILED = 3 - CANCELLED = 4 - - -class Block(object): - class BlockType(enum.IntEnum): - """ - Type of a block (text, image etc) as identified by OCR. - - Attributes: - UNKNOWN (int): Unknown block type. - TEXT (int): Regular text block. - TABLE (int): Table block. - PICTURE (int): Image block. - RULER (int): Horizontal/vertical line box. - BARCODE (int): Barcode block. - """ - - UNKNOWN = 0 - TEXT = 1 - TABLE = 2 - PICTURE = 3 - RULER = 4 - BARCODE = 5 - - -class FaceAnnotation(object): - class Landmark(object): - class Type(enum.IntEnum): - """ - Face landmark (feature) type. Left and right are defined from the - vantage of the viewer of the image without considering mirror - projections typical of photos. So, ``LEFT_EYE``, typically, is the - person's right eye. - - Attributes: - UNKNOWN_LANDMARK (int): Unknown face landmark detected. Should not be filled. - LEFT_EYE (int): Left eye. - RIGHT_EYE (int): Right eye. - LEFT_OF_LEFT_EYEBROW (int): Left of left eyebrow. - RIGHT_OF_LEFT_EYEBROW (int): Right of left eyebrow. - LEFT_OF_RIGHT_EYEBROW (int): Left of right eyebrow. - RIGHT_OF_RIGHT_EYEBROW (int): Right of right eyebrow. - MIDPOINT_BETWEEN_EYES (int): Midpoint between eyes. - NOSE_TIP (int): Nose tip. - UPPER_LIP (int): Upper lip. - LOWER_LIP (int): Lower lip. - MOUTH_LEFT (int): Mouth left. - MOUTH_RIGHT (int): Mouth right. - MOUTH_CENTER (int): Mouth center. - NOSE_BOTTOM_RIGHT (int): Nose, bottom right. - NOSE_BOTTOM_LEFT (int): Nose, bottom left. - NOSE_BOTTOM_CENTER (int): Nose, bottom center. - LEFT_EYE_TOP_BOUNDARY (int): Left eye, top boundary. - LEFT_EYE_RIGHT_CORNER (int): Left eye, right corner. - LEFT_EYE_BOTTOM_BOUNDARY (int): Left eye, bottom boundary. - LEFT_EYE_LEFT_CORNER (int): Left eye, left corner. - RIGHT_EYE_TOP_BOUNDARY (int): Right eye, top boundary. - RIGHT_EYE_RIGHT_CORNER (int): Right eye, right corner. - RIGHT_EYE_BOTTOM_BOUNDARY (int): Right eye, bottom boundary. - RIGHT_EYE_LEFT_CORNER (int): Right eye, left corner. - LEFT_EYEBROW_UPPER_MIDPOINT (int): Left eyebrow, upper midpoint. - RIGHT_EYEBROW_UPPER_MIDPOINT (int): Right eyebrow, upper midpoint. - LEFT_EAR_TRAGION (int): Left ear tragion. - RIGHT_EAR_TRAGION (int): Right ear tragion. - LEFT_EYE_PUPIL (int): Left eye pupil. - RIGHT_EYE_PUPIL (int): Right eye pupil. - FOREHEAD_GLABELLA (int): Forehead glabella. - CHIN_GNATHION (int): Chin gnathion. - CHIN_LEFT_GONION (int): Chin left gonion. - CHIN_RIGHT_GONION (int): Chin right gonion. - """ - - UNKNOWN_LANDMARK = 0 - LEFT_EYE = 1 - RIGHT_EYE = 2 - LEFT_OF_LEFT_EYEBROW = 3 - RIGHT_OF_LEFT_EYEBROW = 4 - LEFT_OF_RIGHT_EYEBROW = 5 - RIGHT_OF_RIGHT_EYEBROW = 6 - MIDPOINT_BETWEEN_EYES = 7 - NOSE_TIP = 8 - UPPER_LIP = 9 - LOWER_LIP = 10 - MOUTH_LEFT = 11 - MOUTH_RIGHT = 12 - MOUTH_CENTER = 13 - NOSE_BOTTOM_RIGHT = 14 - NOSE_BOTTOM_LEFT = 15 - NOSE_BOTTOM_CENTER = 16 - LEFT_EYE_TOP_BOUNDARY = 17 - LEFT_EYE_RIGHT_CORNER = 18 - LEFT_EYE_BOTTOM_BOUNDARY = 19 - LEFT_EYE_LEFT_CORNER = 20 - RIGHT_EYE_TOP_BOUNDARY = 21 - RIGHT_EYE_RIGHT_CORNER = 22 - RIGHT_EYE_BOTTOM_BOUNDARY = 23 - RIGHT_EYE_LEFT_CORNER = 24 - LEFT_EYEBROW_UPPER_MIDPOINT = 25 - RIGHT_EYEBROW_UPPER_MIDPOINT = 26 - LEFT_EAR_TRAGION = 27 - RIGHT_EAR_TRAGION = 28 - LEFT_EYE_PUPIL = 29 - RIGHT_EYE_PUPIL = 30 - FOREHEAD_GLABELLA = 31 - CHIN_GNATHION = 32 - CHIN_LEFT_GONION = 33 - CHIN_RIGHT_GONION = 34 - - -class Feature(object): - class Type(enum.IntEnum): - """ - Type of Google Cloud Vision API feature to be extracted. - - Attributes: - TYPE_UNSPECIFIED (int): Unspecified feature type. - FACE_DETECTION (int): Run face detection. - LANDMARK_DETECTION (int): Run landmark detection. - LOGO_DETECTION (int): Run logo detection. - LABEL_DETECTION (int): Run label detection. - TEXT_DETECTION (int): Run text detection / optical character recognition (OCR). Text - detection is optimized for areas of text within a larger image; if the - image is a document, use ``DOCUMENT_TEXT_DETECTION`` instead. - DOCUMENT_TEXT_DETECTION (int): Run dense text document OCR. Takes precedence when both - ``DOCUMENT_TEXT_DETECTION`` and ``TEXT_DETECTION`` are present. - SAFE_SEARCH_DETECTION (int): Run Safe Search to detect potentially unsafe - or undesirable content. - IMAGE_PROPERTIES (int): Compute a set of image properties, such as the - image's dominant colors. - CROP_HINTS (int): Run crop hints. - WEB_DETECTION (int): Run web detection. - PRODUCT_SEARCH (int): Run Product Search. - OBJECT_LOCALIZATION (int): Run localizer for object detection. - """ - - TYPE_UNSPECIFIED = 0 - FACE_DETECTION = 1 - LANDMARK_DETECTION = 2 - LOGO_DETECTION = 3 - LABEL_DETECTION = 4 - TEXT_DETECTION = 5 - DOCUMENT_TEXT_DETECTION = 11 - SAFE_SEARCH_DETECTION = 6 - IMAGE_PROPERTIES = 7 - CROP_HINTS = 9 - WEB_DETECTION = 10 - PRODUCT_SEARCH = 12 - OBJECT_LOCALIZATION = 19 - - -class OperationMetadata(object): - class State(enum.IntEnum): - """ - Batch operation states. - - Attributes: - STATE_UNSPECIFIED (int): Invalid. - CREATED (int): Request is received. - RUNNING (int): Request is actively being processed. - DONE (int): The batch processing is done. - CANCELLED (int): The batch processing was cancelled. - """ - - STATE_UNSPECIFIED = 0 - CREATED = 1 - RUNNING = 2 - DONE = 3 - CANCELLED = 4 - - -class TextAnnotation(object): - class DetectedBreak(object): - class BreakType(enum.IntEnum): - """ - Enum to denote the type of break found. New line, space etc. - - Attributes: - UNKNOWN (int): Unknown break label type. - SPACE (int): Regular space. - SURE_SPACE (int): Sure space (very wide). - EOL_SURE_SPACE (int): Line-wrapping break. - HYPHEN (int): End-line hyphen that is not present in text; does not co-occur with - ``SPACE``, ``LEADER_SPACE``, or ``LINE_BREAK``. - LINE_BREAK (int): Line break that ends a paragraph. - """ - - UNKNOWN = 0 - SPACE = 1 - SURE_SPACE = 2 - EOL_SURE_SPACE = 3 - HYPHEN = 4 - LINE_BREAK = 5 diff --git a/google/cloud/vision_v1/gapic/image_annotator_client.py b/google/cloud/vision_v1/gapic/image_annotator_client.py deleted file mode 100644 index d56c69f2..00000000 --- a/google/cloud/vision_v1/gapic/image_annotator_client.py +++ /dev/null @@ -1,599 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.vision.v1 ImageAnnotator API.""" - -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.operation -from google.api_core import operations_v1 -import grpc - -from google.cloud.vision_v1.gapic import enums -from google.cloud.vision_v1.gapic import image_annotator_client_config -from google.cloud.vision_v1.gapic.transports import image_annotator_grpc_transport -from google.cloud.vision_v1.proto import image_annotator_pb2 -from google.cloud.vision_v1.proto import image_annotator_pb2_grpc -from google.cloud.vision_v1.proto import product_search_service_pb2 -from google.cloud.vision_v1.proto import product_search_service_pb2_grpc -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-vision",).version - - -class ImageAnnotatorClient(object): - """ - Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - SERVICE_ADDRESS = "vision.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.vision.v1.ImageAnnotator" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ImageAnnotatorClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.ImageAnnotatorGrpcTransport, - Callable[[~.Credentials, type], ~.ImageAnnotatorGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = image_annotator_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=image_annotator_grpc_transport.ImageAnnotatorGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = image_annotator_grpc_transport.ImageAnnotatorGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def batch_annotate_files( - self, - requests, - parent=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Service that performs image detection and annotation for a batch of files. - Now only "application/pdf", "image/tiff" and "image/gif" are supported. - - This service will extract at most 5 (customers can specify which 5 in - AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each - file provided and perform detection and annotation for each image - extracted. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ImageAnnotatorClient() - >>> - >>> # TODO: Initialize `requests`: - >>> requests = [] - >>> - >>> response = client.batch_annotate_files(requests) - - Args: - requests (list[Union[dict, ~google.cloud.vision_v1.types.AnnotateFileRequest]]): Required. The list of file annotation requests. Right now we support only one - AnnotateFileRequest in BatchAnnotateFilesRequest. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1.types.AnnotateFileRequest` - parent (str): Optional. Target project and location to make a call. - - Format: ``projects/{project-id}/locations/{location-id}``. - - If no parent is specified, a region will be chosen automatically. - - Supported location-ids: ``us``: USA country only, ``asia``: East asia - areas, like Japan, Taiwan, ``eu``: The European Union. - - Example: ``projects/project-A/locations/eu``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1.types.BatchAnnotateFilesResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "batch_annotate_files" not in self._inner_api_calls: - self._inner_api_calls[ - "batch_annotate_files" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.batch_annotate_files, - default_retry=self._method_configs["BatchAnnotateFiles"].retry, - default_timeout=self._method_configs["BatchAnnotateFiles"].timeout, - client_info=self._client_info, - ) - - request = image_annotator_pb2.BatchAnnotateFilesRequest( - requests=requests, parent=parent, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["batch_annotate_files"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def async_batch_annotate_images( - self, - requests, - output_config, - parent=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Run asynchronous image detection and annotation for a list of - images. - - Progress and results can be retrieved through the - ``google.longrunning.Operations`` interface. ``Operation.metadata`` - contains ``OperationMetadata`` (metadata). ``Operation.response`` - contains ``AsyncBatchAnnotateImagesResponse`` (results). - - This service will write image annotation outputs to json files in - customer GCS bucket, each json file containing - BatchAnnotateImagesResponse proto. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ImageAnnotatorClient() - >>> - >>> # TODO: Initialize `requests`: - >>> requests = [] - >>> - >>> # TODO: Initialize `output_config`: - >>> output_config = {} - >>> - >>> response = client.async_batch_annotate_images(requests, output_config) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - requests (list[Union[dict, ~google.cloud.vision_v1.types.AnnotateImageRequest]]): Required. Individual image annotation requests for this batch. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1.types.AnnotateImageRequest` - output_config (Union[dict, ~google.cloud.vision_v1.types.OutputConfig]): Required. The desired output location and metadata (e.g. format). - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1.types.OutputConfig` - parent (str): Optional. Target project and location to make a call. - - Format: ``projects/{project-id}/locations/{location-id}``. - - If no parent is specified, a region will be chosen automatically. - - Supported location-ids: ``us``: USA country only, ``asia``: East asia - areas, like Japan, Taiwan, ``eu``: The European Union. - - Example: ``projects/project-A/locations/eu``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "async_batch_annotate_images" not in self._inner_api_calls: - self._inner_api_calls[ - "async_batch_annotate_images" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.async_batch_annotate_images, - default_retry=self._method_configs["AsyncBatchAnnotateImages"].retry, - default_timeout=self._method_configs[ - "AsyncBatchAnnotateImages" - ].timeout, - client_info=self._client_info, - ) - - request = image_annotator_pb2.AsyncBatchAnnotateImagesRequest( - requests=requests, output_config=output_config, parent=parent, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["async_batch_annotate_images"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - image_annotator_pb2.AsyncBatchAnnotateImagesResponse, - metadata_type=image_annotator_pb2.OperationMetadata, - ) - - def async_batch_annotate_files( - self, - requests, - parent=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Run asynchronous image detection and annotation for a list of - generic files, such as PDF files, which may contain multiple pages and - multiple images per page. Progress and results can be retrieved through - the ``google.longrunning.Operations`` interface. ``Operation.metadata`` - contains ``OperationMetadata`` (metadata). ``Operation.response`` - contains ``AsyncBatchAnnotateFilesResponse`` (results). - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ImageAnnotatorClient() - >>> - >>> # TODO: Initialize `requests`: - >>> requests = [] - >>> - >>> response = client.async_batch_annotate_files(requests) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - requests (list[Union[dict, ~google.cloud.vision_v1.types.AsyncAnnotateFileRequest]]): Required. Individual async file annotation requests for this batch. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1.types.AsyncAnnotateFileRequest` - parent (str): Optional. Target project and location to make a call. - - Format: ``projects/{project-id}/locations/{location-id}``. - - If no parent is specified, a region will be chosen automatically. - - Supported location-ids: ``us``: USA country only, ``asia``: East asia - areas, like Japan, Taiwan, ``eu``: The European Union. - - Example: ``projects/project-A/locations/eu``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "async_batch_annotate_files" not in self._inner_api_calls: - self._inner_api_calls[ - "async_batch_annotate_files" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.async_batch_annotate_files, - default_retry=self._method_configs["AsyncBatchAnnotateFiles"].retry, - default_timeout=self._method_configs["AsyncBatchAnnotateFiles"].timeout, - client_info=self._client_info, - ) - - request = image_annotator_pb2.AsyncBatchAnnotateFilesRequest( - requests=requests, parent=parent, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["async_batch_annotate_files"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - image_annotator_pb2.AsyncBatchAnnotateFilesResponse, - metadata_type=image_annotator_pb2.OperationMetadata, - ) - - def batch_annotate_images( - self, - requests, - parent=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Run image detection and annotation for a batch of images. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ImageAnnotatorClient() - >>> - >>> # TODO: Initialize `requests`: - >>> requests = [] - >>> - >>> response = client.batch_annotate_images(requests) - - Args: - requests (list[Union[dict, ~google.cloud.vision_v1.types.AnnotateImageRequest]]): Required. Individual image annotation requests for this batch. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1.types.AnnotateImageRequest` - parent (str): Optional. Target project and location to make a call. - - Format: ``projects/{project-id}/locations/{location-id}``. - - If no parent is specified, a region will be chosen automatically. - - Supported location-ids: ``us``: USA country only, ``asia``: East asia - areas, like Japan, Taiwan, ``eu``: The European Union. - - Example: ``projects/project-A/locations/eu``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1.types.BatchAnnotateImagesResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "batch_annotate_images" not in self._inner_api_calls: - self._inner_api_calls[ - "batch_annotate_images" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.batch_annotate_images, - default_retry=self._method_configs["BatchAnnotateImages"].retry, - default_timeout=self._method_configs["BatchAnnotateImages"].timeout, - client_info=self._client_info, - ) - - request = image_annotator_pb2.BatchAnnotateImagesRequest( - requests=requests, parent=parent, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["batch_annotate_images"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/vision_v1/gapic/image_annotator_client_config.py b/google/cloud/vision_v1/gapic/image_annotator_client_config.py deleted file mode 100644 index d1b1f9e5..00000000 --- a/google/cloud/vision_v1/gapic/image_annotator_client_config.py +++ /dev/null @@ -1,52 +0,0 @@ -config = { - "interfaces": { - "google.cloud.vision.v1.ImageAnnotator": { - "retry_codes": { - "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 600000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 600000, - "total_timeout_millis": 600000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - }, - "methods": { - "BatchAnnotateFiles": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "AsyncBatchAnnotateImages": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "AsyncBatchAnnotateFiles": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "BatchAnnotateImages": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - }, - } - } -} diff --git a/google/cloud/vision_v1/gapic/product_search_client.py b/google/cloud/vision_v1/gapic/product_search_client.py deleted file mode 100644 index 123d2949..00000000 --- a/google/cloud/vision_v1/gapic/product_search_client.py +++ /dev/null @@ -1,2026 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.vision.v1 ProductSearch API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.operation -from google.api_core import operations_v1 -import google.api_core.page_iterator -import google.api_core.path_template -import google.api_core.protobuf_helpers -import grpc - -from google.cloud.vision_v1.gapic import enums -from google.cloud.vision_v1.gapic import product_search_client_config -from google.cloud.vision_v1.gapic.transports import product_search_grpc_transport -from google.cloud.vision_v1.proto import product_search_service_pb2 -from google.cloud.vision_v1.proto import product_search_service_pb2_grpc -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-vision",).version - - -class ProductSearchClient(object): - """ - Manages Products and ProductSets of reference images for use in - product search. It uses the following resource model: - - - The API has a collection of ``ProductSet`` resources, named - ``projects/*/locations/*/productSets/*``, which acts as a way to put - different products into groups to limit identification. - - In parallel, - - - The API has a collection of ``Product`` resources, named - ``projects/*/locations/*/products/*`` - - - Each ``Product`` has a collection of ``ReferenceImage`` resources, - named ``projects/*/locations/*/products/*/referenceImages/*`` - """ - - SERVICE_ADDRESS = "vision.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.vision.v1.ProductSearch" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProductSearchClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def location_path(cls, project, location): - """Return a fully-qualified location string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}", - project=project, - location=location, - ) - - @classmethod - def product_path(cls, project, location, product): - """Return a fully-qualified product string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/products/{product}", - project=project, - location=location, - product=product, - ) - - @classmethod - def product_set_path(cls, project, location, product_set): - """Return a fully-qualified product_set string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/productSets/{product_set}", - project=project, - location=location, - product_set=product_set, - ) - - @classmethod - def reference_image_path(cls, project, location, product, reference_image): - """Return a fully-qualified reference_image string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}", - project=project, - location=location, - product=product, - reference_image=reference_image, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.ProductSearchGrpcTransport, - Callable[[~.Credentials, type], ~.ProductSearchGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = product_search_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=product_search_grpc_transport.ProductSearchGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = product_search_grpc_transport.ProductSearchGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def import_product_sets( - self, - parent, - input_config, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Asynchronous API that imports a list of reference images to - specified product sets based on a list of image information. - - The ``google.longrunning.Operation`` API can be used to keep track of - the progress and results of the request. ``Operation.metadata`` contains - ``BatchOperationMetadata``. (progress) ``Operation.response`` contains - ``ImportProductSetsResponse``. (results) - - The input source of this method is a csv file on Google Cloud Storage. - For the format of the csv file please see - ``ImportProductSetsGcsSource.csv_file_uri``. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `input_config`: - >>> input_config = {} - >>> - >>> response = client.import_product_sets(parent, input_config) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - parent (str): Required. The project in which the ProductSets should be imported. - - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - input_config (Union[dict, ~google.cloud.vision_v1.types.ImportProductSetsInputConfig]): Required. The input content for the list of requests. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1.types.ImportProductSetsInputConfig` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "import_product_sets" not in self._inner_api_calls: - self._inner_api_calls[ - "import_product_sets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.import_product_sets, - default_retry=self._method_configs["ImportProductSets"].retry, - default_timeout=self._method_configs["ImportProductSets"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.ImportProductSetsRequest( - parent=parent, input_config=input_config, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["import_product_sets"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - product_search_service_pb2.ImportProductSetsResponse, - metadata_type=product_search_service_pb2.BatchOperationMetadata, - ) - - def purge_products( - self, - parent, - product_set_purge_config=None, - delete_orphan_products=None, - force=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Asynchronous API to delete all Products in a ProductSet or all - Products that are in no ProductSet. - - If a Product is a member of the specified ProductSet in addition to - other ProductSets, the Product will still be deleted. - - It is recommended to not delete the specified ProductSet until after - this operation has completed. It is also recommended to not add any of - the Products involved in the batch delete to a new ProductSet while this - operation is running because those Products may still end up deleted. - - It's not possible to undo the PurgeProducts operation. Therefore, it is - recommended to keep the csv files used in ImportProductSets (if that was - how you originally built the Product Set) before starting PurgeProducts, - in case you need to re-import the data after deletion. - - If the plan is to purge all of the Products from a ProductSet and then - re-use the empty ProductSet to re-import new Products into the empty - ProductSet, you must wait until the PurgeProducts operation has finished - for that ProductSet. - - The ``google.longrunning.Operation`` API can be used to keep track of - the progress and results of the request. ``Operation.metadata`` contains - ``BatchOperationMetadata``. (progress) - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> response = client.purge_products(parent) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - parent (str): Required. The project and location in which the Products should be - deleted. - - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - product_set_purge_config (Union[dict, ~google.cloud.vision_v1.types.ProductSetPurgeConfig]): Specify which ProductSet contains the Products to be deleted. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1.types.ProductSetPurgeConfig` - delete_orphan_products (bool): If delete_orphan_products is true, all Products that are not in any - ProductSet will be deleted. - force (bool): The default value is false. Override this value to true to actually perform - the purge. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "purge_products" not in self._inner_api_calls: - self._inner_api_calls[ - "purge_products" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.purge_products, - default_retry=self._method_configs["PurgeProducts"].retry, - default_timeout=self._method_configs["PurgeProducts"].timeout, - client_info=self._client_info, - ) - - # Sanity check: We have some fields which are mutually exclusive; - # raise ValueError if more than one is sent. - google.api_core.protobuf_helpers.check_oneof( - product_set_purge_config=product_set_purge_config, - delete_orphan_products=delete_orphan_products, - ) - - request = product_search_service_pb2.PurgeProductsRequest( - parent=parent, - product_set_purge_config=product_set_purge_config, - delete_orphan_products=delete_orphan_products, - force=force, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["purge_products"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - empty_pb2.Empty, - metadata_type=product_search_service_pb2.BatchOperationMetadata, - ) - - def create_product_set( - self, - parent, - product_set, - product_set_id=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates and returns a new ProductSet resource. - - Possible errors: - - - Returns INVALID_ARGUMENT if display_name is missing, or is longer - than 4096 characters. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `product_set`: - >>> product_set = {} - >>> - >>> response = client.create_product_set(parent, product_set) - - Args: - parent (str): Required. The project in which the ProductSet should be created. - - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - product_set (Union[dict, ~google.cloud.vision_v1.types.ProductSet]): Required. The ProductSet to create. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1.types.ProductSet` - product_set_id (str): A user-supplied resource id for this ProductSet. If set, the server - will attempt to use this value as the resource id. If it is already in - use, an error is returned with code ALREADY_EXISTS. Must be at most 128 - characters long. It cannot contain the character ``/``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1.types.ProductSet` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "create_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_product_set, - default_retry=self._method_configs["CreateProductSet"].retry, - default_timeout=self._method_configs["CreateProductSet"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.CreateProductSetRequest( - parent=parent, product_set=product_set, product_set_id=product_set_id, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_product_sets( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists ProductSets in an unspecified order. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100, or less - than 1. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_product_sets(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_product_sets(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The project from which ProductSets should be listed. - - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.vision_v1.types.ProductSet` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_product_sets" not in self._inner_api_calls: - self._inner_api_calls[ - "list_product_sets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_product_sets, - default_retry=self._method_configs["ListProductSets"].retry, - default_timeout=self._method_configs["ListProductSets"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.ListProductSetsRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_product_sets"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="product_sets", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_product_set( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets information associated with a ProductSet. - - Possible errors: - - - Returns NOT_FOUND if the ProductSet does not exist. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> name = client.product_set_path('[PROJECT]', '[LOCATION]', '[PRODUCT_SET]') - >>> - >>> response = client.get_product_set(name) - - Args: - name (str): Required. Resource name of the ProductSet to get. - - Format is: - ``projects/PROJECT_ID/locations/LOG_ID/productSets/PRODUCT_SET_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1.types.ProductSet` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "get_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_product_set, - default_retry=self._method_configs["GetProductSet"].retry, - default_timeout=self._method_configs["GetProductSet"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.GetProductSetRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_product_set( - self, - product_set, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Makes changes to a ProductSet resource. Only display_name can be - updated currently. - - Possible errors: - - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in update_mask - but missing from the request or longer than 4096 characters. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> # TODO: Initialize `product_set`: - >>> product_set = {} - >>> - >>> response = client.update_product_set(product_set) - - Args: - product_set (Union[dict, ~google.cloud.vision_v1.types.ProductSet]): Required. The ProductSet resource which replaces the one on the server. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1.types.ProductSet` - update_mask (Union[dict, ~google.cloud.vision_v1.types.FieldMask]): The ``FieldMask`` that specifies which fields to update. If - update_mask isn't specified, all mutable fields are to be updated. Valid - mask path is ``display_name``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1.types.ProductSet` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "update_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_product_set, - default_retry=self._method_configs["UpdateProductSet"].retry, - default_timeout=self._method_configs["UpdateProductSet"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.UpdateProductSetRequest( - product_set=product_set, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("product_set.name", product_set.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_product_set( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Permanently deletes a ProductSet. Products and ReferenceImages in the - ProductSet are not deleted. - - The actual image files are not deleted from Google Cloud Storage. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> name = client.product_set_path('[PROJECT]', '[LOCATION]', '[PRODUCT_SET]') - >>> - >>> client.delete_product_set(name) - - Args: - name (str): Required. Resource name of the ProductSet to delete. - - Format is: - ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_product_set, - default_retry=self._method_configs["DeleteProductSet"].retry, - default_timeout=self._method_configs["DeleteProductSet"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.DeleteProductSetRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_product( - self, - parent, - product, - product_id=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates and returns a new product resource. - - Possible errors: - - - Returns INVALID_ARGUMENT if display_name is missing or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or invalid. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `product`: - >>> product = {} - >>> - >>> response = client.create_product(parent, product) - - Args: - parent (str): Required. The project in which the Product should be created. - - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - product (Union[dict, ~google.cloud.vision_v1.types.Product]): Required. The product to create. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1.types.Product` - product_id (str): A user-supplied resource id for this Product. If set, the server - will attempt to use this value as the resource id. If it is already in - use, an error is returned with code ALREADY_EXISTS. Must be at most 128 - characters long. It cannot contain the character ``/``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1.types.Product` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_product" not in self._inner_api_calls: - self._inner_api_calls[ - "create_product" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_product, - default_retry=self._method_configs["CreateProduct"].retry, - default_timeout=self._method_configs["CreateProduct"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.CreateProductRequest( - parent=parent, product=product, product_id=product_id, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_product"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_products( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists products in an unspecified order. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100 or less - than 1. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_products(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_products(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The project OR ProductSet from which Products should be - listed. - - Format: ``projects/PROJECT_ID/locations/LOC_ID`` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.vision_v1.types.Product` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_products" not in self._inner_api_calls: - self._inner_api_calls[ - "list_products" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_products, - default_retry=self._method_configs["ListProducts"].retry, - default_timeout=self._method_configs["ListProducts"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.ListProductsRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_products"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="products", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_product( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets information associated with a Product. - - Possible errors: - - - Returns NOT_FOUND if the Product does not exist. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> name = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> response = client.get_product(name) - - Args: - name (str): Required. Resource name of the Product to get. - - Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1.types.Product` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_product" not in self._inner_api_calls: - self._inner_api_calls[ - "get_product" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_product, - default_retry=self._method_configs["GetProduct"].retry, - default_timeout=self._method_configs["GetProduct"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.GetProductRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_product"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_product( - self, - product, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Makes changes to a Product resource. Only the ``display_name``, - ``description``, and ``labels`` fields can be updated right now. - - If labels are updated, the change will not be reflected in queries until - the next index time. - - Possible errors: - - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in update_mask - but is missing from the request or longer than 4096 characters. - - Returns INVALID_ARGUMENT if description is present in update_mask but - is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> # TODO: Initialize `product`: - >>> product = {} - >>> - >>> response = client.update_product(product) - - Args: - product (Union[dict, ~google.cloud.vision_v1.types.Product]): Required. The Product resource which replaces the one on the server. - product.name is immutable. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1.types.Product` - update_mask (Union[dict, ~google.cloud.vision_v1.types.FieldMask]): The ``FieldMask`` that specifies which fields to update. If - update_mask isn't specified, all mutable fields are to be updated. Valid - mask paths include ``product_labels``, ``display_name``, and - ``description``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1.types.Product` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_product" not in self._inner_api_calls: - self._inner_api_calls[ - "update_product" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_product, - default_retry=self._method_configs["UpdateProduct"].retry, - default_timeout=self._method_configs["UpdateProduct"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.UpdateProductRequest( - product=product, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("product.name", product.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_product"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_product( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Permanently deletes a product and its reference images. - - Metadata of the product and all its images will be deleted right away, but - search queries against ProductSets containing the product may still work - until all related caches are refreshed. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> name = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> client.delete_product(name) - - Args: - name (str): Required. Resource name of product to delete. - - Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_product" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_product" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_product, - default_retry=self._method_configs["DeleteProduct"].retry, - default_timeout=self._method_configs["DeleteProduct"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.DeleteProductRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_product"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_reference_image( - self, - parent, - reference_image, - reference_image_id=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates and returns a new ReferenceImage resource. - - The ``bounding_poly`` field is optional. If ``bounding_poly`` is not - specified, the system will try to detect regions of interest in the - image that are compatible with the product_category on the parent - product. If it is specified, detection is ALWAYS skipped. The system - converts polygons into non-rotated rectangles. - - Note that the pipeline will resize the image if the image resolution is - too large to process (above 50MP). - - Possible errors: - - - Returns INVALID_ARGUMENT if the image_uri is missing or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category is - detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than 10 - polygons. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> parent = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> # TODO: Initialize `reference_image`: - >>> reference_image = {} - >>> - >>> response = client.create_reference_image(parent, reference_image) - - Args: - parent (str): Required. Resource name of the product in which to create the - reference image. - - Format is ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. - reference_image (Union[dict, ~google.cloud.vision_v1.types.ReferenceImage]): Required. The reference image to create. - If an image ID is specified, it is ignored. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1.types.ReferenceImage` - reference_image_id (str): A user-supplied resource id for the ReferenceImage to be added. If - set, the server will attempt to use this value as the resource id. If it - is already in use, an error is returned with code ALREADY_EXISTS. Must - be at most 128 characters long. It cannot contain the character ``/``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1.types.ReferenceImage` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_reference_image" not in self._inner_api_calls: - self._inner_api_calls[ - "create_reference_image" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_reference_image, - default_retry=self._method_configs["CreateReferenceImage"].retry, - default_timeout=self._method_configs["CreateReferenceImage"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.CreateReferenceImageRequest( - parent=parent, - reference_image=reference_image, - reference_image_id=reference_image_id, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_reference_image"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_reference_image( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Permanently deletes a reference image. - - The image metadata will be deleted right away, but search queries - against ProductSets containing the image may still work until all related - caches are refreshed. - - The actual image files are not deleted from Google Cloud Storage. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> name = client.reference_image_path('[PROJECT]', '[LOCATION]', '[PRODUCT]', '[REFERENCE_IMAGE]') - >>> - >>> client.delete_reference_image(name) - - Args: - name (str): Required. The resource name of the reference image to delete. - - Format is: - - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_reference_image" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_reference_image" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_reference_image, - default_retry=self._method_configs["DeleteReferenceImage"].retry, - default_timeout=self._method_configs["DeleteReferenceImage"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.DeleteReferenceImageRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_reference_image"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_reference_images( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists reference images. - - Possible errors: - - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, or - less than 1. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> parent = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> # Iterate over all results - >>> for element in client.list_reference_images(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_reference_images(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. Resource name of the product containing the reference - images. - - Format is ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.vision_v1.types.ReferenceImage` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_reference_images" not in self._inner_api_calls: - self._inner_api_calls[ - "list_reference_images" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_reference_images, - default_retry=self._method_configs["ListReferenceImages"].retry, - default_timeout=self._method_configs["ListReferenceImages"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.ListReferenceImagesRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_reference_images"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="reference_images", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_reference_image( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets information associated with a ReferenceImage. - - Possible errors: - - - Returns NOT_FOUND if the specified image does not exist. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> name = client.reference_image_path('[PROJECT]', '[LOCATION]', '[PRODUCT]', '[REFERENCE_IMAGE]') - >>> - >>> response = client.get_reference_image(name) - - Args: - name (str): Required. The resource name of the ReferenceImage to get. - - Format is: - - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1.types.ReferenceImage` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_reference_image" not in self._inner_api_calls: - self._inner_api_calls[ - "get_reference_image" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_reference_image, - default_retry=self._method_configs["GetReferenceImage"].retry, - default_timeout=self._method_configs["GetReferenceImage"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.GetReferenceImageRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_reference_image"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def add_product_to_product_set( - self, - name, - product, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Adds a Product to the specified ProductSet. If the Product is - already present, no change is made. - - One Product can be added to at most 100 ProductSets. - - Possible errors: - - - Returns NOT_FOUND if the Product or the ProductSet doesn't exist. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> name = client.product_set_path('[PROJECT]', '[LOCATION]', '[PRODUCT_SET]') - >>> product = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> client.add_product_to_product_set(name, product) - - Args: - name (str): Required. The resource name for the ProductSet to modify. - - Format is: - ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` - product (str): Required. The resource name for the Product to be added to this - ProductSet. - - Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "add_product_to_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "add_product_to_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.add_product_to_product_set, - default_retry=self._method_configs["AddProductToProductSet"].retry, - default_timeout=self._method_configs["AddProductToProductSet"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.AddProductToProductSetRequest( - name=name, product=product, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["add_product_to_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def remove_product_from_product_set( - self, - name, - product, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Removes a Product from the specified ProductSet. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> name = client.product_set_path('[PROJECT]', '[LOCATION]', '[PRODUCT_SET]') - >>> product = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> client.remove_product_from_product_set(name, product) - - Args: - name (str): Required. The resource name for the ProductSet to modify. - - Format is: - ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` - product (str): Required. The resource name for the Product to be removed from this - ProductSet. - - Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "remove_product_from_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "remove_product_from_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.remove_product_from_product_set, - default_retry=self._method_configs["RemoveProductFromProductSet"].retry, - default_timeout=self._method_configs[ - "RemoveProductFromProductSet" - ].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.RemoveProductFromProductSetRequest( - name=name, product=product, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["remove_product_from_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_products_in_product_set( - self, - name, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists the Products in a ProductSet, in an unspecified order. If the - ProductSet does not exist, the products field of the response will be - empty. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100 or less - than 1. - - Example: - >>> from google.cloud import vision_v1 - >>> - >>> client = vision_v1.ProductSearchClient() - >>> - >>> name = client.product_set_path('[PROJECT]', '[LOCATION]', '[PRODUCT_SET]') - >>> - >>> # Iterate over all results - >>> for element in client.list_products_in_product_set(name): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_products_in_product_set(name).pages: - ... for element in page: - ... # process element - ... pass - - Args: - name (str): Required. The ProductSet resource for which to retrieve Products. - - Format is: - ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.vision_v1.types.Product` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_products_in_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "list_products_in_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_products_in_product_set, - default_retry=self._method_configs["ListProductsInProductSet"].retry, - default_timeout=self._method_configs[ - "ListProductsInProductSet" - ].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.ListProductsInProductSetRequest( - name=name, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_products_in_product_set"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="products", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator diff --git a/google/cloud/vision_v1/gapic/product_search_client_config.py b/google/cloud/vision_v1/gapic/product_search_client_config.py deleted file mode 100644 index 00bbdce0..00000000 --- a/google/cloud/vision_v1/gapic/product_search_client_config.py +++ /dev/null @@ -1,137 +0,0 @@ -config = { - "interfaces": { - "google.cloud.vision.v1.ProductSearch": { - "retry_codes": { - "no_retry_codes": [], - "retry_policy_3_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "retry_policy_2_codes": [], - }, - "retry_params": { - "retry_policy_2_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 600000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 600000, - "total_timeout_millis": 600000, - }, - "retry_policy_3_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 600000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 600000, - "total_timeout_millis": 600000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - }, - "methods": { - "ImportProductSets": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "PurgeProducts": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "CreateProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListProductSets": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "GetProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "UpdateProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "DeleteProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "CreateProduct": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListProducts": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "GetProduct": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "UpdateProduct": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "DeleteProduct": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "CreateReferenceImage": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "DeleteReferenceImage": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "ListReferenceImages": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "GetReferenceImage": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "AddProductToProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "RemoveProductFromProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "ListProductsInProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - }, - } - } -} diff --git a/google/cloud/vision_v1/gapic/transports/__init__.py b/google/cloud/vision_v1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/vision_v1/gapic/transports/image_annotator_grpc_transport.py b/google/cloud/vision_v1/gapic/transports/image_annotator_grpc_transport.py deleted file mode 100644 index de1ef61f..00000000 --- a/google/cloud/vision_v1/gapic/transports/image_annotator_grpc_transport.py +++ /dev/null @@ -1,194 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers -from google.api_core import operations_v1 - -from google.cloud.vision_v1.proto import image_annotator_pb2_grpc - - -class ImageAnnotatorGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.vision.v1 ImageAnnotator API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ) - - def __init__( - self, channel=None, credentials=None, address="vision.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "image_annotator_stub": image_annotator_pb2_grpc.ImageAnnotatorStub( - channel - ), - } - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="vision.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def batch_annotate_files(self): - """Return the gRPC stub for :meth:`ImageAnnotatorClient.batch_annotate_files`. - - Service that performs image detection and annotation for a batch of files. - Now only "application/pdf", "image/tiff" and "image/gif" are supported. - - This service will extract at most 5 (customers can specify which 5 in - AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each - file provided and perform detection and annotation for each image - extracted. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["image_annotator_stub"].BatchAnnotateFiles - - @property - def async_batch_annotate_images(self): - """Return the gRPC stub for :meth:`ImageAnnotatorClient.async_batch_annotate_images`. - - Run asynchronous image detection and annotation for a list of - images. - - Progress and results can be retrieved through the - ``google.longrunning.Operations`` interface. ``Operation.metadata`` - contains ``OperationMetadata`` (metadata). ``Operation.response`` - contains ``AsyncBatchAnnotateImagesResponse`` (results). - - This service will write image annotation outputs to json files in - customer GCS bucket, each json file containing - BatchAnnotateImagesResponse proto. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["image_annotator_stub"].AsyncBatchAnnotateImages - - @property - def async_batch_annotate_files(self): - """Return the gRPC stub for :meth:`ImageAnnotatorClient.async_batch_annotate_files`. - - Run asynchronous image detection and annotation for a list of - generic files, such as PDF files, which may contain multiple pages and - multiple images per page. Progress and results can be retrieved through - the ``google.longrunning.Operations`` interface. ``Operation.metadata`` - contains ``OperationMetadata`` (metadata). ``Operation.response`` - contains ``AsyncBatchAnnotateFilesResponse`` (results). - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["image_annotator_stub"].AsyncBatchAnnotateFiles - - @property - def batch_annotate_images(self): - """Return the gRPC stub for :meth:`ImageAnnotatorClient.batch_annotate_images`. - - Run image detection and annotation for a batch of images. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["image_annotator_stub"].BatchAnnotateImages diff --git a/google/cloud/vision_v1/gapic/transports/product_search_grpc_transport.py b/google/cloud/vision_v1/gapic/transports/product_search_grpc_transport.py deleted file mode 100644 index b237d0a9..00000000 --- a/google/cloud/vision_v1/gapic/transports/product_search_grpc_transport.py +++ /dev/null @@ -1,510 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers -from google.api_core import operations_v1 - -from google.cloud.vision_v1.proto import product_search_service_pb2_grpc - - -class ProductSearchGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.vision.v1 ProductSearch API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ) - - def __init__( - self, channel=None, credentials=None, address="vision.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "product_search_stub": product_search_service_pb2_grpc.ProductSearchStub( - channel - ), - } - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="vision.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def import_product_sets(self): - """Return the gRPC stub for :meth:`ProductSearchClient.import_product_sets`. - - Asynchronous API that imports a list of reference images to - specified product sets based on a list of image information. - - The ``google.longrunning.Operation`` API can be used to keep track of - the progress and results of the request. ``Operation.metadata`` contains - ``BatchOperationMetadata``. (progress) ``Operation.response`` contains - ``ImportProductSetsResponse``. (results) - - The input source of this method is a csv file on Google Cloud Storage. - For the format of the csv file please see - ``ImportProductSetsGcsSource.csv_file_uri``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].ImportProductSets - - @property - def purge_products(self): - """Return the gRPC stub for :meth:`ProductSearchClient.purge_products`. - - Asynchronous API to delete all Products in a ProductSet or all - Products that are in no ProductSet. - - If a Product is a member of the specified ProductSet in addition to - other ProductSets, the Product will still be deleted. - - It is recommended to not delete the specified ProductSet until after - this operation has completed. It is also recommended to not add any of - the Products involved in the batch delete to a new ProductSet while this - operation is running because those Products may still end up deleted. - - It's not possible to undo the PurgeProducts operation. Therefore, it is - recommended to keep the csv files used in ImportProductSets (if that was - how you originally built the Product Set) before starting PurgeProducts, - in case you need to re-import the data after deletion. - - If the plan is to purge all of the Products from a ProductSet and then - re-use the empty ProductSet to re-import new Products into the empty - ProductSet, you must wait until the PurgeProducts operation has finished - for that ProductSet. - - The ``google.longrunning.Operation`` API can be used to keep track of - the progress and results of the request. ``Operation.metadata`` contains - ``BatchOperationMetadata``. (progress) - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].PurgeProducts - - @property - def create_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.create_product_set`. - - Creates and returns a new ProductSet resource. - - Possible errors: - - - Returns INVALID_ARGUMENT if display_name is missing, or is longer - than 4096 characters. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].CreateProductSet - - @property - def list_product_sets(self): - """Return the gRPC stub for :meth:`ProductSearchClient.list_product_sets`. - - Lists ProductSets in an unspecified order. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100, or less - than 1. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].ListProductSets - - @property - def get_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.get_product_set`. - - Gets information associated with a ProductSet. - - Possible errors: - - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].GetProductSet - - @property - def update_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.update_product_set`. - - Makes changes to a ProductSet resource. Only display_name can be - updated currently. - - Possible errors: - - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in update_mask - but missing from the request or longer than 4096 characters. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].UpdateProductSet - - @property - def delete_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.delete_product_set`. - - Permanently deletes a ProductSet. Products and ReferenceImages in the - ProductSet are not deleted. - - The actual image files are not deleted from Google Cloud Storage. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].DeleteProductSet - - @property - def create_product(self): - """Return the gRPC stub for :meth:`ProductSearchClient.create_product`. - - Creates and returns a new product resource. - - Possible errors: - - - Returns INVALID_ARGUMENT if display_name is missing or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or invalid. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].CreateProduct - - @property - def list_products(self): - """Return the gRPC stub for :meth:`ProductSearchClient.list_products`. - - Lists products in an unspecified order. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100 or less - than 1. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].ListProducts - - @property - def get_product(self): - """Return the gRPC stub for :meth:`ProductSearchClient.get_product`. - - Gets information associated with a Product. - - Possible errors: - - - Returns NOT_FOUND if the Product does not exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].GetProduct - - @property - def update_product(self): - """Return the gRPC stub for :meth:`ProductSearchClient.update_product`. - - Makes changes to a Product resource. Only the ``display_name``, - ``description``, and ``labels`` fields can be updated right now. - - If labels are updated, the change will not be reflected in queries until - the next index time. - - Possible errors: - - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in update_mask - but is missing from the request or longer than 4096 characters. - - Returns INVALID_ARGUMENT if description is present in update_mask but - is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].UpdateProduct - - @property - def delete_product(self): - """Return the gRPC stub for :meth:`ProductSearchClient.delete_product`. - - Permanently deletes a product and its reference images. - - Metadata of the product and all its images will be deleted right away, but - search queries against ProductSets containing the product may still work - until all related caches are refreshed. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].DeleteProduct - - @property - def create_reference_image(self): - """Return the gRPC stub for :meth:`ProductSearchClient.create_reference_image`. - - Creates and returns a new ReferenceImage resource. - - The ``bounding_poly`` field is optional. If ``bounding_poly`` is not - specified, the system will try to detect regions of interest in the - image that are compatible with the product_category on the parent - product. If it is specified, detection is ALWAYS skipped. The system - converts polygons into non-rotated rectangles. - - Note that the pipeline will resize the image if the image resolution is - too large to process (above 50MP). - - Possible errors: - - - Returns INVALID_ARGUMENT if the image_uri is missing or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category is - detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than 10 - polygons. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].CreateReferenceImage - - @property - def delete_reference_image(self): - """Return the gRPC stub for :meth:`ProductSearchClient.delete_reference_image`. - - Permanently deletes a reference image. - - The image metadata will be deleted right away, but search queries - against ProductSets containing the image may still work until all related - caches are refreshed. - - The actual image files are not deleted from Google Cloud Storage. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].DeleteReferenceImage - - @property - def list_reference_images(self): - """Return the gRPC stub for :meth:`ProductSearchClient.list_reference_images`. - - Lists reference images. - - Possible errors: - - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, or - less than 1. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].ListReferenceImages - - @property - def get_reference_image(self): - """Return the gRPC stub for :meth:`ProductSearchClient.get_reference_image`. - - Gets information associated with a ReferenceImage. - - Possible errors: - - - Returns NOT_FOUND if the specified image does not exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].GetReferenceImage - - @property - def add_product_to_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.add_product_to_product_set`. - - Adds a Product to the specified ProductSet. If the Product is - already present, no change is made. - - One Product can be added to at most 100 ProductSets. - - Possible errors: - - - Returns NOT_FOUND if the Product or the ProductSet doesn't exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].AddProductToProductSet - - @property - def remove_product_from_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.remove_product_from_product_set`. - - Removes a Product from the specified ProductSet. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].RemoveProductFromProductSet - - @property - def list_products_in_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.list_products_in_product_set`. - - Lists the Products in a ProductSet, in an unspecified order. If the - ProductSet does not exist, the products field of the response will be - empty. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100 or less - than 1. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].ListProductsInProductSet diff --git a/google/cloud/vision_v1/proto/__init__.py b/google/cloud/vision_v1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/vision_v1/proto/geometry_pb2.py b/google/cloud/vision_v1/proto/geometry_pb2.py deleted file mode 100644 index 9629f858..00000000 --- a/google/cloud/vision_v1/proto/geometry_pb2.py +++ /dev/null @@ -1,373 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1/proto/geometry.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1/proto/geometry.proto", - package="google.cloud.vision.v1", - syntax="proto3", - serialized_options=b"\n\032com.google.cloud.vision.v1B\rGeometryProtoP\001Z\n\x10\x66\x64_bounding_poly\x18\x02 \x01(\x0b\x32$.google.cloud.vision.v1.BoundingPoly\x12\x42\n\tlandmarks\x18\x03 \x03(\x0b\x32/.google.cloud.vision.v1.FaceAnnotation.Landmark\x12\x12\n\nroll_angle\x18\x04 \x01(\x02\x12\x11\n\tpan_angle\x18\x05 \x01(\x02\x12\x12\n\ntilt_angle\x18\x06 \x01(\x02\x12\x1c\n\x14\x64\x65tection_confidence\x18\x07 \x01(\x02\x12\x1e\n\x16landmarking_confidence\x18\x08 \x01(\x02\x12:\n\x0ejoy_likelihood\x18\t \x01(\x0e\x32".google.cloud.vision.v1.Likelihood\x12=\n\x11sorrow_likelihood\x18\n \x01(\x0e\x32".google.cloud.vision.v1.Likelihood\x12<\n\x10\x61nger_likelihood\x18\x0b \x01(\x0e\x32".google.cloud.vision.v1.Likelihood\x12?\n\x13surprise_likelihood\x18\x0c \x01(\x0e\x32".google.cloud.vision.v1.Likelihood\x12\x44\n\x18under_exposed_likelihood\x18\r \x01(\x0e\x32".google.cloud.vision.v1.Likelihood\x12>\n\x12\x62lurred_likelihood\x18\x0e \x01(\x0e\x32".google.cloud.vision.v1.Likelihood\x12?\n\x13headwear_likelihood\x18\x0f \x01(\x0e\x32".google.cloud.vision.v1.Likelihood\x1a\xb9\x07\n\x08Landmark\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32\x34.google.cloud.vision.v1.FaceAnnotation.Landmark.Type\x12\x32\n\x08position\x18\x04 \x01(\x0b\x32 .google.cloud.vision.v1.Position"\xb4\x06\n\x04Type\x12\x14\n\x10UNKNOWN_LANDMARK\x10\x00\x12\x0c\n\x08LEFT_EYE\x10\x01\x12\r\n\tRIGHT_EYE\x10\x02\x12\x18\n\x14LEFT_OF_LEFT_EYEBROW\x10\x03\x12\x19\n\x15RIGHT_OF_LEFT_EYEBROW\x10\x04\x12\x19\n\x15LEFT_OF_RIGHT_EYEBROW\x10\x05\x12\x1a\n\x16RIGHT_OF_RIGHT_EYEBROW\x10\x06\x12\x19\n\x15MIDPOINT_BETWEEN_EYES\x10\x07\x12\x0c\n\x08NOSE_TIP\x10\x08\x12\r\n\tUPPER_LIP\x10\t\x12\r\n\tLOWER_LIP\x10\n\x12\x0e\n\nMOUTH_LEFT\x10\x0b\x12\x0f\n\x0bMOUTH_RIGHT\x10\x0c\x12\x10\n\x0cMOUTH_CENTER\x10\r\x12\x15\n\x11NOSE_BOTTOM_RIGHT\x10\x0e\x12\x14\n\x10NOSE_BOTTOM_LEFT\x10\x0f\x12\x16\n\x12NOSE_BOTTOM_CENTER\x10\x10\x12\x19\n\x15LEFT_EYE_TOP_BOUNDARY\x10\x11\x12\x19\n\x15LEFT_EYE_RIGHT_CORNER\x10\x12\x12\x1c\n\x18LEFT_EYE_BOTTOM_BOUNDARY\x10\x13\x12\x18\n\x14LEFT_EYE_LEFT_CORNER\x10\x14\x12\x1a\n\x16RIGHT_EYE_TOP_BOUNDARY\x10\x15\x12\x1a\n\x16RIGHT_EYE_RIGHT_CORNER\x10\x16\x12\x1d\n\x19RIGHT_EYE_BOTTOM_BOUNDARY\x10\x17\x12\x19\n\x15RIGHT_EYE_LEFT_CORNER\x10\x18\x12\x1f\n\x1bLEFT_EYEBROW_UPPER_MIDPOINT\x10\x19\x12 \n\x1cRIGHT_EYEBROW_UPPER_MIDPOINT\x10\x1a\x12\x14\n\x10LEFT_EAR_TRAGION\x10\x1b\x12\x15\n\x11RIGHT_EAR_TRAGION\x10\x1c\x12\x12\n\x0eLEFT_EYE_PUPIL\x10\x1d\x12\x13\n\x0fRIGHT_EYE_PUPIL\x10\x1e\x12\x15\n\x11\x46OREHEAD_GLABELLA\x10\x1f\x12\x11\n\rCHIN_GNATHION\x10 \x12\x14\n\x10\x43HIN_LEFT_GONION\x10!\x12\x15\n\x11\x43HIN_RIGHT_GONION\x10""4\n\x0cLocationInfo\x12$\n\x07lat_lng\x18\x01 \x01(\x0b\x32\x13.google.type.LatLng"=\n\x08Property\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t\x12\x14\n\x0cuint64_value\x18\x03 \x01(\x04"\xab\x02\n\x10\x45ntityAnnotation\x12\x0b\n\x03mid\x18\x01 \x01(\t\x12\x0e\n\x06locale\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\x12\r\n\x05score\x18\x04 \x01(\x02\x12\x16\n\nconfidence\x18\x05 \x01(\x02\x42\x02\x18\x01\x12\x12\n\ntopicality\x18\x06 \x01(\x02\x12;\n\rbounding_poly\x18\x07 \x01(\x0b\x32$.google.cloud.vision.v1.BoundingPoly\x12\x37\n\tlocations\x18\x08 \x03(\x0b\x32$.google.cloud.vision.v1.LocationInfo\x12\x34\n\nproperties\x18\t \x03(\x0b\x32 .google.cloud.vision.v1.Property"\x99\x01\n\x19LocalizedObjectAnnotation\x12\x0b\n\x03mid\x18\x01 \x01(\t\x12\x15\n\rlanguage_code\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\r\n\x05score\x18\x04 \x01(\x02\x12;\n\rbounding_poly\x18\x05 \x01(\x0b\x32$.google.cloud.vision.v1.BoundingPoly"\xb8\x03\n\x14SafeSearchAnnotation\x12\x31\n\x05\x61\x64ult\x18\x01 \x01(\x0e\x32".google.cloud.vision.v1.Likelihood\x12\x31\n\x05spoof\x18\x02 \x01(\x0e\x32".google.cloud.vision.v1.Likelihood\x12\x33\n\x07medical\x18\x03 \x01(\x0e\x32".google.cloud.vision.v1.Likelihood\x12\x34\n\x08violence\x18\x04 \x01(\x0e\x32".google.cloud.vision.v1.Likelihood\x12\x30\n\x04racy\x18\t \x01(\x0e\x32".google.cloud.vision.v1.Likelihood\x12\x18\n\x10\x61\x64ult_confidence\x18\x10 \x01(\x02\x12\x18\n\x10spoof_confidence\x18\x12 \x01(\x02\x12\x1a\n\x12medical_confidence\x18\x14 \x01(\x02\x12\x1b\n\x13violence_confidence\x18\x16 \x01(\x02\x12\x17\n\x0fracy_confidence\x18\x18 \x01(\x02\x12\x17\n\x0fnsfw_confidence\x18\x1a \x01(\x02"a\n\x0bLatLongRect\x12(\n\x0bmin_lat_lng\x18\x01 \x01(\x0b\x32\x13.google.type.LatLng\x12(\n\x0bmax_lat_lng\x18\x02 \x01(\x0b\x32\x13.google.type.LatLng"U\n\tColorInfo\x12!\n\x05\x63olor\x18\x01 \x01(\x0b\x32\x12.google.type.Color\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x16\n\x0epixel_fraction\x18\x03 \x01(\x02"M\n\x18\x44ominantColorsAnnotation\x12\x31\n\x06\x63olors\x18\x01 \x03(\x0b\x32!.google.cloud.vision.v1.ColorInfo"\\\n\x0fImageProperties\x12I\n\x0f\x64ominant_colors\x18\x01 \x01(\x0b\x32\x30.google.cloud.vision.v1.DominantColorsAnnotation"x\n\x08\x43ropHint\x12;\n\rbounding_poly\x18\x01 \x01(\x0b\x32$.google.cloud.vision.v1.BoundingPoly\x12\x12\n\nconfidence\x18\x02 \x01(\x02\x12\x1b\n\x13importance_fraction\x18\x03 \x01(\x02"K\n\x13\x43ropHintsAnnotation\x12\x34\n\ncrop_hints\x18\x01 \x03(\x0b\x32 .google.cloud.vision.v1.CropHint"(\n\x0f\x43ropHintsParams\x12\x15\n\raspect_ratios\x18\x01 \x03(\x02"1\n\x12WebDetectionParams\x12\x1b\n\x13include_geo_results\x18\x02 \x01(\x08"\xbc\x02\n\x0cImageContext\x12:\n\rlat_long_rect\x18\x01 \x01(\x0b\x32#.google.cloud.vision.v1.LatLongRect\x12\x16\n\x0elanguage_hints\x18\x02 \x03(\t\x12\x42\n\x11\x63rop_hints_params\x18\x04 \x01(\x0b\x32\'.google.cloud.vision.v1.CropHintsParams\x12J\n\x15product_search_params\x18\x05 \x01(\x0b\x32+.google.cloud.vision.v1.ProductSearchParams\x12H\n\x14web_detection_params\x18\x06 \x01(\x0b\x32*.google.cloud.vision.v1.WebDetectionParams"\xb4\x01\n\x14\x41nnotateImageRequest\x12,\n\x05image\x18\x01 \x01(\x0b\x32\x1d.google.cloud.vision.v1.Image\x12\x31\n\x08\x66\x65\x61tures\x18\x02 \x03(\x0b\x32\x1f.google.cloud.vision.v1.Feature\x12;\n\rimage_context\x18\x03 \x01(\x0b\x32$.google.cloud.vision.v1.ImageContext":\n\x16ImageAnnotationContext\x12\x0b\n\x03uri\x18\x01 \x01(\t\x12\x13\n\x0bpage_number\x18\x02 \x01(\x05"\xe4\x07\n\x15\x41nnotateImageResponse\x12@\n\x10\x66\x61\x63\x65_annotations\x18\x01 \x03(\x0b\x32&.google.cloud.vision.v1.FaceAnnotation\x12\x46\n\x14landmark_annotations\x18\x02 \x03(\x0b\x32(.google.cloud.vision.v1.EntityAnnotation\x12\x42\n\x10logo_annotations\x18\x03 \x03(\x0b\x32(.google.cloud.vision.v1.EntityAnnotation\x12\x43\n\x11label_annotations\x18\x04 \x03(\x0b\x32(.google.cloud.vision.v1.EntityAnnotation\x12W\n\x1clocalized_object_annotations\x18\x16 \x03(\x0b\x32\x31.google.cloud.vision.v1.LocalizedObjectAnnotation\x12\x42\n\x10text_annotations\x18\x05 \x03(\x0b\x32(.google.cloud.vision.v1.EntityAnnotation\x12\x44\n\x14\x66ull_text_annotation\x18\x0c \x01(\x0b\x32&.google.cloud.vision.v1.TextAnnotation\x12L\n\x16safe_search_annotation\x18\x06 \x01(\x0b\x32,.google.cloud.vision.v1.SafeSearchAnnotation\x12L\n\x1bimage_properties_annotation\x18\x08 \x01(\x0b\x32\'.google.cloud.vision.v1.ImageProperties\x12J\n\x15\x63rop_hints_annotation\x18\x0b \x01(\x0b\x32+.google.cloud.vision.v1.CropHintsAnnotation\x12;\n\rweb_detection\x18\r \x01(\x0b\x32$.google.cloud.vision.v1.WebDetection\x12L\n\x16product_search_results\x18\x0e \x01(\x0b\x32,.google.cloud.vision.v1.ProductSearchResults\x12!\n\x05\x65rror\x18\t \x01(\x0b\x32\x12.google.rpc.Status\x12?\n\x07\x63ontext\x18\x15 \x01(\x0b\x32..google.cloud.vision.v1.ImageAnnotationContext"q\n\x1a\x42\x61tchAnnotateImagesRequest\x12\x43\n\x08requests\x18\x01 \x03(\x0b\x32,.google.cloud.vision.v1.AnnotateImageRequestB\x03\xe0\x41\x02\x12\x0e\n\x06parent\x18\x04 \x01(\t"_\n\x1b\x42\x61tchAnnotateImagesResponse\x12@\n\tresponses\x18\x01 \x03(\x0b\x32-.google.cloud.vision.v1.AnnotateImageResponse"\xcf\x01\n\x13\x41nnotateFileRequest\x12\x39\n\x0cinput_config\x18\x01 \x01(\x0b\x32#.google.cloud.vision.v1.InputConfig\x12\x31\n\x08\x66\x65\x61tures\x18\x02 \x03(\x0b\x32\x1f.google.cloud.vision.v1.Feature\x12;\n\rimage_context\x18\x03 \x01(\x0b\x32$.google.cloud.vision.v1.ImageContext\x12\r\n\x05pages\x18\x04 \x03(\x05"\xcb\x01\n\x14\x41nnotateFileResponse\x12\x39\n\x0cinput_config\x18\x01 \x01(\x0b\x32#.google.cloud.vision.v1.InputConfig\x12@\n\tresponses\x18\x02 \x03(\x0b\x32-.google.cloud.vision.v1.AnnotateImageResponse\x12\x13\n\x0btotal_pages\x18\x03 \x01(\x05\x12!\n\x05\x65rror\x18\x04 \x01(\x0b\x32\x12.google.rpc.Status"o\n\x19\x42\x61tchAnnotateFilesRequest\x12\x42\n\x08requests\x18\x01 \x03(\x0b\x32+.google.cloud.vision.v1.AnnotateFileRequestB\x03\xe0\x41\x02\x12\x0e\n\x06parent\x18\x03 \x01(\t"]\n\x1a\x42\x61tchAnnotateFilesResponse\x12?\n\tresponses\x18\x01 \x03(\x0b\x32,.google.cloud.vision.v1.AnnotateFileResponse"\x82\x02\n\x18\x41syncAnnotateFileRequest\x12\x39\n\x0cinput_config\x18\x01 \x01(\x0b\x32#.google.cloud.vision.v1.InputConfig\x12\x31\n\x08\x66\x65\x61tures\x18\x02 \x03(\x0b\x32\x1f.google.cloud.vision.v1.Feature\x12;\n\rimage_context\x18\x03 \x01(\x0b\x32$.google.cloud.vision.v1.ImageContext\x12;\n\routput_config\x18\x04 \x01(\x0b\x32$.google.cloud.vision.v1.OutputConfig"X\n\x19\x41syncAnnotateFileResponse\x12;\n\routput_config\x18\x01 \x01(\x0b\x32$.google.cloud.vision.v1.OutputConfig"\xb8\x01\n\x1f\x41syncBatchAnnotateImagesRequest\x12\x43\n\x08requests\x18\x01 \x03(\x0b\x32,.google.cloud.vision.v1.AnnotateImageRequestB\x03\xe0\x41\x02\x12@\n\routput_config\x18\x02 \x01(\x0b\x32$.google.cloud.vision.v1.OutputConfigB\x03\xe0\x41\x02\x12\x0e\n\x06parent\x18\x04 \x01(\t"_\n AsyncBatchAnnotateImagesResponse\x12;\n\routput_config\x18\x01 \x01(\x0b\x32$.google.cloud.vision.v1.OutputConfig"y\n\x1e\x41syncBatchAnnotateFilesRequest\x12G\n\x08requests\x18\x01 \x03(\x0b\x32\x30.google.cloud.vision.v1.AsyncAnnotateFileRequestB\x03\xe0\x41\x02\x12\x0e\n\x06parent\x18\x04 \x01(\t"g\n\x1f\x41syncBatchAnnotateFilesResponse\x12\x44\n\tresponses\x18\x01 \x03(\x0b\x32\x31.google.cloud.vision.v1.AsyncAnnotateFileResponse"h\n\x0bInputConfig\x12\x35\n\ngcs_source\x18\x01 \x01(\x0b\x32!.google.cloud.vision.v1.GcsSource\x12\x0f\n\x07\x63ontent\x18\x03 \x01(\x0c\x12\x11\n\tmime_type\x18\x02 \x01(\t"c\n\x0cOutputConfig\x12?\n\x0fgcs_destination\x18\x01 \x01(\x0b\x32&.google.cloud.vision.v1.GcsDestination\x12\x12\n\nbatch_size\x18\x02 \x01(\x05"\x18\n\tGcsSource\x12\x0b\n\x03uri\x18\x01 \x01(\t"\x1d\n\x0eGcsDestination\x12\x0b\n\x03uri\x18\x01 \x01(\t"\x88\x02\n\x11OperationMetadata\x12>\n\x05state\x18\x01 \x01(\x0e\x32/.google.cloud.vision.v1.OperationMetadata.State\x12/\n\x0b\x63reate_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"Q\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0b\n\x07\x43REATED\x10\x01\x12\x0b\n\x07RUNNING\x10\x02\x12\x08\n\x04\x44ONE\x10\x03\x12\r\n\tCANCELLED\x10\x04*e\n\nLikelihood\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x11\n\rVERY_UNLIKELY\x10\x01\x12\x0c\n\x08UNLIKELY\x10\x02\x12\x0c\n\x08POSSIBLE\x10\x03\x12\n\n\x06LIKELY\x10\x04\x12\x0f\n\x0bVERY_LIKELY\x10\x05\x32\xf5\n\n\x0eImageAnnotator\x12\x93\x02\n\x13\x42\x61tchAnnotateImages\x12\x32.google.cloud.vision.v1.BatchAnnotateImagesRequest\x1a\x33.google.cloud.vision.v1.BatchAnnotateImagesResponse"\x92\x01\x82\xd3\xe4\x93\x02\x80\x01"\x13/v1/images:annotate:\x01*Z8"3/v1/{parent=projects/*/locations/*}/images:annotate:\x01*Z,"\'/v1/{parent=projects/*}/images:annotate:\x01*\xda\x41\x08requests\x12\x8c\x02\n\x12\x42\x61tchAnnotateFiles\x12\x31.google.cloud.vision.v1.BatchAnnotateFilesRequest\x1a\x32.google.cloud.vision.v1.BatchAnnotateFilesResponse"\x8e\x01\x82\xd3\xe4\x93\x02}"\x12/v1/files:annotate:\x01*Z7"2/v1/{parent=projects/*/locations/*}/files:annotate:\x01*Z+"&/v1/{parent=projects/*}/files:annotate:\x01*\xda\x41\x08requests\x12\xeb\x02\n\x18\x41syncBatchAnnotateImages\x12\x37.google.cloud.vision.v1.AsyncBatchAnnotateImagesRequest\x1a\x1d.google.longrunning.Operation"\xf6\x01\x82\xd3\xe4\x93\x02\x9e\x01"\x1d/v1/images:asyncBatchAnnotate:\x01*ZB"=/v1/{parent=projects/*/locations/*}/images:asyncBatchAnnotate:\x01*Z6"1/v1/{parent=projects/*}/images:asyncBatchAnnotate:\x01*\xda\x41\x16requests,output_config\xca\x41\x35\n AsyncBatchAnnotateImagesResponse\x12\x11OperationMetadata\x12\xd7\x02\n\x17\x41syncBatchAnnotateFiles\x12\x36.google.cloud.vision.v1.AsyncBatchAnnotateFilesRequest\x1a\x1d.google.longrunning.Operation"\xe4\x01\x82\xd3\xe4\x93\x02\x9b\x01"\x1c/v1/files:asyncBatchAnnotate:\x01*ZA"`__ - for more info. - image_uri: - The URI of the source image. Can be either: 1. A Google Cloud - Storage URI of the form ``gs://bucket_name/object_name``. - Object versioning is not supported. See `Google Cloud - Storage Request URIs - `__ for - more info. 2. A publicly-accessible image HTTP/HTTPS URL. - When fetching images from HTTP/HTTPS URLs, Google cannot - guarantee that the request will be completed. Your request - may fail if the specified host denies the request (e.g. due - to request throttling or DOS prevention), or if Google - throttles requests to the site for abuse prevention. You - should not depend on externally-hosted images for production - applications. When both ``gcs_image_uri`` and ``image_uri`` - are specified, ``image_uri`` takes precedence. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.ImageSource) - }, -) -_sym_db.RegisterMessage(ImageSource) - -Image = _reflection.GeneratedProtocolMessageType( - "Image", - (_message.Message,), - { - "DESCRIPTOR": _IMAGE, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Client image to perform Google Cloud Vision API tasks over. - - Attributes: - content: - Image content, represented as a stream of bytes. Note: As with - all ``bytes`` fields, protobuffers use a pure binary - representation, whereas JSON representations use base64. - source: - Google Cloud Storage image location, or publicly-accessible - image URL. If both ``content`` and ``source`` are provided for - an image, ``content`` takes precedence and is used to perform - the image annotation request. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.Image) - }, -) -_sym_db.RegisterMessage(Image) - -FaceAnnotation = _reflection.GeneratedProtocolMessageType( - "FaceAnnotation", - (_message.Message,), - { - "Landmark": _reflection.GeneratedProtocolMessageType( - "Landmark", - (_message.Message,), - { - "DESCRIPTOR": _FACEANNOTATION_LANDMARK, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """A face-specific landmark (for example, a face feature). - - Attributes: - type: - Face landmark type. - position: - Face landmark position. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.FaceAnnotation.Landmark) - }, - ), - "DESCRIPTOR": _FACEANNOTATION, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """A face annotation object contains the results of face detection. - - Attributes: - bounding_poly: - The bounding polygon around the face. The coordinates of the - bounding box are in the original image’s scale. The bounding - box is computed to “frame” the face in accordance with human - expectations. It is based on the landmarker results. Note that - one or more x and/or y coordinates may not be generated in the - ``BoundingPoly`` (the polygon will be unbounded) if only a - partial face appears in the image to be annotated. - fd_bounding_poly: - The ``fd_bounding_poly`` bounding polygon is tighter than the - ``boundingPoly``, and encloses only the skin part of the face. - Typically, it is used to eliminate the face from any image - analysis that detects the “amount of skin” visible in an - image. It is not based on the landmarker results, only on the - initial face detection, hence the fd (face detection) prefix. - landmarks: - Detected face landmarks. - roll_angle: - Roll angle, which indicates the amount of clockwise/anti- - clockwise rotation of the face relative to the image vertical - about the axis perpendicular to the face. Range [-180,180]. - pan_angle: - Yaw angle, which indicates the leftward/rightward angle that - the face is pointing relative to the vertical plane - perpendicular to the image. Range [-180,180]. - tilt_angle: - Pitch angle, which indicates the upwards/downwards angle that - the face is pointing relative to the image’s horizontal plane. - Range [-180,180]. - detection_confidence: - Detection confidence. Range [0, 1]. - landmarking_confidence: - Face landmarking confidence. Range [0, 1]. - joy_likelihood: - Joy likelihood. - sorrow_likelihood: - Sorrow likelihood. - anger_likelihood: - Anger likelihood. - surprise_likelihood: - Surprise likelihood. - under_exposed_likelihood: - Under-exposed likelihood. - blurred_likelihood: - Blurred likelihood. - headwear_likelihood: - Headwear likelihood. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.FaceAnnotation) - }, -) -_sym_db.RegisterMessage(FaceAnnotation) -_sym_db.RegisterMessage(FaceAnnotation.Landmark) - -LocationInfo = _reflection.GeneratedProtocolMessageType( - "LocationInfo", - (_message.Message,), - { - "DESCRIPTOR": _LOCATIONINFO, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Detected entity location information. - - Attributes: - lat_lng: - lat/long location coordinates. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.LocationInfo) - }, -) -_sym_db.RegisterMessage(LocationInfo) - -Property = _reflection.GeneratedProtocolMessageType( - "Property", - (_message.Message,), - { - "DESCRIPTOR": _PROPERTY, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """A ``Property`` consists of a user-supplied name/value pair. - - Attributes: - name: - Name of the property. - value: - Value of the property. - uint64_value: - Value of numeric properties. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.Property) - }, -) -_sym_db.RegisterMessage(Property) - -EntityAnnotation = _reflection.GeneratedProtocolMessageType( - "EntityAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _ENTITYANNOTATION, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Set of detected entity features. - - Attributes: - mid: - Opaque entity ID. Some IDs may be available in `Google - Knowledge Graph Search API - `__. - locale: - The language code for the locale in which the entity textual - ``description`` is expressed. - description: - Entity textual description, expressed in its ``locale`` - language. - score: - Overall score of the result. Range [0, 1]. - confidence: - \ **Deprecated. Use ``score`` instead.** The accuracy of the - entity detection in an image. For example, for an image in - which the “Eiffel Tower” entity is detected, this field - represents the confidence that there is a tower in the query - image. Range [0, 1]. - topicality: - The relevancy of the ICA (Image Content Annotation) label to - the image. For example, the relevancy of “tower” is likely - higher to an image containing the detected “Eiffel Tower” than - to an image containing a detected distant towering building, - even though the confidence that there is a tower in each image - may be the same. Range [0, 1]. - bounding_poly: - Image region to which this entity belongs. Not produced for - ``LABEL_DETECTION`` features. - locations: - The location information for the detected entity. Multiple - ``LocationInfo`` elements can be present because one location - may indicate the location of the scene in the image, and - another location may indicate the location of the place where - the image was taken. Location information is usually present - for landmarks. - properties: - Some entities may have optional user-supplied ``Property`` - (name/value) fields, such a score or string that qualifies the - entity. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.EntityAnnotation) - }, -) -_sym_db.RegisterMessage(EntityAnnotation) - -LocalizedObjectAnnotation = _reflection.GeneratedProtocolMessageType( - "LocalizedObjectAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _LOCALIZEDOBJECTANNOTATION, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Set of detected objects with bounding boxes. - - Attributes: - mid: - Object ID that should align with EntityAnnotation mid. - language_code: - The BCP-47 language code, such as “en-US” or “sr-Latn”. For - more information, see http://www.unicode.org/reports/tr35/#Uni - code_locale_identifier. - name: - Object name, expressed in its ``language_code`` language. - score: - Score of the result. Range [0, 1]. - bounding_poly: - Image region to which this object belongs. This must be - populated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.LocalizedObjectAnnotation) - }, -) -_sym_db.RegisterMessage(LocalizedObjectAnnotation) - -SafeSearchAnnotation = _reflection.GeneratedProtocolMessageType( - "SafeSearchAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _SAFESEARCHANNOTATION, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Set of features pertaining to the image, computed by computer vision - methods over safe-search verticals (for example, adult, spoof, - medical, violence). - - Attributes: - adult: - Represents the adult content likelihood for the image. Adult - content may contain elements such as nudity, pornographic - images or cartoons, or sexual activities. - spoof: - Spoof likelihood. The likelihood that an modification was made - to the image’s canonical version to make it appear funny or - offensive. - medical: - Likelihood that this is a medical image. - violence: - Likelihood that this image contains violent content. - racy: - Likelihood that the request image contains racy content. Racy - content may include (but is not limited to) skimpy or sheer - clothing, strategically covered nudity, lewd or provocative - poses, or close-ups of sensitive body areas. - adult_confidence: - Confidence of adult_score. Range [0, 1]. 0 means not - confident, 1 means very confident. - spoof_confidence: - Confidence of spoof_score. Range [0, 1]. 0 means not - confident, 1 means very confident. - medical_confidence: - Confidence of medical_score. Range [0, 1]. 0 means not - confident, 1 means very confident. - violence_confidence: - Confidence of violence_score. Range [0, 1]. 0 means not - confident, 1 means very confident. - racy_confidence: - Confidence of racy_score. Range [0, 1]. 0 means not confident, - 1 means very confident. - nsfw_confidence: - Confidence of nsfw_score. Range [0, 1]. 0 means not confident, - 1 means very confident. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.SafeSearchAnnotation) - }, -) -_sym_db.RegisterMessage(SafeSearchAnnotation) - -LatLongRect = _reflection.GeneratedProtocolMessageType( - "LatLongRect", - (_message.Message,), - { - "DESCRIPTOR": _LATLONGRECT, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Rectangle determined by min and max ``LatLng`` pairs. - - Attributes: - min_lat_lng: - Min lat/long pair. - max_lat_lng: - Max lat/long pair. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.LatLongRect) - }, -) -_sym_db.RegisterMessage(LatLongRect) - -ColorInfo = _reflection.GeneratedProtocolMessageType( - "ColorInfo", - (_message.Message,), - { - "DESCRIPTOR": _COLORINFO, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Color information consists of RGB channels, score, and the fraction of - the image that the color occupies in the image. - - Attributes: - color: - RGB components of the color. - score: - Image-specific score for this color. Value in range [0, 1]. - pixel_fraction: - The fraction of pixels the color occupies in the image. Value - in range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.ColorInfo) - }, -) -_sym_db.RegisterMessage(ColorInfo) - -DominantColorsAnnotation = _reflection.GeneratedProtocolMessageType( - "DominantColorsAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _DOMINANTCOLORSANNOTATION, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Set of dominant colors and their corresponding scores. - - Attributes: - colors: - RGB color values with their score and pixel fraction. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.DominantColorsAnnotation) - }, -) -_sym_db.RegisterMessage(DominantColorsAnnotation) - -ImageProperties = _reflection.GeneratedProtocolMessageType( - "ImageProperties", - (_message.Message,), - { - "DESCRIPTOR": _IMAGEPROPERTIES, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Stores image properties, such as dominant colors. - - Attributes: - dominant_colors: - If present, dominant colors completed successfully. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.ImageProperties) - }, -) -_sym_db.RegisterMessage(ImageProperties) - -CropHint = _reflection.GeneratedProtocolMessageType( - "CropHint", - (_message.Message,), - { - "DESCRIPTOR": _CROPHINT, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Single crop hint that is used to generate a new crop when serving an - image. - - Attributes: - bounding_poly: - The bounding polygon for the crop region. The coordinates of - the bounding box are in the original image’s scale. - confidence: - Confidence of this being a salient region. Range [0, 1]. - importance_fraction: - Fraction of importance of this salient region with respect to - the original image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.CropHint) - }, -) -_sym_db.RegisterMessage(CropHint) - -CropHintsAnnotation = _reflection.GeneratedProtocolMessageType( - "CropHintsAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _CROPHINTSANNOTATION, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Set of crop hints that are used to generate new crops when serving - images. - - Attributes: - crop_hints: - Crop hint results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.CropHintsAnnotation) - }, -) -_sym_db.RegisterMessage(CropHintsAnnotation) - -CropHintsParams = _reflection.GeneratedProtocolMessageType( - "CropHintsParams", - (_message.Message,), - { - "DESCRIPTOR": _CROPHINTSPARAMS, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Parameters for crop hints annotation request. - - Attributes: - aspect_ratios: - Aspect ratios in floats, representing the ratio of the width - to the height of the image. For example, if the desired aspect - ratio is 4/3, the corresponding float value should be 1.33333. - If not specified, the best possible crop is returned. The - number of provided aspect ratios is limited to a maximum of - 16; any aspect ratios provided after the 16th are ignored. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.CropHintsParams) - }, -) -_sym_db.RegisterMessage(CropHintsParams) - -WebDetectionParams = _reflection.GeneratedProtocolMessageType( - "WebDetectionParams", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTIONPARAMS, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Parameters for web detection request. - - Attributes: - include_geo_results: - Whether to include results derived from the geo information in - the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.WebDetectionParams) - }, -) -_sym_db.RegisterMessage(WebDetectionParams) - -ImageContext = _reflection.GeneratedProtocolMessageType( - "ImageContext", - (_message.Message,), - { - "DESCRIPTOR": _IMAGECONTEXT, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Image context and/or feature-specific parameters. - - Attributes: - lat_long_rect: - Not used. - language_hints: - List of languages to use for TEXT_DETECTION. In most cases, an - empty value yields the best results since it enables automatic - language detection. For languages based on the Latin alphabet, - setting ``language_hints`` is not needed. In rare cases, when - the language of the text in the image is known, setting a hint - will help get better results (although it will be a - significant hindrance if the hint is wrong). Text detection - returns an error if one or more of the specified languages is - not one of the `supported languages - `__. - crop_hints_params: - Parameters for crop hints annotation request. - product_search_params: - Parameters for product search. - web_detection_params: - Parameters for web detection. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.ImageContext) - }, -) -_sym_db.RegisterMessage(ImageContext) - -AnnotateImageRequest = _reflection.GeneratedProtocolMessageType( - "AnnotateImageRequest", - (_message.Message,), - { - "DESCRIPTOR": _ANNOTATEIMAGEREQUEST, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Request for performing Google Cloud Vision API tasks over a user- - provided image, with user-requested features, and with context - information. - - Attributes: - image: - The image to be processed. - features: - Requested features. - image_context: - Additional context that may accompany the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.AnnotateImageRequest) - }, -) -_sym_db.RegisterMessage(AnnotateImageRequest) - -ImageAnnotationContext = _reflection.GeneratedProtocolMessageType( - "ImageAnnotationContext", - (_message.Message,), - { - "DESCRIPTOR": _IMAGEANNOTATIONCONTEXT, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """If an image was produced from a file (e.g. a PDF), this message gives - information about the source of that image. - - Attributes: - uri: - The URI of the file used to produce the image. - page_number: - If the file was a PDF or TIFF, this field gives the page - number within the file used to produce the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.ImageAnnotationContext) - }, -) -_sym_db.RegisterMessage(ImageAnnotationContext) - -AnnotateImageResponse = _reflection.GeneratedProtocolMessageType( - "AnnotateImageResponse", - (_message.Message,), - { - "DESCRIPTOR": _ANNOTATEIMAGERESPONSE, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Response to an image annotation request. - - Attributes: - face_annotations: - If present, face detection has completed successfully. - landmark_annotations: - If present, landmark detection has completed successfully. - logo_annotations: - If present, logo detection has completed successfully. - label_annotations: - If present, label detection has completed successfully. - localized_object_annotations: - If present, localized object detection has completed - successfully. This will be sorted descending by confidence - score. - text_annotations: - If present, text (OCR) detection has completed successfully. - full_text_annotation: - If present, text (OCR) detection or document (OCR) text - detection has completed successfully. This annotation provides - the structural hierarchy for the OCR detected text. - safe_search_annotation: - If present, safe-search annotation has completed successfully. - image_properties_annotation: - If present, image properties were extracted successfully. - crop_hints_annotation: - If present, crop hints have completed successfully. - web_detection: - If present, web detection has completed successfully. - product_search_results: - If present, product search has completed successfully. - error: - If set, represents the error message for the operation. Note - that filled-in image annotations are guaranteed to be correct, - even when ``error`` is set. - context: - If present, contextual information is needed to understand - where this image comes from. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.AnnotateImageResponse) - }, -) -_sym_db.RegisterMessage(AnnotateImageResponse) - -BatchAnnotateImagesRequest = _reflection.GeneratedProtocolMessageType( - "BatchAnnotateImagesRequest", - (_message.Message,), - { - "DESCRIPTOR": _BATCHANNOTATEIMAGESREQUEST, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Multiple image annotation requests are batched into a single service - call. - - Attributes: - requests: - Required. Individual image annotation requests for this batch. - parent: - Optional. Target project and location to make a call. Format: - ``projects/{project-id}/locations/{location-id}``. If no - parent is specified, a region will be chosen automatically. - Supported location-ids: ``us``: USA country only, ``asia``: - East asia areas, like Japan, Taiwan, ``eu``: The European - Union. Example: ``projects/project-A/locations/eu``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.BatchAnnotateImagesRequest) - }, -) -_sym_db.RegisterMessage(BatchAnnotateImagesRequest) - -BatchAnnotateImagesResponse = _reflection.GeneratedProtocolMessageType( - "BatchAnnotateImagesResponse", - (_message.Message,), - { - "DESCRIPTOR": _BATCHANNOTATEIMAGESRESPONSE, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Response to a batch image annotation request. - - Attributes: - responses: - Individual responses to image annotation requests within the - batch. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.BatchAnnotateImagesResponse) - }, -) -_sym_db.RegisterMessage(BatchAnnotateImagesResponse) - -AnnotateFileRequest = _reflection.GeneratedProtocolMessageType( - "AnnotateFileRequest", - (_message.Message,), - { - "DESCRIPTOR": _ANNOTATEFILEREQUEST, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """A request to annotate one single file, e.g. a PDF, TIFF or GIF file. - - Attributes: - input_config: - Required. Information about the input file. - features: - Required. Requested features. - image_context: - Additional context that may accompany the image(s) in the - file. - pages: - Pages of the file to perform image annotation. Pages starts - from 1, we assume the first page of the file is page 1. At - most 5 pages are supported per request. Pages can be negative. - Page 1 means the first page. Page 2 means the second page. - Page -1 means the last page. Page -2 means the second to the - last page. If the file is GIF instead of PDF or TIFF, page - refers to GIF frames. If this field is empty, by default the - service performs image annotation for the first 5 pages of the - file. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.AnnotateFileRequest) - }, -) -_sym_db.RegisterMessage(AnnotateFileRequest) - -AnnotateFileResponse = _reflection.GeneratedProtocolMessageType( - "AnnotateFileResponse", - (_message.Message,), - { - "DESCRIPTOR": _ANNOTATEFILERESPONSE, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Response to a single file annotation request. A file may contain one - or more images, which individually have their own responses. - - Attributes: - input_config: - Information about the file for which this response is - generated. - responses: - Individual responses to images found within the file. This - field will be empty if the ``error`` field is set. - total_pages: - This field gives the total number of pages in the file. - error: - If set, represents the error message for the failed request. - The ``responses`` field will not be set in this case. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.AnnotateFileResponse) - }, -) -_sym_db.RegisterMessage(AnnotateFileResponse) - -BatchAnnotateFilesRequest = _reflection.GeneratedProtocolMessageType( - "BatchAnnotateFilesRequest", - (_message.Message,), - { - "DESCRIPTOR": _BATCHANNOTATEFILESREQUEST, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """A list of requests to annotate files using the BatchAnnotateFiles API. - - Attributes: - requests: - Required. The list of file annotation requests. Right now we - support only one AnnotateFileRequest in - BatchAnnotateFilesRequest. - parent: - Optional. Target project and location to make a call. Format: - ``projects/{project-id}/locations/{location-id}``. If no - parent is specified, a region will be chosen automatically. - Supported location-ids: ``us``: USA country only, ``asia``: - East asia areas, like Japan, Taiwan, ``eu``: The European - Union. Example: ``projects/project-A/locations/eu``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.BatchAnnotateFilesRequest) - }, -) -_sym_db.RegisterMessage(BatchAnnotateFilesRequest) - -BatchAnnotateFilesResponse = _reflection.GeneratedProtocolMessageType( - "BatchAnnotateFilesResponse", - (_message.Message,), - { - "DESCRIPTOR": _BATCHANNOTATEFILESRESPONSE, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """A list of file annotation responses. - - Attributes: - responses: - The list of file annotation responses, each response - corresponding to each AnnotateFileRequest in - BatchAnnotateFilesRequest. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.BatchAnnotateFilesResponse) - }, -) -_sym_db.RegisterMessage(BatchAnnotateFilesResponse) - -AsyncAnnotateFileRequest = _reflection.GeneratedProtocolMessageType( - "AsyncAnnotateFileRequest", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCANNOTATEFILEREQUEST, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """An offline file annotation request. - - Attributes: - input_config: - Required. Information about the input file. - features: - Required. Requested features. - image_context: - Additional context that may accompany the image(s) in the - file. - output_config: - Required. The desired output location and metadata - (e.g. format). - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.AsyncAnnotateFileRequest) - }, -) -_sym_db.RegisterMessage(AsyncAnnotateFileRequest) - -AsyncAnnotateFileResponse = _reflection.GeneratedProtocolMessageType( - "AsyncAnnotateFileResponse", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCANNOTATEFILERESPONSE, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """The response for a single offline file annotation request. - - Attributes: - output_config: - The output location and metadata from - AsyncAnnotateFileRequest. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.AsyncAnnotateFileResponse) - }, -) -_sym_db.RegisterMessage(AsyncAnnotateFileResponse) - -AsyncBatchAnnotateImagesRequest = _reflection.GeneratedProtocolMessageType( - "AsyncBatchAnnotateImagesRequest", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCBATCHANNOTATEIMAGESREQUEST, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Request for async image annotation for a list of images. - - Attributes: - requests: - Required. Individual image annotation requests for this batch. - output_config: - Required. The desired output location and metadata - (e.g. format). - parent: - Optional. Target project and location to make a call. Format: - ``projects/{project-id}/locations/{location-id}``. If no - parent is specified, a region will be chosen automatically. - Supported location-ids: ``us``: USA country only, ``asia``: - East asia areas, like Japan, Taiwan, ``eu``: The European - Union. Example: ``projects/project-A/locations/eu``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.AsyncBatchAnnotateImagesRequest) - }, -) -_sym_db.RegisterMessage(AsyncBatchAnnotateImagesRequest) - -AsyncBatchAnnotateImagesResponse = _reflection.GeneratedProtocolMessageType( - "AsyncBatchAnnotateImagesResponse", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCBATCHANNOTATEIMAGESRESPONSE, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Response to an async batch image annotation request. - - Attributes: - output_config: - The output location and metadata from - AsyncBatchAnnotateImagesRequest. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.AsyncBatchAnnotateImagesResponse) - }, -) -_sym_db.RegisterMessage(AsyncBatchAnnotateImagesResponse) - -AsyncBatchAnnotateFilesRequest = _reflection.GeneratedProtocolMessageType( - "AsyncBatchAnnotateFilesRequest", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCBATCHANNOTATEFILESREQUEST, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Multiple async file annotation requests are batched into a single - service call. - - Attributes: - requests: - Required. Individual async file annotation requests for this - batch. - parent: - Optional. Target project and location to make a call. Format: - ``projects/{project-id}/locations/{location-id}``. If no - parent is specified, a region will be chosen automatically. - Supported location-ids: ``us``: USA country only, ``asia``: - East asia areas, like Japan, Taiwan, ``eu``: The European - Union. Example: ``projects/project-A/locations/eu``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.AsyncBatchAnnotateFilesRequest) - }, -) -_sym_db.RegisterMessage(AsyncBatchAnnotateFilesRequest) - -AsyncBatchAnnotateFilesResponse = _reflection.GeneratedProtocolMessageType( - "AsyncBatchAnnotateFilesResponse", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCBATCHANNOTATEFILESRESPONSE, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Response to an async batch file annotation request. - - Attributes: - responses: - The list of file annotation responses, one for each request in - AsyncBatchAnnotateFilesRequest. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.AsyncBatchAnnotateFilesResponse) - }, -) -_sym_db.RegisterMessage(AsyncBatchAnnotateFilesResponse) - -InputConfig = _reflection.GeneratedProtocolMessageType( - "InputConfig", - (_message.Message,), - { - "DESCRIPTOR": _INPUTCONFIG, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """The desired input location and metadata. - - Attributes: - gcs_source: - The Google Cloud Storage location to read the input from. - content: - File content, represented as a stream of bytes. Note: As with - all ``bytes`` fields, protobuffers use a pure binary - representation, whereas JSON representations use base64. - Currently, this field only works for BatchAnnotateFiles - requests. It does not work for AsyncBatchAnnotateFiles - requests. - mime_type: - The type of the file. Currently only “application/pdf”, - “image/tiff” and “image/gif” are supported. Wildcards are not - supported. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.InputConfig) - }, -) -_sym_db.RegisterMessage(InputConfig) - -OutputConfig = _reflection.GeneratedProtocolMessageType( - "OutputConfig", - (_message.Message,), - { - "DESCRIPTOR": _OUTPUTCONFIG, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """The desired output location and metadata. - - Attributes: - gcs_destination: - The Google Cloud Storage location to write the output(s) to. - batch_size: - The max number of response protos to put into each output JSON - file on Google Cloud Storage. The valid range is [1, 100]. If - not specified, the default value is 20. For example, for one - pdf file with 100 pages, 100 response protos will be - generated. If ``batch_size`` = 20, then 5 json files each - containing 20 response protos will be written under the prefix - ``gcs_destination``.\ ``uri``. Currently, batch_size only - applies to GcsDestination, with potential future support for - other output configurations. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.OutputConfig) - }, -) -_sym_db.RegisterMessage(OutputConfig) - -GcsSource = _reflection.GeneratedProtocolMessageType( - "GcsSource", - (_message.Message,), - { - "DESCRIPTOR": _GCSSOURCE, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """The Google Cloud Storage location where the input will be read from. - - Attributes: - uri: - Google Cloud Storage URI for the input file. This must only be - a Google Cloud Storage object. Wildcards are not currently - supported. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.GcsSource) - }, -) -_sym_db.RegisterMessage(GcsSource) - -GcsDestination = _reflection.GeneratedProtocolMessageType( - "GcsDestination", - (_message.Message,), - { - "DESCRIPTOR": _GCSDESTINATION, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """The Google Cloud Storage location where the output will be written to. - - Attributes: - uri: - Google Cloud Storage URI prefix where the results will be - stored. Results will be in JSON format and preceded by its - corresponding input URI prefix. This field can either - represent a gcs file prefix or gcs directory. In either case, - the uri should be unique because in order to get all of the - output files, you will need to do a wildcard gcs search on the - uri prefix you provide. Examples: - File Prefix: - gs://bucket-name/here/filenameprefix The output files will - be created in gs://bucket-name/here/ and the names of the - output files will begin with “filenameprefix”. - - Directory Prefix: gs://bucket-name/some/location/ The output - files will be created in gs://bucket-name/some/location/ - and the names of the output files could be anything because - there was no filename prefix specified. If multiple - outputs, each response is still AnnotateFileResponse, each of - which contains some subset of the full list of - AnnotateImageResponse. Multiple outputs can happen if, for - example, the output JSON is too large and overflows into - multiple sharded files. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.GcsDestination) - }, -) -_sym_db.RegisterMessage(GcsDestination) - -OperationMetadata = _reflection.GeneratedProtocolMessageType( - "OperationMetadata", - (_message.Message,), - { - "DESCRIPTOR": _OPERATIONMETADATA, - "__module__": "google.cloud.vision_v1.proto.image_annotator_pb2", - "__doc__": """Contains metadata for the BatchAnnotateImages operation. - - Attributes: - state: - Current state of the batch operation. - create_time: - The time when the batch request was received. - update_time: - The time when the operation result was last updated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.OperationMetadata) - }, -) -_sym_db.RegisterMessage(OperationMetadata) - - -DESCRIPTOR._options = None -_ENTITYANNOTATION.fields_by_name["confidence"]._options = None -_BATCHANNOTATEIMAGESREQUEST.fields_by_name["requests"]._options = None -_BATCHANNOTATEFILESREQUEST.fields_by_name["requests"]._options = None -_ASYNCBATCHANNOTATEIMAGESREQUEST.fields_by_name["requests"]._options = None -_ASYNCBATCHANNOTATEIMAGESREQUEST.fields_by_name["output_config"]._options = None -_ASYNCBATCHANNOTATEFILESREQUEST.fields_by_name["requests"]._options = None - -_IMAGEANNOTATOR = _descriptor.ServiceDescriptor( - name="ImageAnnotator", - full_name="google.cloud.vision.v1.ImageAnnotator", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\025vision.googleapis.com\322A[https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-vision", - create_key=_descriptor._internal_create_key, - serialized_start=8376, - serialized_end=9773, - methods=[ - _descriptor.MethodDescriptor( - name="BatchAnnotateImages", - full_name="google.cloud.vision.v1.ImageAnnotator.BatchAnnotateImages", - index=0, - containing_service=None, - input_type=_BATCHANNOTATEIMAGESREQUEST, - output_type=_BATCHANNOTATEIMAGESRESPONSE, - serialized_options=b'\202\323\344\223\002\200\001"\023/v1/images:annotate:\001*Z8"3/v1/{parent=projects/*/locations/*}/images:annotate:\001*Z,"\'/v1/{parent=projects/*}/images:annotate:\001*\332A\010requests', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="BatchAnnotateFiles", - full_name="google.cloud.vision.v1.ImageAnnotator.BatchAnnotateFiles", - index=1, - containing_service=None, - input_type=_BATCHANNOTATEFILESREQUEST, - output_type=_BATCHANNOTATEFILESRESPONSE, - serialized_options=b'\202\323\344\223\002}"\022/v1/files:annotate:\001*Z7"2/v1/{parent=projects/*/locations/*}/files:annotate:\001*Z+"&/v1/{parent=projects/*}/files:annotate:\001*\332A\010requests', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="AsyncBatchAnnotateImages", - full_name="google.cloud.vision.v1.ImageAnnotator.AsyncBatchAnnotateImages", - index=2, - containing_service=None, - input_type=_ASYNCBATCHANNOTATEIMAGESREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002\236\001"\035/v1/images:asyncBatchAnnotate:\001*ZB"=/v1/{parent=projects/*/locations/*}/images:asyncBatchAnnotate:\001*Z6"1/v1/{parent=projects/*}/images:asyncBatchAnnotate:\001*\332A\026requests,output_config\312A5\n AsyncBatchAnnotateImagesResponse\022\021OperationMetadata', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="AsyncBatchAnnotateFiles", - full_name="google.cloud.vision.v1.ImageAnnotator.AsyncBatchAnnotateFiles", - index=3, - containing_service=None, - input_type=_ASYNCBATCHANNOTATEFILESREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002\233\001"\034/v1/files:asyncBatchAnnotate:\001*ZA""//v1/{parent=projects/*/locations/*}/productSets:\x0bproduct_set\xda\x41!parent,product_set,product_set_id\x12\xb4\x01\n\x0fListProductSets\x12..google.cloud.vision.v1.ListProductSetsRequest\x1a/.google.cloud.vision.v1.ListProductSetsResponse"@\x82\xd3\xe4\x93\x02\x31\x12//v1/{parent=projects/*/locations/*}/productSets\xda\x41\x06parent\x12\xa1\x01\n\rGetProductSet\x12,.google.cloud.vision.v1.GetProductSetRequest\x1a".google.cloud.vision.v1.ProductSet">\x82\xd3\xe4\x93\x02\x31\x12//v1/{name=projects/*/locations/*/productSets/*}\xda\x41\x04name\x12\xd3\x01\n\x10UpdateProductSet\x12/.google.cloud.vision.v1.UpdateProductSetRequest\x1a".google.cloud.vision.v1.ProductSet"j\x82\xd3\xe4\x93\x02J2;/v1/{product_set.name=projects/*/locations/*/productSets/*}:\x0bproduct_set\xda\x41\x17product_set,update_mask\x12\x9b\x01\n\x10\x44\x65leteProductSet\x12/.google.cloud.vision.v1.DeleteProductSetRequest\x1a\x16.google.protobuf.Empty">\x82\xd3\xe4\x93\x02\x31*//v1/{name=projects/*/locations/*/productSets/*}\xda\x41\x04name\x12\xb9\x01\n\rCreateProduct\x12,.google.cloud.vision.v1.CreateProductRequest\x1a\x1f.google.cloud.vision.v1.Product"Y\x82\xd3\xe4\x93\x02\x37",/v1/{parent=projects/*/locations/*}/products:\x07product\xda\x41\x19parent,product,product_id\x12\xa8\x01\n\x0cListProducts\x12+.google.cloud.vision.v1.ListProductsRequest\x1a,.google.cloud.vision.v1.ListProductsResponse"=\x82\xd3\xe4\x93\x02.\x12,/v1/{parent=projects/*/locations/*}/products\xda\x41\x06parent\x12\x95\x01\n\nGetProduct\x12).google.cloud.vision.v1.GetProductRequest\x1a\x1f.google.cloud.vision.v1.Product";\x82\xd3\xe4\x93\x02.\x12,/v1/{name=projects/*/locations/*/products/*}\xda\x41\x04name\x12\xbb\x01\n\rUpdateProduct\x12,.google.cloud.vision.v1.UpdateProductRequest\x1a\x1f.google.cloud.vision.v1.Product"[\x82\xd3\xe4\x93\x02?24/v1/{product.name=projects/*/locations/*/products/*}:\x07product\xda\x41\x13product,update_mask\x12\x92\x01\n\rDeleteProduct\x12,.google.cloud.vision.v1.DeleteProductRequest\x1a\x16.google.protobuf.Empty";\x82\xd3\xe4\x93\x02.*,/v1/{name=projects/*/locations/*/products/*}\xda\x41\x04name\x12\xf9\x01\n\x14\x43reateReferenceImage\x12\x33.google.cloud.vision.v1.CreateReferenceImageRequest\x1a&.google.cloud.vision.v1.ReferenceImage"\x83\x01\x82\xd3\xe4\x93\x02Q">/v1/{parent=projects/*/locations/*/products/*}/referenceImages:\x0freference_image\xda\x41)parent,reference_image,reference_image_id\x12\xb2\x01\n\x14\x44\x65leteReferenceImage\x12\x33.google.cloud.vision.v1.DeleteReferenceImageRequest\x1a\x16.google.protobuf.Empty"M\x82\xd3\xe4\x93\x02@*>/v1/{name=projects/*/locations/*/products/*/referenceImages/*}\xda\x41\x04name\x12\xcf\x01\n\x13ListReferenceImages\x12\x32.google.cloud.vision.v1.ListReferenceImagesRequest\x1a\x33.google.cloud.vision.v1.ListReferenceImagesResponse"O\x82\xd3\xe4\x93\x02@\x12>/v1/{parent=projects/*/locations/*/products/*}/referenceImages\xda\x41\x06parent\x12\xbc\x01\n\x11GetReferenceImage\x12\x30.google.cloud.vision.v1.GetReferenceImageRequest\x1a&.google.cloud.vision.v1.ReferenceImage"M\x82\xd3\xe4\x93\x02@\x12>/v1/{name=projects/*/locations/*/products/*/referenceImages/*}\xda\x41\x04name\x12\xbd\x01\n\x16\x41\x64\x64ProductToProductSet\x12\x35.google.cloud.vision.v1.AddProductToProductSetRequest\x1a\x16.google.protobuf.Empty"T\x82\xd3\xe4\x93\x02?":/v1/{name=projects/*/locations/*/productSets/*}:addProduct:\x01*\xda\x41\x0cname,product\x12\xca\x01\n\x1bRemoveProductFromProductSet\x12:.google.cloud.vision.v1.RemoveProductFromProductSetRequest\x1a\x16.google.protobuf.Empty"W\x82\xd3\xe4\x93\x02\x42"=/v1/{name=projects/*/locations/*/productSets/*}:removeProduct:\x01*\xda\x41\x0cname,product\x12\xd6\x01\n\x18ListProductsInProductSet\x12\x37.google.cloud.vision.v1.ListProductsInProductSetRequest\x1a\x38.google.cloud.vision.v1.ListProductsInProductSetResponse"G\x82\xd3\xe4\x93\x02:\x12\x38/v1/{name=projects/*/locations/*/productSets/*}/products\xda\x41\x04name\x12\xf4\x01\n\x11ImportProductSets\x12\x30.google.cloud.vision.v1.ImportProductSetsRequest\x1a\x1d.google.longrunning.Operation"\x8d\x01\x82\xd3\xe4\x93\x02;"6/v1/{parent=projects/*/locations/*}/productSets:import:\x01*\xda\x41\x13parent,input_config\xca\x41\x33\n\x19ImportProductSetsResponse\x12\x16\x42\x61tchOperationMetadata\x12\xd6\x01\n\rPurgeProducts\x12,.google.cloud.vision.v1.PurgeProductsRequest\x1a\x1d.google.longrunning.Operation"x\x82\xd3\xe4\x93\x02\x37"2/v1/{parent=projects/*/locations/*}/products:purge:\x01*\xda\x41\x06parent\xca\x41/\n\x15google.protobuf.Empty\x12\x16\x42\x61tchOperationMetadata\x1av\xca\x41\x15vision.googleapis.com\xd2\x41[https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-visionB\x81\x01\n\x1a\x63om.google.cloud.vision.v1B\x19ProductSearchServiceProtoP\x01Z"//v1/{parent=projects/*/locations/*}/productSets:\013product_set\332A!parent,product_set,product_set_id', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListProductSets", - full_name="google.cloud.vision.v1.ProductSearch.ListProductSets", - index=1, - containing_service=None, - input_type=_LISTPRODUCTSETSREQUEST, - output_type=_LISTPRODUCTSETSRESPONSE, - serialized_options=b"\202\323\344\223\0021\022//v1/{parent=projects/*/locations/*}/productSets\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetProductSet", - full_name="google.cloud.vision.v1.ProductSearch.GetProductSet", - index=2, - containing_service=None, - input_type=_GETPRODUCTSETREQUEST, - output_type=_PRODUCTSET, - serialized_options=b"\202\323\344\223\0021\022//v1/{name=projects/*/locations/*/productSets/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateProductSet", - full_name="google.cloud.vision.v1.ProductSearch.UpdateProductSet", - index=3, - containing_service=None, - input_type=_UPDATEPRODUCTSETREQUEST, - output_type=_PRODUCTSET, - serialized_options=b"\202\323\344\223\002J2;/v1/{product_set.name=projects/*/locations/*/productSets/*}:\013product_set\332A\027product_set,update_mask", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteProductSet", - full_name="google.cloud.vision.v1.ProductSearch.DeleteProductSet", - index=4, - containing_service=None, - input_type=_DELETEPRODUCTSETREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\0021*//v1/{name=projects/*/locations/*/productSets/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateProduct", - full_name="google.cloud.vision.v1.ProductSearch.CreateProduct", - index=5, - containing_service=None, - input_type=_CREATEPRODUCTREQUEST, - output_type=_PRODUCT, - serialized_options=b'\202\323\344\223\0027",/v1/{parent=projects/*/locations/*}/products:\007product\332A\031parent,product,product_id', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListProducts", - full_name="google.cloud.vision.v1.ProductSearch.ListProducts", - index=6, - containing_service=None, - input_type=_LISTPRODUCTSREQUEST, - output_type=_LISTPRODUCTSRESPONSE, - serialized_options=b"\202\323\344\223\002.\022,/v1/{parent=projects/*/locations/*}/products\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetProduct", - full_name="google.cloud.vision.v1.ProductSearch.GetProduct", - index=7, - containing_service=None, - input_type=_GETPRODUCTREQUEST, - output_type=_PRODUCT, - serialized_options=b"\202\323\344\223\002.\022,/v1/{name=projects/*/locations/*/products/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateProduct", - full_name="google.cloud.vision.v1.ProductSearch.UpdateProduct", - index=8, - containing_service=None, - input_type=_UPDATEPRODUCTREQUEST, - output_type=_PRODUCT, - serialized_options=b"\202\323\344\223\002?24/v1/{product.name=projects/*/locations/*/products/*}:\007product\332A\023product,update_mask", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteProduct", - full_name="google.cloud.vision.v1.ProductSearch.DeleteProduct", - index=9, - containing_service=None, - input_type=_DELETEPRODUCTREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\002.*,/v1/{name=projects/*/locations/*/products/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateReferenceImage", - full_name="google.cloud.vision.v1.ProductSearch.CreateReferenceImage", - index=10, - containing_service=None, - input_type=_CREATEREFERENCEIMAGEREQUEST, - output_type=_REFERENCEIMAGE, - serialized_options=b'\202\323\344\223\002Q">/v1/{parent=projects/*/locations/*/products/*}/referenceImages:\017reference_image\332A)parent,reference_image,reference_image_id', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteReferenceImage", - full_name="google.cloud.vision.v1.ProductSearch.DeleteReferenceImage", - index=11, - containing_service=None, - input_type=_DELETEREFERENCEIMAGEREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\002@*>/v1/{name=projects/*/locations/*/products/*/referenceImages/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListReferenceImages", - full_name="google.cloud.vision.v1.ProductSearch.ListReferenceImages", - index=12, - containing_service=None, - input_type=_LISTREFERENCEIMAGESREQUEST, - output_type=_LISTREFERENCEIMAGESRESPONSE, - serialized_options=b"\202\323\344\223\002@\022>/v1/{parent=projects/*/locations/*/products/*}/referenceImages\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetReferenceImage", - full_name="google.cloud.vision.v1.ProductSearch.GetReferenceImage", - index=13, - containing_service=None, - input_type=_GETREFERENCEIMAGEREQUEST, - output_type=_REFERENCEIMAGE, - serialized_options=b"\202\323\344\223\002@\022>/v1/{name=projects/*/locations/*/products/*/referenceImages/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="AddProductToProductSet", - full_name="google.cloud.vision.v1.ProductSearch.AddProductToProductSet", - index=14, - containing_service=None, - input_type=_ADDPRODUCTTOPRODUCTSETREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b'\202\323\344\223\002?":/v1/{name=projects/*/locations/*/productSets/*}:addProduct:\001*\332A\014name,product', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="RemoveProductFromProductSet", - full_name="google.cloud.vision.v1.ProductSearch.RemoveProductFromProductSet", - index=15, - containing_service=None, - input_type=_REMOVEPRODUCTFROMPRODUCTSETREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b'\202\323\344\223\002B"=/v1/{name=projects/*/locations/*/productSets/*}:removeProduct:\001*\332A\014name,product', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListProductsInProductSet", - full_name="google.cloud.vision.v1.ProductSearch.ListProductsInProductSet", - index=16, - containing_service=None, - input_type=_LISTPRODUCTSINPRODUCTSETREQUEST, - output_type=_LISTPRODUCTSINPRODUCTSETRESPONSE, - serialized_options=b"\202\323\344\223\002:\0228/v1/{name=projects/*/locations/*/productSets/*}/products\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ImportProductSets", - full_name="google.cloud.vision.v1.ProductSearch.ImportProductSets", - index=17, - containing_service=None, - input_type=_IMPORTPRODUCTSETSREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002;"6/v1/{parent=projects/*/locations/*}/productSets:import:\001*\332A\023parent,input_config\312A3\n\031ImportProductSetsResponse\022\026BatchOperationMetadata', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="PurgeProducts", - full_name="google.cloud.vision.v1.ProductSearch.PurgeProducts", - index=18, - containing_service=None, - input_type=_PURGEPRODUCTSREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\0027"2/v1/{parent=projects/*/locations/*}/products:purge:\001*\332A\006parent\312A/\n\025google.protobuf.Empty\022\026BatchOperationMetadata', - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_PRODUCTSEARCH) - -DESCRIPTOR.services_by_name["ProductSearch"] = _PRODUCTSEARCH - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1/proto/product_search_service_pb2_grpc.py b/google/cloud/vision_v1/proto/product_search_service_pb2_grpc.py deleted file mode 100644 index 61dd1660..00000000 --- a/google/cloud/vision_v1/proto/product_search_service_pb2_grpc.py +++ /dev/null @@ -1,1055 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.vision_v1.proto import ( - product_search_service_pb2 as google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 - - -class ProductSearchStub(object): - """Manages Products and ProductSets of reference images for use in product - search. It uses the following resource model: - - - The API has a collection of [ProductSet][google.cloud.vision.v1.ProductSet] resources, named - `projects/*/locations/*/productSets/*`, which acts as a way to put different - products into groups to limit identification. - - In parallel, - - - The API has a collection of [Product][google.cloud.vision.v1.Product] resources, named - `projects/*/locations/*/products/*` - - - Each [Product][google.cloud.vision.v1.Product] has a collection of [ReferenceImage][google.cloud.vision.v1.ReferenceImage] resources, named - `projects/*/locations/*/products/*/referenceImages/*` - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.CreateProductSet = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/CreateProductSet", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.CreateProductSetRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - ) - self.ListProductSets = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/ListProductSets", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductSetsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductSetsResponse.FromString, - ) - self.GetProductSet = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/GetProductSet", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.GetProductSetRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - ) - self.UpdateProductSet = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/UpdateProductSet", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.UpdateProductSetRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - ) - self.DeleteProductSet = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/DeleteProductSet", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.DeleteProductSetRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.CreateProduct = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/CreateProduct", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.CreateProductRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.Product.FromString, - ) - self.ListProducts = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/ListProducts", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductsResponse.FromString, - ) - self.GetProduct = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/GetProduct", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.GetProductRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.Product.FromString, - ) - self.UpdateProduct = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/UpdateProduct", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.UpdateProductRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.Product.FromString, - ) - self.DeleteProduct = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/DeleteProduct", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.DeleteProductRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.CreateReferenceImage = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/CreateReferenceImage", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.CreateReferenceImageRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ReferenceImage.FromString, - ) - self.DeleteReferenceImage = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/DeleteReferenceImage", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.DeleteReferenceImageRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.ListReferenceImages = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/ListReferenceImages", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesResponse.FromString, - ) - self.GetReferenceImage = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/GetReferenceImage", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.GetReferenceImageRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ReferenceImage.FromString, - ) - self.AddProductToProductSet = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/AddProductToProductSet", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.AddProductToProductSetRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.RemoveProductFromProductSet = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/RemoveProductFromProductSet", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.RemoveProductFromProductSetRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.ListProductsInProductSet = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/ListProductsInProductSet", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetResponse.FromString, - ) - self.ImportProductSets = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/ImportProductSets", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ImportProductSetsRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - self.PurgeProducts = channel.unary_unary( - "/google.cloud.vision.v1.ProductSearch/PurgeProducts", - request_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.PurgeProductsRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - - -class ProductSearchServicer(object): - """Manages Products and ProductSets of reference images for use in product - search. It uses the following resource model: - - - The API has a collection of [ProductSet][google.cloud.vision.v1.ProductSet] resources, named - `projects/*/locations/*/productSets/*`, which acts as a way to put different - products into groups to limit identification. - - In parallel, - - - The API has a collection of [Product][google.cloud.vision.v1.Product] resources, named - `projects/*/locations/*/products/*` - - - Each [Product][google.cloud.vision.v1.Product] has a collection of [ReferenceImage][google.cloud.vision.v1.ReferenceImage] resources, named - `projects/*/locations/*/products/*/referenceImages/*` - """ - - def CreateProductSet(self, request, context): - """Creates and returns a new ProductSet resource. - - Possible errors: - - * Returns INVALID_ARGUMENT if display_name is missing, or is longer than - 4096 characters. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListProductSets(self, request, context): - """Lists ProductSets in an unspecified order. - - Possible errors: - - * Returns INVALID_ARGUMENT if page_size is greater than 100, or less - than 1. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetProductSet(self, request, context): - """Gets information associated with a ProductSet. - - Possible errors: - - * Returns NOT_FOUND if the ProductSet does not exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateProductSet(self, request, context): - """Makes changes to a ProductSet resource. - Only display_name can be updated currently. - - Possible errors: - - * Returns NOT_FOUND if the ProductSet does not exist. - * Returns INVALID_ARGUMENT if display_name is present in update_mask but - missing from the request or longer than 4096 characters. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteProductSet(self, request, context): - """Permanently deletes a ProductSet. Products and ReferenceImages in the - ProductSet are not deleted. - - The actual image files are not deleted from Google Cloud Storage. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateProduct(self, request, context): - """Creates and returns a new product resource. - - Possible errors: - - * Returns INVALID_ARGUMENT if display_name is missing or longer than 4096 - characters. - * Returns INVALID_ARGUMENT if description is longer than 4096 characters. - * Returns INVALID_ARGUMENT if product_category is missing or invalid. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListProducts(self, request, context): - """Lists products in an unspecified order. - - Possible errors: - - * Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetProduct(self, request, context): - """Gets information associated with a Product. - - Possible errors: - - * Returns NOT_FOUND if the Product does not exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateProduct(self, request, context): - """Makes changes to a Product resource. - Only the `display_name`, `description`, and `labels` fields can be updated - right now. - - If labels are updated, the change will not be reflected in queries until - the next index time. - - Possible errors: - - * Returns NOT_FOUND if the Product does not exist. - * Returns INVALID_ARGUMENT if display_name is present in update_mask but is - missing from the request or longer than 4096 characters. - * Returns INVALID_ARGUMENT if description is present in update_mask but is - longer than 4096 characters. - * Returns INVALID_ARGUMENT if product_category is present in update_mask. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteProduct(self, request, context): - """Permanently deletes a product and its reference images. - - Metadata of the product and all its images will be deleted right away, but - search queries against ProductSets containing the product may still work - until all related caches are refreshed. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateReferenceImage(self, request, context): - """Creates and returns a new ReferenceImage resource. - - The `bounding_poly` field is optional. If `bounding_poly` is not specified, - the system will try to detect regions of interest in the image that are - compatible with the product_category on the parent product. If it is - specified, detection is ALWAYS skipped. The system converts polygons into - non-rotated rectangles. - - Note that the pipeline will resize the image if the image resolution is too - large to process (above 50MP). - - Possible errors: - - * Returns INVALID_ARGUMENT if the image_uri is missing or longer than 4096 - characters. - * Returns INVALID_ARGUMENT if the product does not exist. - * Returns INVALID_ARGUMENT if bounding_poly is not provided, and nothing - compatible with the parent product's product_category is detected. - * Returns INVALID_ARGUMENT if bounding_poly contains more than 10 polygons. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteReferenceImage(self, request, context): - """Permanently deletes a reference image. - - The image metadata will be deleted right away, but search queries - against ProductSets containing the image may still work until all related - caches are refreshed. - - The actual image files are not deleted from Google Cloud Storage. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListReferenceImages(self, request, context): - """Lists reference images. - - Possible errors: - - * Returns NOT_FOUND if the parent product does not exist. - * Returns INVALID_ARGUMENT if the page_size is greater than 100, or less - than 1. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetReferenceImage(self, request, context): - """Gets information associated with a ReferenceImage. - - Possible errors: - - * Returns NOT_FOUND if the specified image does not exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def AddProductToProductSet(self, request, context): - """Adds a Product to the specified ProductSet. If the Product is already - present, no change is made. - - One Product can be added to at most 100 ProductSets. - - Possible errors: - - * Returns NOT_FOUND if the Product or the ProductSet doesn't exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def RemoveProductFromProductSet(self, request, context): - """Removes a Product from the specified ProductSet. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListProductsInProductSet(self, request, context): - """Lists the Products in a ProductSet, in an unspecified order. If the - ProductSet does not exist, the products field of the response will be - empty. - - Possible errors: - - * Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ImportProductSets(self, request, context): - """Asynchronous API that imports a list of reference images to specified - product sets based on a list of image information. - - The [google.longrunning.Operation][google.longrunning.Operation] API can be used to keep track of the - progress and results of the request. - `Operation.metadata` contains `BatchOperationMetadata`. (progress) - `Operation.response` contains `ImportProductSetsResponse`. (results) - - The input source of this method is a csv file on Google Cloud Storage. - For the format of the csv file please see - [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1.ImportProductSetsGcsSource.csv_file_uri]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def PurgeProducts(self, request, context): - """Asynchronous API to delete all Products in a ProductSet or all Products - that are in no ProductSet. - - If a Product is a member of the specified ProductSet in addition to other - ProductSets, the Product will still be deleted. - - It is recommended to not delete the specified ProductSet until after this - operation has completed. It is also recommended to not add any of the - Products involved in the batch delete to a new ProductSet while this - operation is running because those Products may still end up deleted. - - It's not possible to undo the PurgeProducts operation. Therefore, it is - recommended to keep the csv files used in ImportProductSets (if that was - how you originally built the Product Set) before starting PurgeProducts, in - case you need to re-import the data after deletion. - - If the plan is to purge all of the Products from a ProductSet and then - re-use the empty ProductSet to re-import new Products into the empty - ProductSet, you must wait until the PurgeProducts operation has finished - for that ProductSet. - - The [google.longrunning.Operation][google.longrunning.Operation] API can be used to keep track of the - progress and results of the request. - `Operation.metadata` contains `BatchOperationMetadata`. (progress) - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_ProductSearchServicer_to_server(servicer, server): - rpc_method_handlers = { - "CreateProductSet": grpc.unary_unary_rpc_method_handler( - servicer.CreateProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.CreateProductSetRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ProductSet.SerializeToString, - ), - "ListProductSets": grpc.unary_unary_rpc_method_handler( - servicer.ListProductSets, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductSetsRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductSetsResponse.SerializeToString, - ), - "GetProductSet": grpc.unary_unary_rpc_method_handler( - servicer.GetProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.GetProductSetRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ProductSet.SerializeToString, - ), - "UpdateProductSet": grpc.unary_unary_rpc_method_handler( - servicer.UpdateProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.UpdateProductSetRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ProductSet.SerializeToString, - ), - "DeleteProductSet": grpc.unary_unary_rpc_method_handler( - servicer.DeleteProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.DeleteProductSetRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "CreateProduct": grpc.unary_unary_rpc_method_handler( - servicer.CreateProduct, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.CreateProductRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.Product.SerializeToString, - ), - "ListProducts": grpc.unary_unary_rpc_method_handler( - servicer.ListProducts, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductsRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductsResponse.SerializeToString, - ), - "GetProduct": grpc.unary_unary_rpc_method_handler( - servicer.GetProduct, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.GetProductRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.Product.SerializeToString, - ), - "UpdateProduct": grpc.unary_unary_rpc_method_handler( - servicer.UpdateProduct, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.UpdateProductRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.Product.SerializeToString, - ), - "DeleteProduct": grpc.unary_unary_rpc_method_handler( - servicer.DeleteProduct, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.DeleteProductRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "CreateReferenceImage": grpc.unary_unary_rpc_method_handler( - servicer.CreateReferenceImage, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.CreateReferenceImageRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ReferenceImage.SerializeToString, - ), - "DeleteReferenceImage": grpc.unary_unary_rpc_method_handler( - servicer.DeleteReferenceImage, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.DeleteReferenceImageRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "ListReferenceImages": grpc.unary_unary_rpc_method_handler( - servicer.ListReferenceImages, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesResponse.SerializeToString, - ), - "GetReferenceImage": grpc.unary_unary_rpc_method_handler( - servicer.GetReferenceImage, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.GetReferenceImageRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ReferenceImage.SerializeToString, - ), - "AddProductToProductSet": grpc.unary_unary_rpc_method_handler( - servicer.AddProductToProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.AddProductToProductSetRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "RemoveProductFromProductSet": grpc.unary_unary_rpc_method_handler( - servicer.RemoveProductFromProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.RemoveProductFromProductSetRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "ListProductsInProductSet": grpc.unary_unary_rpc_method_handler( - servicer.ListProductsInProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetResponse.SerializeToString, - ), - "ImportProductSets": grpc.unary_unary_rpc_method_handler( - servicer.ImportProductSets, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ImportProductSetsRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - "PurgeProducts": grpc.unary_unary_rpc_method_handler( - servicer.PurgeProducts, - request_deserializer=google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.PurgeProductsRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.vision.v1.ProductSearch", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class ProductSearch(object): - """Manages Products and ProductSets of reference images for use in product - search. It uses the following resource model: - - - The API has a collection of [ProductSet][google.cloud.vision.v1.ProductSet] resources, named - `projects/*/locations/*/productSets/*`, which acts as a way to put different - products into groups to limit identification. - - In parallel, - - - The API has a collection of [Product][google.cloud.vision.v1.Product] resources, named - `projects/*/locations/*/products/*` - - - Each [Product][google.cloud.vision.v1.Product] has a collection of [ReferenceImage][google.cloud.vision.v1.ReferenceImage] resources, named - `projects/*/locations/*/products/*/referenceImages/*` - """ - - @staticmethod - def CreateProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/CreateProductSet", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.CreateProductSetRequest.SerializeToString, - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListProductSets( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/ListProductSets", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductSetsRequest.SerializeToString, - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductSetsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/GetProductSet", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.GetProductSetRequest.SerializeToString, - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/UpdateProductSet", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.UpdateProductSetRequest.SerializeToString, - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/DeleteProductSet", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.DeleteProductSetRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def CreateProduct( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/CreateProduct", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.CreateProductRequest.SerializeToString, - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.Product.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListProducts( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/ListProducts", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductsRequest.SerializeToString, - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetProduct( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/GetProduct", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.GetProductRequest.SerializeToString, - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.Product.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateProduct( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/UpdateProduct", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.UpdateProductRequest.SerializeToString, - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.Product.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteProduct( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/DeleteProduct", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.DeleteProductRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def CreateReferenceImage( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/CreateReferenceImage", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.CreateReferenceImageRequest.SerializeToString, - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ReferenceImage.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteReferenceImage( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/DeleteReferenceImage", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.DeleteReferenceImageRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListReferenceImages( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/ListReferenceImages", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesRequest.SerializeToString, - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetReferenceImage( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/GetReferenceImage", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.GetReferenceImageRequest.SerializeToString, - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ReferenceImage.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def AddProductToProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/AddProductToProductSet", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.AddProductToProductSetRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def RemoveProductFromProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/RemoveProductFromProductSet", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.RemoveProductFromProductSetRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListProductsInProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/ListProductsInProductSet", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetRequest.SerializeToString, - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ImportProductSets( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/ImportProductSets", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.ImportProductSetsRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def PurgeProducts( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1.ProductSearch/PurgeProducts", - google_dot_cloud_dot_vision__v1_dot_proto_dot_product__search__service__pb2.PurgeProductsRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/vision_v1/proto/text_annotation_pb2.py b/google/cloud/vision_v1/proto/text_annotation_pb2.py deleted file mode 100644 index 24a4021b..00000000 --- a/google/cloud/vision_v1/proto/text_annotation_pb2.py +++ /dev/null @@ -1,1224 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1/proto/text_annotation.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.cloud.vision_v1.proto import ( - geometry_pb2 as google_dot_cloud_dot_vision__v1_dot_proto_dot_geometry__pb2, -) -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1/proto/text_annotation.proto", - package="google.cloud.vision.v1", - syntax="proto3", - serialized_options=b"\n\032com.google.cloud.vision.v1B\023TextAnnotationProtoP\001Z.google.cloud.vision.v1.TextAnnotation.DetectedBreak.BreakType\x12\x11\n\tis_prefix\x18\x02 \x01(\x08"c\n\tBreakType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\t\n\x05SPACE\x10\x01\x12\x0e\n\nSURE_SPACE\x10\x02\x12\x12\n\x0e\x45OL_SURE_SPACE\x10\x03\x12\n\n\x06HYPHEN\x10\x04\x12\x0e\n\nLINE_BREAK\x10\x05\x1a\xb1\x01\n\x0cTextProperty\x12S\n\x12\x64\x65tected_languages\x18\x01 \x03(\x0b\x32\x37.google.cloud.vision.v1.TextAnnotation.DetectedLanguage\x12L\n\x0e\x64\x65tected_break\x18\x02 \x01(\x0b\x32\x34.google.cloud.vision.v1.TextAnnotation.DetectedBreak"\xaf\x01\n\x04Page\x12\x45\n\x08property\x18\x01 \x01(\x0b\x32\x33.google.cloud.vision.v1.TextAnnotation.TextProperty\x12\r\n\x05width\x18\x02 \x01(\x05\x12\x0e\n\x06height\x18\x03 \x01(\x05\x12-\n\x06\x62locks\x18\x04 \x03(\x0b\x32\x1d.google.cloud.vision.v1.Block\x12\x12\n\nconfidence\x18\x05 \x01(\x02"\xe6\x02\n\x05\x42lock\x12\x45\n\x08property\x18\x01 \x01(\x0b\x32\x33.google.cloud.vision.v1.TextAnnotation.TextProperty\x12:\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32$.google.cloud.vision.v1.BoundingPoly\x12\x35\n\nparagraphs\x18\x03 \x03(\x0b\x32!.google.cloud.vision.v1.Paragraph\x12;\n\nblock_type\x18\x04 \x01(\x0e\x32\'.google.cloud.vision.v1.Block.BlockType\x12\x12\n\nconfidence\x18\x05 \x01(\x02"R\n\tBlockType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x08\n\x04TEXT\x10\x01\x12\t\n\x05TABLE\x10\x02\x12\x0b\n\x07PICTURE\x10\x03\x12\t\n\x05RULER\x10\x04\x12\x0b\n\x07\x42\x41RCODE\x10\x05"\xcf\x01\n\tParagraph\x12\x45\n\x08property\x18\x01 \x01(\x0b\x32\x33.google.cloud.vision.v1.TextAnnotation.TextProperty\x12:\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32$.google.cloud.vision.v1.BoundingPoly\x12+\n\x05words\x18\x03 \x03(\x0b\x32\x1c.google.cloud.vision.v1.Word\x12\x12\n\nconfidence\x18\x04 \x01(\x02"\xce\x01\n\x04Word\x12\x45\n\x08property\x18\x01 \x01(\x0b\x32\x33.google.cloud.vision.v1.TextAnnotation.TextProperty\x12:\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32$.google.cloud.vision.v1.BoundingPoly\x12/\n\x07symbols\x18\x03 \x03(\x0b\x32\x1e.google.cloud.vision.v1.Symbol\x12\x12\n\nconfidence\x18\x04 \x01(\x02"\xad\x01\n\x06Symbol\x12\x45\n\x08property\x18\x01 \x01(\x0b\x32\x33.google.cloud.vision.v1.TextAnnotation.TextProperty\x12:\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32$.google.cloud.vision.v1.BoundingPoly\x12\x0c\n\x04text\x18\x03 \x01(\t\x12\x12\n\nconfidence\x18\x04 \x01(\x02\x42{\n\x1a\x63om.google.cloud.vision.v1B\x13TextAnnotationProtoP\x01Z Page -> Block -> Paragraph -> Word -> Symbol Each - structural component, starting from Page, may further have their own - properties. Properties describe detected languages, breaks etc.. - Please refer to the [TextAnnotation.TextProperty][google.cloud.vision. - v1.TextAnnotation.TextProperty] message definition below for more - detail. - - Attributes: - pages: - List of pages detected by OCR. - text: - UTF-8 text detected on the pages. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.TextAnnotation) - }, -) -_sym_db.RegisterMessage(TextAnnotation) -_sym_db.RegisterMessage(TextAnnotation.DetectedLanguage) -_sym_db.RegisterMessage(TextAnnotation.DetectedBreak) -_sym_db.RegisterMessage(TextAnnotation.TextProperty) - -Page = _reflection.GeneratedProtocolMessageType( - "Page", - (_message.Message,), - { - "DESCRIPTOR": _PAGE, - "__module__": "google.cloud.vision_v1.proto.text_annotation_pb2", - "__doc__": """Detected page from OCR. - - Attributes: - property: - Additional information detected on the page. - width: - Page width. For PDFs the unit is points. For images (including - TIFFs) the unit is pixels. - height: - Page height. For PDFs the unit is points. For images - (including TIFFs) the unit is pixels. - blocks: - List of blocks of text, images etc on this page. - confidence: - Confidence of the OCR results on the page. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.Page) - }, -) -_sym_db.RegisterMessage(Page) - -Block = _reflection.GeneratedProtocolMessageType( - "Block", - (_message.Message,), - { - "DESCRIPTOR": _BLOCK, - "__module__": "google.cloud.vision_v1.proto.text_annotation_pb2", - "__doc__": """Logical element on the page. - - Attributes: - property: - Additional information detected for the block. - bounding_box: - The bounding box for the block. The vertices are in the order - of top-left, top-right, bottom-right, bottom-left. When a - rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: - - when the text is horizontal it might look like: :: - 0----1 | | 3----2 - when it’s rotated 180 - degrees around the top-left corner it becomes: :: - 2----3 | | 1----0 and the vertex order - will still be (0, 1, 2, 3). - paragraphs: - List of paragraphs in this block (if this blocks is of type - text). - block_type: - Detected block type (text, image etc) for this block. - confidence: - Confidence of the OCR results on the block. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.Block) - }, -) -_sym_db.RegisterMessage(Block) - -Paragraph = _reflection.GeneratedProtocolMessageType( - "Paragraph", - (_message.Message,), - { - "DESCRIPTOR": _PARAGRAPH, - "__module__": "google.cloud.vision_v1.proto.text_annotation_pb2", - "__doc__": """Structural unit of text representing a number of words in certain - order. - - Attributes: - property: - Additional information detected for the paragraph. - bounding_box: - The bounding box for the paragraph. The vertices are in the - order of top-left, top-right, bottom-right, bottom-left. When - a rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: \* - when the text is horizontal it might look like: 0—-1 \| \| - 3—-2 \* when it’s rotated 180 degrees around the top-left - corner it becomes: 2—-3 \| \| 1—-0 and the vertex order will - still be (0, 1, 2, 3). - words: - List of all words in this paragraph. - confidence: - Confidence of the OCR results for the paragraph. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.Paragraph) - }, -) -_sym_db.RegisterMessage(Paragraph) - -Word = _reflection.GeneratedProtocolMessageType( - "Word", - (_message.Message,), - { - "DESCRIPTOR": _WORD, - "__module__": "google.cloud.vision_v1.proto.text_annotation_pb2", - "__doc__": """A word representation. - - Attributes: - property: - Additional information detected for the word. - bounding_box: - The bounding box for the word. The vertices are in the order - of top-left, top-right, bottom-right, bottom-left. When a - rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: \* - when the text is horizontal it might look like: 0—-1 \| \| - 3—-2 \* when it’s rotated 180 degrees around the top-left - corner it becomes: 2—-3 \| \| 1—-0 and the vertex order will - still be (0, 1, 2, 3). - symbols: - List of symbols in the word. The order of the symbols follows - the natural reading order. - confidence: - Confidence of the OCR results for the word. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.Word) - }, -) -_sym_db.RegisterMessage(Word) - -Symbol = _reflection.GeneratedProtocolMessageType( - "Symbol", - (_message.Message,), - { - "DESCRIPTOR": _SYMBOL, - "__module__": "google.cloud.vision_v1.proto.text_annotation_pb2", - "__doc__": """A single symbol representation. - - Attributes: - property: - Additional information detected for the symbol. - bounding_box: - The bounding box for the symbol. The vertices are in the order - of top-left, top-right, bottom-right, bottom-left. When a - rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: \* - when the text is horizontal it might look like: 0—-1 \| \| - 3—-2 \* when it’s rotated 180 degrees around the top-left - corner it becomes: 2—-3 \| \| 1—-0 and the vertex order will - still be (0, 1, 2, 3). - text: - The actual UTF-8 representation of the symbol. - confidence: - Confidence of the OCR results for the symbol. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1.Symbol) - }, -) -_sym_db.RegisterMessage(Symbol) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1/proto/text_annotation_pb2_grpc.py b/google/cloud/vision_v1/proto/text_annotation_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/vision_v1/proto/text_annotation_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/vision_v1/proto/web_detection_pb2.py b/google/cloud/vision_v1/proto/web_detection_pb2.py deleted file mode 100644 index d57e7a80..00000000 --- a/google/cloud/vision_v1/proto/web_detection_pb2.py +++ /dev/null @@ -1,629 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1/proto/web_detection.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1/proto/web_detection.proto", - package="google.cloud.vision.v1", - syntax="proto3", - serialized_options=b"\n\032com.google.cloud.vision.v1B\021WebDetectionProtoP\001Z None: + """Instantiate the image annotator client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ImageAnnotatorTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = ImageAnnotatorClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def batch_annotate_images( + self, + request: image_annotator.BatchAnnotateImagesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateImageRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: + r"""Run image detection and annotation for a batch of + images. + + Args: + request (:class:`~.image_annotator.BatchAnnotateImagesRequest`): + The request object. Multiple image annotation requests + are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AnnotateImageRequest]`): + Required. Individual image annotation + requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.image_annotator.BatchAnnotateImagesResponse: + Response to a batch image annotation + request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([requests]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = image_annotator.BatchAnnotateImagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_annotate_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def batch_annotate_files( + self, + request: image_annotator.BatchAnnotateFilesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateFileRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> image_annotator.BatchAnnotateFilesResponse: + r"""Service that performs image detection and annotation + for a batch of files. Now only "application/pdf", + "image/tiff" and "image/gif" are supported. + This service will extract at most 5 (customers can + specify which 5 in AnnotateFileRequest.pages) frames + (gif) or pages (pdf or tiff) from each file provided and + perform detection and annotation for each image + extracted. + + Args: + request (:class:`~.image_annotator.BatchAnnotateFilesRequest`): + The request object. A list of requests to annotate files + using the BatchAnnotateFiles API. + requests (:class:`Sequence[~.image_annotator.AnnotateFileRequest]`): + Required. The list of file annotation + requests. Right now we support only one + AnnotateFileRequest in + BatchAnnotateFilesRequest. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.image_annotator.BatchAnnotateFilesResponse: + A list of file annotation responses. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([requests]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = image_annotator.BatchAnnotateFilesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_annotate_files, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def async_batch_annotate_images( + self, + request: image_annotator.AsyncBatchAnnotateImagesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateImageRequest] = None, + output_config: image_annotator.OutputConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Run asynchronous image detection and annotation for a list of + images. + + Progress and results can be retrieved through the + ``google.longrunning.Operations`` interface. + ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateImagesResponse`` (results). + + This service will write image annotation outputs to json files + in customer GCS bucket, each json file containing + BatchAnnotateImagesResponse proto. + + Args: + request (:class:`~.image_annotator.AsyncBatchAnnotateImagesRequest`): + The request object. Request for async image annotation + for a list of images. + requests (:class:`Sequence[~.image_annotator.AnnotateImageRequest]`): + Required. Individual image annotation + requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + output_config (:class:`~.image_annotator.OutputConfig`): + Required. The desired output location + and metadata (e.g. format). + This corresponds to the ``output_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.image_annotator.AsyncBatchAnnotateImagesResponse``: + Response to an async batch image annotation request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([requests, output_config]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = image_annotator.AsyncBatchAnnotateImagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + if output_config is not None: + request.output_config = output_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.async_batch_annotate_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + image_annotator.AsyncBatchAnnotateImagesResponse, + metadata_type=image_annotator.OperationMetadata, + ) + + # Done; return the response. + return response + + async def async_batch_annotate_files( + self, + request: image_annotator.AsyncBatchAnnotateFilesRequest = None, + *, + requests: Sequence[image_annotator.AsyncAnnotateFileRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Run asynchronous image detection and annotation for a list of + generic files, such as PDF files, which may contain multiple + pages and multiple images per page. Progress and results can be + retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateFilesResponse`` (results). + + Args: + request (:class:`~.image_annotator.AsyncBatchAnnotateFilesRequest`): + The request object. Multiple async file annotation + requests are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AsyncAnnotateFileRequest]`): + Required. Individual async file + annotation requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.image_annotator.AsyncBatchAnnotateFilesResponse``: + Response to an async batch file annotation request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([requests]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = image_annotator.AsyncBatchAnnotateFilesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.async_batch_annotate_files, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + image_annotator.AsyncBatchAnnotateFilesResponse, + metadata_type=image_annotator.OperationMetadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ImageAnnotatorAsyncClient",) diff --git a/google/cloud/vision_v1/services/image_annotator/client.py b/google/cloud/vision_v1/services/image_annotator/client.py new file mode 100644 index 00000000..f3bbe4dc --- /dev/null +++ b/google/cloud/vision_v1/services/image_annotator/client.py @@ -0,0 +1,604 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1.types import image_annotator + +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ImageAnnotatorGrpcTransport +from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport + + +class ImageAnnotatorClientMeta(type): + """Metaclass for the ImageAnnotator client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[ImageAnnotatorTransport]] + _transport_registry["grpc"] = ImageAnnotatorGrpcTransport + _transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[ImageAnnotatorTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ImageAnnotatorClient(metaclass=ImageAnnotatorClientMeta): + """Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "vision.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + def __init__( + self, + *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, ImageAnnotatorTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the image annotator client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ImageAnnotatorTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ImageAnnotatorTransport): + # transport is a ImageAnnotatorTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def batch_annotate_images( + self, + request: image_annotator.BatchAnnotateImagesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateImageRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: + r"""Run image detection and annotation for a batch of + images. + + Args: + request (:class:`~.image_annotator.BatchAnnotateImagesRequest`): + The request object. Multiple image annotation requests + are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AnnotateImageRequest]`): + Required. Individual image annotation + requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.image_annotator.BatchAnnotateImagesResponse: + Response to a batch image annotation + request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([requests]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a image_annotator.BatchAnnotateImagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, image_annotator.BatchAnnotateImagesRequest): + request = image_annotator.BatchAnnotateImagesRequest(request) + if requests is not None: + for i in range(len(requests)): + requests[i] = image_annotator.AnnotateImageRequest(requests[i]) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_annotate_images] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def batch_annotate_files( + self, + request: image_annotator.BatchAnnotateFilesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateFileRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> image_annotator.BatchAnnotateFilesResponse: + r"""Service that performs image detection and annotation + for a batch of files. Now only "application/pdf", + "image/tiff" and "image/gif" are supported. + This service will extract at most 5 (customers can + specify which 5 in AnnotateFileRequest.pages) frames + (gif) or pages (pdf or tiff) from each file provided and + perform detection and annotation for each image + extracted. + + Args: + request (:class:`~.image_annotator.BatchAnnotateFilesRequest`): + The request object. A list of requests to annotate files + using the BatchAnnotateFiles API. + requests (:class:`Sequence[~.image_annotator.AnnotateFileRequest]`): + Required. The list of file annotation + requests. Right now we support only one + AnnotateFileRequest in + BatchAnnotateFilesRequest. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.image_annotator.BatchAnnotateFilesResponse: + A list of file annotation responses. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([requests]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a image_annotator.BatchAnnotateFilesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, image_annotator.BatchAnnotateFilesRequest): + request = image_annotator.BatchAnnotateFilesRequest(request) + if requests is not None: + for i in range(len(requests)): + requests[i] = image_annotator.AnnotateFileRequest(requests[i]) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_annotate_files] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def async_batch_annotate_images( + self, + request: image_annotator.AsyncBatchAnnotateImagesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateImageRequest] = None, + output_config: image_annotator.OutputConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Run asynchronous image detection and annotation for a list of + images. + + Progress and results can be retrieved through the + ``google.longrunning.Operations`` interface. + ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateImagesResponse`` (results). + + This service will write image annotation outputs to json files + in customer GCS bucket, each json file containing + BatchAnnotateImagesResponse proto. + + Args: + request (:class:`~.image_annotator.AsyncBatchAnnotateImagesRequest`): + The request object. Request for async image annotation + for a list of images. + requests (:class:`Sequence[~.image_annotator.AnnotateImageRequest]`): + Required. Individual image annotation + requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + output_config (:class:`~.image_annotator.OutputConfig`): + Required. The desired output location + and metadata (e.g. format). + This corresponds to the ``output_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.image_annotator.AsyncBatchAnnotateImagesResponse``: + Response to an async batch image annotation request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([requests, output_config]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a image_annotator.AsyncBatchAnnotateImagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, image_annotator.AsyncBatchAnnotateImagesRequest): + request = image_annotator.AsyncBatchAnnotateImagesRequest(request) + if requests is not None: + for i in range(len(requests)): + requests[i] = image_annotator.AnnotateImageRequest(requests[i]) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + if output_config is not None: + request.output_config = output_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.async_batch_annotate_images + ] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + image_annotator.AsyncBatchAnnotateImagesResponse, + metadata_type=image_annotator.OperationMetadata, + ) + + # Done; return the response. + return response + + def async_batch_annotate_files( + self, + request: image_annotator.AsyncBatchAnnotateFilesRequest = None, + *, + requests: Sequence[image_annotator.AsyncAnnotateFileRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Run asynchronous image detection and annotation for a list of + generic files, such as PDF files, which may contain multiple + pages and multiple images per page. Progress and results can be + retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateFilesResponse`` (results). + + Args: + request (:class:`~.image_annotator.AsyncBatchAnnotateFilesRequest`): + The request object. Multiple async file annotation + requests are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AsyncAnnotateFileRequest]`): + Required. Individual async file + annotation requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.image_annotator.AsyncBatchAnnotateFilesResponse``: + Response to an async batch file annotation request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([requests]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a image_annotator.AsyncBatchAnnotateFilesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, image_annotator.AsyncBatchAnnotateFilesRequest): + request = image_annotator.AsyncBatchAnnotateFilesRequest(request) + if requests is not None: + for i in range(len(requests)): + requests[i] = image_annotator.AsyncAnnotateFileRequest(requests[i]) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.async_batch_annotate_files + ] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + image_annotator.AsyncBatchAnnotateFilesResponse, + metadata_type=image_annotator.OperationMetadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ImageAnnotatorClient",) diff --git a/google/cloud/vision_v1/services/image_annotator/transports/__init__.py b/google/cloud/vision_v1/services/image_annotator/transports/__init__.py new file mode 100644 index 00000000..f2315e0d --- /dev/null +++ b/google/cloud/vision_v1/services/image_annotator/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import ImageAnnotatorTransport +from .grpc import ImageAnnotatorGrpcTransport +from .grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ImageAnnotatorTransport]] +_transport_registry["grpc"] = ImageAnnotatorGrpcTransport +_transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport + + +__all__ = ( + "ImageAnnotatorTransport", + "ImageAnnotatorGrpcTransport", + "ImageAnnotatorGrpcAsyncIOTransport", +) diff --git a/google/cloud/vision_v1/services/image_annotator/transports/base.py b/google/cloud/vision_v1/services/image_annotator/transports/base.py new file mode 100644 index 00000000..5648dc5c --- /dev/null +++ b/google/cloud/vision_v1/services/image_annotator/transports/base.py @@ -0,0 +1,214 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.vision_v1.types import image_annotator +from google.longrunning import operations_pb2 as operations # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ImageAnnotatorTransport(abc.ABC): + """Abstract transport class for ImageAnnotator.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ) + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.batch_annotate_images: gapic_v1.method.wrap_method( + self.batch_annotate_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.batch_annotate_files: gapic_v1.method.wrap_method( + self.batch_annotate_files, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.async_batch_annotate_images: gapic_v1.method.wrap_method( + self.async_batch_annotate_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.async_batch_annotate_files: gapic_v1.method.wrap_method( + self.async_batch_annotate_files, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def batch_annotate_images( + self, + ) -> typing.Callable[ + [image_annotator.BatchAnnotateImagesRequest], + typing.Union[ + image_annotator.BatchAnnotateImagesResponse, + typing.Awaitable[image_annotator.BatchAnnotateImagesResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_annotate_files( + self, + ) -> typing.Callable[ + [image_annotator.BatchAnnotateFilesRequest], + typing.Union[ + image_annotator.BatchAnnotateFilesResponse, + typing.Awaitable[image_annotator.BatchAnnotateFilesResponse], + ], + ]: + raise NotImplementedError() + + @property + def async_batch_annotate_images( + self, + ) -> typing.Callable[ + [image_annotator.AsyncBatchAnnotateImagesRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def async_batch_annotate_files( + self, + ) -> typing.Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + +__all__ = ("ImageAnnotatorTransport",) diff --git a/google/cloud/vision_v1/services/image_annotator/transports/grpc.py b/google/cloud/vision_v1/services/image_annotator/transports/grpc.py new file mode 100644 index 00000000..b939263b --- /dev/null +++ b/google/cloud/vision_v1/services/image_annotator/transports/grpc.py @@ -0,0 +1,393 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.vision_v1.types import image_annotator +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO + + +class ImageAnnotatorGrpcTransport(ImageAnnotatorTransport): + """gRPC backend transport for ImageAnnotator. + + Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def batch_annotate_images( + self, + ) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + image_annotator.BatchAnnotateImagesResponse, + ]: + r"""Return a callable for the batch annotate images method over gRPC. + + Run image detection and annotation for a batch of + images. + + Returns: + Callable[[~.BatchAnnotateImagesRequest], + ~.BatchAnnotateImagesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_annotate_images" not in self._stubs: + self._stubs["batch_annotate_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ImageAnnotator/BatchAnnotateImages", + request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, + response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, + ) + return self._stubs["batch_annotate_images"] + + @property + def batch_annotate_files( + self, + ) -> Callable[ + [image_annotator.BatchAnnotateFilesRequest], + image_annotator.BatchAnnotateFilesResponse, + ]: + r"""Return a callable for the batch annotate files method over gRPC. + + Service that performs image detection and annotation + for a batch of files. Now only "application/pdf", + "image/tiff" and "image/gif" are supported. + This service will extract at most 5 (customers can + specify which 5 in AnnotateFileRequest.pages) frames + (gif) or pages (pdf or tiff) from each file provided and + perform detection and annotation for each image + extracted. + + Returns: + Callable[[~.BatchAnnotateFilesRequest], + ~.BatchAnnotateFilesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_annotate_files" not in self._stubs: + self._stubs["batch_annotate_files"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ImageAnnotator/BatchAnnotateFiles", + request_serializer=image_annotator.BatchAnnotateFilesRequest.serialize, + response_deserializer=image_annotator.BatchAnnotateFilesResponse.deserialize, + ) + return self._stubs["batch_annotate_files"] + + @property + def async_batch_annotate_images( + self, + ) -> Callable[ + [image_annotator.AsyncBatchAnnotateImagesRequest], operations.Operation + ]: + r"""Return a callable for the async batch annotate images method over gRPC. + + Run asynchronous image detection and annotation for a list of + images. + + Progress and results can be retrieved through the + ``google.longrunning.Operations`` interface. + ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateImagesResponse`` (results). + + This service will write image annotation outputs to json files + in customer GCS bucket, each json file containing + BatchAnnotateImagesResponse proto. + + Returns: + Callable[[~.AsyncBatchAnnotateImagesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "async_batch_annotate_images" not in self._stubs: + self._stubs["async_batch_annotate_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ImageAnnotator/AsyncBatchAnnotateImages", + request_serializer=image_annotator.AsyncBatchAnnotateImagesRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["async_batch_annotate_images"] + + @property + def async_batch_annotate_files( + self, + ) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], operations.Operation + ]: + r"""Return a callable for the async batch annotate files method over gRPC. + + Run asynchronous image detection and annotation for a list of + generic files, such as PDF files, which may contain multiple + pages and multiple images per page. Progress and results can be + retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateFilesResponse`` (results). + + Returns: + Callable[[~.AsyncBatchAnnotateFilesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "async_batch_annotate_files" not in self._stubs: + self._stubs["async_batch_annotate_files"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ImageAnnotator/AsyncBatchAnnotateFiles", + request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["async_batch_annotate_files"] + + +__all__ = ("ImageAnnotatorGrpcTransport",) diff --git a/google/cloud/vision_v1/services/image_annotator/transports/grpc_asyncio.py b/google/cloud/vision_v1/services/image_annotator/transports/grpc_asyncio.py new file mode 100644 index 00000000..c36b70fd --- /dev/null +++ b/google/cloud/vision_v1/services/image_annotator/transports/grpc_asyncio.py @@ -0,0 +1,395 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.vision_v1.types import image_annotator +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .grpc import ImageAnnotatorGrpcTransport + + +class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): + """gRPC AsyncIO backend transport for ImageAnnotator. + + Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def batch_annotate_images( + self, + ) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + Awaitable[image_annotator.BatchAnnotateImagesResponse], + ]: + r"""Return a callable for the batch annotate images method over gRPC. + + Run image detection and annotation for a batch of + images. + + Returns: + Callable[[~.BatchAnnotateImagesRequest], + Awaitable[~.BatchAnnotateImagesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_annotate_images" not in self._stubs: + self._stubs["batch_annotate_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ImageAnnotator/BatchAnnotateImages", + request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, + response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, + ) + return self._stubs["batch_annotate_images"] + + @property + def batch_annotate_files( + self, + ) -> Callable[ + [image_annotator.BatchAnnotateFilesRequest], + Awaitable[image_annotator.BatchAnnotateFilesResponse], + ]: + r"""Return a callable for the batch annotate files method over gRPC. + + Service that performs image detection and annotation + for a batch of files. Now only "application/pdf", + "image/tiff" and "image/gif" are supported. + This service will extract at most 5 (customers can + specify which 5 in AnnotateFileRequest.pages) frames + (gif) or pages (pdf or tiff) from each file provided and + perform detection and annotation for each image + extracted. + + Returns: + Callable[[~.BatchAnnotateFilesRequest], + Awaitable[~.BatchAnnotateFilesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_annotate_files" not in self._stubs: + self._stubs["batch_annotate_files"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ImageAnnotator/BatchAnnotateFiles", + request_serializer=image_annotator.BatchAnnotateFilesRequest.serialize, + response_deserializer=image_annotator.BatchAnnotateFilesResponse.deserialize, + ) + return self._stubs["batch_annotate_files"] + + @property + def async_batch_annotate_images( + self, + ) -> Callable[ + [image_annotator.AsyncBatchAnnotateImagesRequest], + Awaitable[operations.Operation], + ]: + r"""Return a callable for the async batch annotate images method over gRPC. + + Run asynchronous image detection and annotation for a list of + images. + + Progress and results can be retrieved through the + ``google.longrunning.Operations`` interface. + ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateImagesResponse`` (results). + + This service will write image annotation outputs to json files + in customer GCS bucket, each json file containing + BatchAnnotateImagesResponse proto. + + Returns: + Callable[[~.AsyncBatchAnnotateImagesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "async_batch_annotate_images" not in self._stubs: + self._stubs["async_batch_annotate_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ImageAnnotator/AsyncBatchAnnotateImages", + request_serializer=image_annotator.AsyncBatchAnnotateImagesRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["async_batch_annotate_images"] + + @property + def async_batch_annotate_files( + self, + ) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + Awaitable[operations.Operation], + ]: + r"""Return a callable for the async batch annotate files method over gRPC. + + Run asynchronous image detection and annotation for a list of + generic files, such as PDF files, which may contain multiple + pages and multiple images per page. Progress and results can be + retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateFilesResponse`` (results). + + Returns: + Callable[[~.AsyncBatchAnnotateFilesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "async_batch_annotate_files" not in self._stubs: + self._stubs["async_batch_annotate_files"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ImageAnnotator/AsyncBatchAnnotateFiles", + request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["async_batch_annotate_files"] + + +__all__ = ("ImageAnnotatorGrpcAsyncIOTransport",) diff --git a/google/cloud/vision_v1/services/product_search/__init__.py b/google/cloud/vision_v1/services/product_search/__init__.py new file mode 100644 index 00000000..e82b5909 --- /dev/null +++ b/google/cloud/vision_v1/services/product_search/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import ProductSearchClient +from .async_client import ProductSearchAsyncClient + +__all__ = ( + "ProductSearchClient", + "ProductSearchAsyncClient", +) diff --git a/google/cloud/vision_v1/services/product_search/async_client.py b/google/cloud/vision_v1/services/product_search/async_client.py new file mode 100644 index 00000000..0afae177 --- /dev/null +++ b/google/cloud/vision_v1/services/product_search/async_client.py @@ -0,0 +1,1995 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1.services.product_search import pagers +from google.cloud.vision_v1.types import geometry +from google.cloud.vision_v1.types import product_search_service +from google.protobuf import empty_pb2 as empty # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + +from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport +from .client import ProductSearchClient + + +class ProductSearchAsyncClient: + """Manages Products and ProductSets of reference images for use in + product search. It uses the following resource model: + + - The API has a collection of + [ProductSet][google.cloud.vision.v1.ProductSet] resources, named + ``projects/*/locations/*/productSets/*``, which acts as a way to + put different products into groups to limit identification. + + In parallel, + + - The API has a collection of + [Product][google.cloud.vision.v1.Product] resources, named + ``projects/*/locations/*/products/*`` + + - Each [Product][google.cloud.vision.v1.Product] has a collection + of [ReferenceImage][google.cloud.vision.v1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` + """ + + _client: ProductSearchClient + + DEFAULT_ENDPOINT = ProductSearchClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProductSearchClient.DEFAULT_MTLS_ENDPOINT + + product_path = staticmethod(ProductSearchClient.product_path) + parse_product_path = staticmethod(ProductSearchClient.parse_product_path) + product_set_path = staticmethod(ProductSearchClient.product_set_path) + parse_product_set_path = staticmethod(ProductSearchClient.parse_product_set_path) + reference_image_path = staticmethod(ProductSearchClient.reference_image_path) + parse_reference_image_path = staticmethod( + ProductSearchClient.parse_reference_image_path + ) + + from_service_account_file = ProductSearchClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(ProductSearchClient).get_transport_class, type(ProductSearchClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, ProductSearchTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the product search client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProductSearchTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = ProductSearchClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def create_product_set( + self, + request: product_search_service.CreateProductSetRequest = None, + *, + parent: str = None, + product_set: product_search_service.ProductSet = None, + product_set_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Creates and returns a new ProductSet resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. + + Args: + request (:class:`~.product_search_service.CreateProductSetRequest`): + The request object. Request message for the + `CreateProductSet` method. + parent (:class:`str`): + Required. The project in which the ProductSet should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_set (:class:`~.product_search_service.ProductSet`): + Required. The ProductSet to create. + This corresponds to the ``product_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_set_id (:class:`str`): + A user-supplied resource id for this ProductSet. If set, + the server will attempt to use this value as the + resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``product_set_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, product_set, product_set_id]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.CreateProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if product_set is not None: + request.product_set = product_set + if product_set_id is not None: + request.product_set_id = product_set_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_product_sets( + self, + request: product_search_service.ListProductSetsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductSetsAsyncPager: + r"""Lists ProductSets in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductSetsRequest`): + The request object. Request message for the + `ListProductSets` method. + parent (:class:`str`): + Required. The project from which ProductSets should be + listed. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductSetsAsyncPager: + Response message for the ``ListProductSets`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.ListProductSetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_product_sets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductSetsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_product_set( + self, + request: product_search_service.GetProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Gets information associated with a ProductSet. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + + Args: + request (:class:`~.product_search_service.GetProductSetRequest`): + The request object. Request message for the + `GetProductSet` method. + name (:class:`str`): + Required. Resource name of the ProductSet to get. + + Format is: + ``projects/PROJECT_ID/locations/LOG_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.GetProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_product_set( + self, + request: product_search_service.UpdateProductSetRequest = None, + *, + product_set: product_search_service.ProductSet = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Makes changes to a ProductSet resource. Only display_name can be + updated currently. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. + + Args: + request (:class:`~.product_search_service.UpdateProductSetRequest`): + The request object. Request message for the + `UpdateProductSet` method. + product_set (:class:`~.product_search_service.ProductSet`): + Required. The ProductSet resource + which replaces the one on the server. + This corresponds to the ``product_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The [FieldMask][google.protobuf.FieldMask] that + specifies which fields to update. If update_mask isn't + specified, all mutable fields are to be updated. Valid + mask path is ``display_name``. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([product_set, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.UpdateProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if product_set is not None: + request.product_set = product_set + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("product_set.name", request.product_set.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_product_set( + self, + request: product_search_service.DeleteProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a ProductSet. Products and + ReferenceImages in the ProductSet are not deleted. + The actual image files are not deleted from Google Cloud + Storage. + + Args: + request (:class:`~.product_search_service.DeleteProductSetRequest`): + The request object. Request message for the + `DeleteProductSet` method. + name (:class:`str`): + Required. Resource name of the ProductSet to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.DeleteProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def create_product( + self, + request: product_search_service.CreateProductRequest = None, + *, + parent: str = None, + product: product_search_service.Product = None, + product_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Creates and returns a new product resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. + + Args: + request (:class:`~.product_search_service.CreateProductRequest`): + The request object. Request message for the + `CreateProduct` method. + parent (:class:`str`): + Required. The project in which the Product should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`~.product_search_service.Product`): + Required. The product to create. + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (:class:`str`): + A user-supplied resource id for this Product. If set, + the server will attempt to use this value as the + resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``product_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, product, product_id]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.CreateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_products( + self, + request: product_search_service.ListProductsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsAsyncPager: + r"""Lists products in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductsRequest`): + The request object. Request message for the + `ListProducts` method. + parent (:class:`str`): + Required. The project OR ProductSet from which Products + should be listed. + + Format: ``projects/PROJECT_ID/locations/LOC_ID`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductsAsyncPager: + Response message for the ``ListProducts`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.ListProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_products, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_product( + self, + request: product_search_service.GetProductRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Gets information associated with a Product. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + + Args: + request (:class:`~.product_search_service.GetProductRequest`): + The request object. Request message for the `GetProduct` + method. + name (:class:`str`): + Required. Resource name of the Product to get. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.GetProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_product( + self, + request: product_search_service.UpdateProductRequest = None, + *, + product: product_search_service.Product = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Makes changes to a Product resource. Only the ``display_name``, + ``description``, and ``labels`` fields can be updated right now. + + If labels are updated, the change will not be reflected in + queries until the next index time. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. + + Args: + request (:class:`~.product_search_service.UpdateProductRequest`): + The request object. Request message for the + `UpdateProduct` method. + product (:class:`~.product_search_service.Product`): + Required. The Product resource which + replaces the one on the server. + product.name is immutable. + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The [FieldMask][google.protobuf.FieldMask] that + specifies which fields to update. If update_mask isn't + specified, all mutable fields are to be updated. Valid + mask paths include ``product_labels``, ``display_name``, + and ``description``. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([product, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.UpdateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if product is not None: + request.product = product + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("product.name", request.product.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_product( + self, + request: product_search_service.DeleteProductRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a product and its reference + images. + Metadata of the product and all its images will be + deleted right away, but search queries against + ProductSets containing the product may still work until + all related caches are refreshed. + + Args: + request (:class:`~.product_search_service.DeleteProductRequest`): + The request object. Request message for the + `DeleteProduct` method. + name (:class:`str`): + Required. Resource name of product to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.DeleteProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def create_reference_image( + self, + request: product_search_service.CreateReferenceImageRequest = None, + *, + parent: str = None, + reference_image: product_search_service.ReferenceImage = None, + reference_image_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ReferenceImage: + r"""Creates and returns a new ReferenceImage resource. + + The ``bounding_poly`` field is optional. If ``bounding_poly`` is + not specified, the system will try to detect regions of interest + in the image that are compatible with the product_category on + the parent product. If it is specified, detection is ALWAYS + skipped. The system converts polygons into non-rotated + rectangles. + + Note that the pipeline will resize the image if the image + resolution is too large to process (above 50MP). + + Possible errors: + + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. + + Args: + request (:class:`~.product_search_service.CreateReferenceImageRequest`): + The request object. Request message for the + `CreateReferenceImage` method. + parent (:class:`str`): + Required. Resource name of the product in which to + create the reference image. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reference_image (:class:`~.product_search_service.ReferenceImage`): + Required. The reference image to + create. If an image ID is specified, it + is ignored. + This corresponds to the ``reference_image`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reference_image_id (:class:`str`): + A user-supplied resource id for the ReferenceImage to be + added. If set, the server will attempt to use this value + as the resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``reference_image_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ReferenceImage: + A ``ReferenceImage`` represents a product image and its + associated metadata, such as bounding boxes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, reference_image, reference_image_id]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.CreateReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if reference_image is not None: + request.reference_image = reference_image + if reference_image_id is not None: + request.reference_image_id = reference_image_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_reference_image( + self, + request: product_search_service.DeleteReferenceImageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a reference image. + The image metadata will be deleted right away, but + search queries against ProductSets containing the image + may still work until all related caches are refreshed. + + The actual image files are not deleted from Google Cloud + Storage. + + Args: + request (:class:`~.product_search_service.DeleteReferenceImageRequest`): + The request object. Request message for the + `DeleteReferenceImage` method. + name (:class:`str`): + Required. The resource name of the reference image to + delete. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.DeleteReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def list_reference_images( + self, + request: product_search_service.ListReferenceImagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListReferenceImagesAsyncPager: + r"""Lists reference images. + + Possible errors: + + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. + + Args: + request (:class:`~.product_search_service.ListReferenceImagesRequest`): + The request object. Request message for the + `ListReferenceImages` method. + parent (:class:`str`): + Required. Resource name of the product containing the + reference images. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListReferenceImagesAsyncPager: + Response message for the ``ListReferenceImages`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.ListReferenceImagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_reference_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListReferenceImagesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_reference_image( + self, + request: product_search_service.GetReferenceImageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ReferenceImage: + r"""Gets information associated with a ReferenceImage. + + Possible errors: + + - Returns NOT_FOUND if the specified image does not exist. + + Args: + request (:class:`~.product_search_service.GetReferenceImageRequest`): + The request object. Request message for the + `GetReferenceImage` method. + name (:class:`str`): + Required. The resource name of the ReferenceImage to + get. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ReferenceImage: + A ``ReferenceImage`` represents a product image and its + associated metadata, such as bounding boxes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.GetReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def add_product_to_product_set( + self, + request: product_search_service.AddProductToProductSetRequest = None, + *, + name: str = None, + product: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Adds a Product to the specified ProductSet. If the Product is + already present, no change is made. + + One Product can be added to at most 100 ProductSets. + + Possible errors: + + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. + + Args: + request (:class:`~.product_search_service.AddProductToProductSetRequest`): + The request object. Request message for the + `AddProductToProductSet` method. + name (:class:`str`): + Required. The resource name for the ProductSet to + modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`str`): + Required. The resource name for the Product to be added + to this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name, product]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.AddProductToProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_product_to_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def remove_product_from_product_set( + self, + request: product_search_service.RemoveProductFromProductSetRequest = None, + *, + name: str = None, + product: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Removes a Product from the specified ProductSet. + + Args: + request (:class:`~.product_search_service.RemoveProductFromProductSetRequest`): + The request object. Request message for the + `RemoveProductFromProductSet` method. + name (:class:`str`): + Required. The resource name for the ProductSet to + modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`str`): + Required. The resource name for the Product to be + removed from this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name, product]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.RemoveProductFromProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_product_from_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def list_products_in_product_set( + self, + request: product_search_service.ListProductsInProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsInProductSetAsyncPager: + r"""Lists the Products in a ProductSet, in an unspecified order. If + the ProductSet does not exist, the products field of the + response will be empty. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductsInProductSetRequest`): + The request object. Request message for the + `ListProductsInProductSet` method. + name (:class:`str`): + Required. The ProductSet resource for which to retrieve + Products. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductsInProductSetAsyncPager: + Response message for the ``ListProductsInProductSet`` + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.ListProductsInProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_products_in_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductsInProductSetAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_product_sets( + self, + request: product_search_service.ImportProductSetsRequest = None, + *, + parent: str = None, + input_config: product_search_service.ImportProductSetsInputConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Asynchronous API that imports a list of reference images to + specified product sets based on a list of image information. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) ``Operation.response`` + contains ``ImportProductSetsResponse``. (results) + + The input source of this method is a csv file on Google Cloud + Storage. For the format of the csv file please see + [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1.ImportProductSetsGcsSource.csv_file_uri]. + + Args: + request (:class:`~.product_search_service.ImportProductSetsRequest`): + The request object. Request message for the + `ImportProductSets` method. + parent (:class:`str`): + Required. The project in which the ProductSets should be + imported. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + input_config (:class:`~.product_search_service.ImportProductSetsInputConfig`): + Required. The input content for the + list of requests. + This corresponds to the ``input_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.product_search_service.ImportProductSetsResponse``: + Response message for the ``ImportProductSets`` method. + + This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, input_config]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.ImportProductSetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if input_config is not None: + request.input_config = input_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_product_sets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + product_search_service.ImportProductSetsResponse, + metadata_type=product_search_service.BatchOperationMetadata, + ) + + # Done; return the response. + return response + + async def purge_products( + self, + request: product_search_service.PurgeProductsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Asynchronous API to delete all Products in a ProductSet or all + Products that are in no ProductSet. + + If a Product is a member of the specified ProductSet in addition + to other ProductSets, the Product will still be deleted. + + It is recommended to not delete the specified ProductSet until + after this operation has completed. It is also recommended to + not add any of the Products involved in the batch delete to a + new ProductSet while this operation is running because those + Products may still end up deleted. + + It's not possible to undo the PurgeProducts operation. + Therefore, it is recommended to keep the csv files used in + ImportProductSets (if that was how you originally built the + Product Set) before starting PurgeProducts, in case you need to + re-import the data after deletion. + + If the plan is to purge all of the Products from a ProductSet + and then re-use the empty ProductSet to re-import new Products + into the empty ProductSet, you must wait until the PurgeProducts + operation has finished for that ProductSet. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) + + Args: + request (:class:`~.product_search_service.PurgeProductsRequest`): + The request object. Request message for the + `PurgeProducts` method. + parent (:class:`str`): + Required. The project and location in which the Products + should be deleted. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.empty.Empty``: A generic empty message that + you can re-use to avoid defining duplicated empty + messages in your APIs. A typical example is to use it as + the request or the response type of an API method. For + instance: + + :: + + service Foo { + rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); + } + + The JSON representation for ``Empty`` is empty JSON + object ``{}``. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.PurgeProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_products, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty.Empty, + metadata_type=product_search_service.BatchOperationMetadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ProductSearchAsyncClient",) diff --git a/google/cloud/vision_v1/services/product_search/client.py b/google/cloud/vision_v1/services/product_search/client.py new file mode 100644 index 00000000..640f4e46 --- /dev/null +++ b/google/cloud/vision_v1/services/product_search/client.py @@ -0,0 +1,2093 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1.services.product_search import pagers +from google.cloud.vision_v1.types import geometry +from google.cloud.vision_v1.types import product_search_service +from google.protobuf import empty_pb2 as empty # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + +from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProductSearchGrpcTransport +from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport + + +class ProductSearchClientMeta(type): + """Metaclass for the ProductSearch client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[ProductSearchTransport]] + _transport_registry["grpc"] = ProductSearchGrpcTransport + _transport_registry["grpc_asyncio"] = ProductSearchGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[ProductSearchTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ProductSearchClient(metaclass=ProductSearchClientMeta): + """Manages Products and ProductSets of reference images for use in + product search. It uses the following resource model: + + - The API has a collection of + [ProductSet][google.cloud.vision.v1.ProductSet] resources, named + ``projects/*/locations/*/productSets/*``, which acts as a way to + put different products into groups to limit identification. + + In parallel, + + - The API has a collection of + [Product][google.cloud.vision.v1.Product] resources, named + ``projects/*/locations/*/products/*`` + + - Each [Product][google.cloud.vision.v1.Product] has a collection + of [ReferenceImage][google.cloud.vision.v1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "vision.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def product_path(project: str, location: str, product: str,) -> str: + """Return a fully-qualified product string.""" + return "projects/{project}/locations/{location}/products/{product}".format( + project=project, location=location, product=product, + ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str, str]: + """Parse a product path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def product_set_path(project: str, location: str, product_set: str,) -> str: + """Return a fully-qualified product_set string.""" + return "projects/{project}/locations/{location}/productSets/{product_set}".format( + project=project, location=location, product_set=product_set, + ) + + @staticmethod + def parse_product_set_path(path: str) -> Dict[str, str]: + """Parse a product_set path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def reference_image_path( + project: str, location: str, product: str, reference_image: str, + ) -> str: + """Return a fully-qualified reference_image string.""" + return "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( + project=project, + location=location, + product=product, + reference_image=reference_image, + ) + + @staticmethod + def parse_reference_image_path(path: str) -> Dict[str, str]: + """Parse a reference_image path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)/referenceImages/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, ProductSearchTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the product search client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProductSearchTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ProductSearchTransport): + # transport is a ProductSearchTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def create_product_set( + self, + request: product_search_service.CreateProductSetRequest = None, + *, + parent: str = None, + product_set: product_search_service.ProductSet = None, + product_set_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Creates and returns a new ProductSet resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. + + Args: + request (:class:`~.product_search_service.CreateProductSetRequest`): + The request object. Request message for the + `CreateProductSet` method. + parent (:class:`str`): + Required. The project in which the ProductSet should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_set (:class:`~.product_search_service.ProductSet`): + Required. The ProductSet to create. + This corresponds to the ``product_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_set_id (:class:`str`): + A user-supplied resource id for this ProductSet. If set, + the server will attempt to use this value as the + resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``product_set_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product_set, product_set_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.CreateProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.CreateProductSetRequest): + request = product_search_service.CreateProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if product_set is not None: + request.product_set = product_set + if product_set_id is not None: + request.product_set_id = product_set_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_product_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_product_sets( + self, + request: product_search_service.ListProductSetsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductSetsPager: + r"""Lists ProductSets in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductSetsRequest`): + The request object. Request message for the + `ListProductSets` method. + parent (:class:`str`): + Required. The project from which ProductSets should be + listed. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductSetsPager: + Response message for the ``ListProductSets`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.ListProductSetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.ListProductSetsRequest): + request = product_search_service.ListProductSetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_product_sets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductSetsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_product_set( + self, + request: product_search_service.GetProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Gets information associated with a ProductSet. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + + Args: + request (:class:`~.product_search_service.GetProductSetRequest`): + The request object. Request message for the + `GetProductSet` method. + name (:class:`str`): + Required. Resource name of the ProductSet to get. + + Format is: + ``projects/PROJECT_ID/locations/LOG_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.GetProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.GetProductSetRequest): + request = product_search_service.GetProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_product_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_product_set( + self, + request: product_search_service.UpdateProductSetRequest = None, + *, + product_set: product_search_service.ProductSet = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Makes changes to a ProductSet resource. Only display_name can be + updated currently. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. + + Args: + request (:class:`~.product_search_service.UpdateProductSetRequest`): + The request object. Request message for the + `UpdateProductSet` method. + product_set (:class:`~.product_search_service.ProductSet`): + Required. The ProductSet resource + which replaces the one on the server. + This corresponds to the ``product_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The [FieldMask][google.protobuf.FieldMask] that + specifies which fields to update. If update_mask isn't + specified, all mutable fields are to be updated. Valid + mask path is ``display_name``. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product_set, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.UpdateProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.UpdateProductSetRequest): + request = product_search_service.UpdateProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if product_set is not None: + request.product_set = product_set + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_product_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("product_set.name", request.product_set.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_product_set( + self, + request: product_search_service.DeleteProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a ProductSet. Products and + ReferenceImages in the ProductSet are not deleted. + The actual image files are not deleted from Google Cloud + Storage. + + Args: + request (:class:`~.product_search_service.DeleteProductSetRequest`): + The request object. Request message for the + `DeleteProductSet` method. + name (:class:`str`): + Required. Resource name of the ProductSet to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.DeleteProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.DeleteProductSetRequest): + request = product_search_service.DeleteProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_product_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def create_product( + self, + request: product_search_service.CreateProductRequest = None, + *, + parent: str = None, + product: product_search_service.Product = None, + product_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Creates and returns a new product resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. + + Args: + request (:class:`~.product_search_service.CreateProductRequest`): + The request object. Request message for the + `CreateProduct` method. + parent (:class:`str`): + Required. The project in which the Product should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`~.product_search_service.Product`): + Required. The product to create. + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (:class:`str`): + A user-supplied resource id for this Product. If set, + the server will attempt to use this value as the + resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``product_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.CreateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.CreateProductRequest): + request = product_search_service.CreateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_products( + self, + request: product_search_service.ListProductsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsPager: + r"""Lists products in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductsRequest`): + The request object. Request message for the + `ListProducts` method. + parent (:class:`str`): + Required. The project OR ProductSet from which Products + should be listed. + + Format: ``projects/PROJECT_ID/locations/LOC_ID`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductsPager: + Response message for the ``ListProducts`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.ListProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.ListProductsRequest): + request = product_search_service.ListProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_product( + self, + request: product_search_service.GetProductRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Gets information associated with a Product. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + + Args: + request (:class:`~.product_search_service.GetProductRequest`): + The request object. Request message for the `GetProduct` + method. + name (:class:`str`): + Required. Resource name of the Product to get. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.GetProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.GetProductRequest): + request = product_search_service.GetProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_product( + self, + request: product_search_service.UpdateProductRequest = None, + *, + product: product_search_service.Product = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Makes changes to a Product resource. Only the ``display_name``, + ``description``, and ``labels`` fields can be updated right now. + + If labels are updated, the change will not be reflected in + queries until the next index time. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. + + Args: + request (:class:`~.product_search_service.UpdateProductRequest`): + The request object. Request message for the + `UpdateProduct` method. + product (:class:`~.product_search_service.Product`): + Required. The Product resource which + replaces the one on the server. + product.name is immutable. + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The [FieldMask][google.protobuf.FieldMask] that + specifies which fields to update. If update_mask isn't + specified, all mutable fields are to be updated. Valid + mask paths include ``product_labels``, ``display_name``, + and ``description``. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.UpdateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.UpdateProductRequest): + request = product_search_service.UpdateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if product is not None: + request.product = product + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("product.name", request.product.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_product( + self, + request: product_search_service.DeleteProductRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a product and its reference + images. + Metadata of the product and all its images will be + deleted right away, but search queries against + ProductSets containing the product may still work until + all related caches are refreshed. + + Args: + request (:class:`~.product_search_service.DeleteProductRequest`): + The request object. Request message for the + `DeleteProduct` method. + name (:class:`str`): + Required. Resource name of product to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.DeleteProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.DeleteProductRequest): + request = product_search_service.DeleteProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def create_reference_image( + self, + request: product_search_service.CreateReferenceImageRequest = None, + *, + parent: str = None, + reference_image: product_search_service.ReferenceImage = None, + reference_image_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ReferenceImage: + r"""Creates and returns a new ReferenceImage resource. + + The ``bounding_poly`` field is optional. If ``bounding_poly`` is + not specified, the system will try to detect regions of interest + in the image that are compatible with the product_category on + the parent product. If it is specified, detection is ALWAYS + skipped. The system converts polygons into non-rotated + rectangles. + + Note that the pipeline will resize the image if the image + resolution is too large to process (above 50MP). + + Possible errors: + + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. + + Args: + request (:class:`~.product_search_service.CreateReferenceImageRequest`): + The request object. Request message for the + `CreateReferenceImage` method. + parent (:class:`str`): + Required. Resource name of the product in which to + create the reference image. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reference_image (:class:`~.product_search_service.ReferenceImage`): + Required. The reference image to + create. If an image ID is specified, it + is ignored. + This corresponds to the ``reference_image`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reference_image_id (:class:`str`): + A user-supplied resource id for the ReferenceImage to be + added. If set, the server will attempt to use this value + as the resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``reference_image_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ReferenceImage: + A ``ReferenceImage`` represents a product image and its + associated metadata, such as bounding boxes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, reference_image, reference_image_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.CreateReferenceImageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.CreateReferenceImageRequest): + request = product_search_service.CreateReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if reference_image is not None: + request.reference_image = reference_image + if reference_image_id is not None: + request.reference_image_id = reference_image_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_reference_image] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_reference_image( + self, + request: product_search_service.DeleteReferenceImageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a reference image. + The image metadata will be deleted right away, but + search queries against ProductSets containing the image + may still work until all related caches are refreshed. + + The actual image files are not deleted from Google Cloud + Storage. + + Args: + request (:class:`~.product_search_service.DeleteReferenceImageRequest`): + The request object. Request message for the + `DeleteReferenceImage` method. + name (:class:`str`): + Required. The resource name of the reference image to + delete. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.DeleteReferenceImageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.DeleteReferenceImageRequest): + request = product_search_service.DeleteReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_reference_image] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def list_reference_images( + self, + request: product_search_service.ListReferenceImagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListReferenceImagesPager: + r"""Lists reference images. + + Possible errors: + + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. + + Args: + request (:class:`~.product_search_service.ListReferenceImagesRequest`): + The request object. Request message for the + `ListReferenceImages` method. + parent (:class:`str`): + Required. Resource name of the product containing the + reference images. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListReferenceImagesPager: + Response message for the ``ListReferenceImages`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.ListReferenceImagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.ListReferenceImagesRequest): + request = product_search_service.ListReferenceImagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_reference_images] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListReferenceImagesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_reference_image( + self, + request: product_search_service.GetReferenceImageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ReferenceImage: + r"""Gets information associated with a ReferenceImage. + + Possible errors: + + - Returns NOT_FOUND if the specified image does not exist. + + Args: + request (:class:`~.product_search_service.GetReferenceImageRequest`): + The request object. Request message for the + `GetReferenceImage` method. + name (:class:`str`): + Required. The resource name of the ReferenceImage to + get. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ReferenceImage: + A ``ReferenceImage`` represents a product image and its + associated metadata, such as bounding boxes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.GetReferenceImageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.GetReferenceImageRequest): + request = product_search_service.GetReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_reference_image] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def add_product_to_product_set( + self, + request: product_search_service.AddProductToProductSetRequest = None, + *, + name: str = None, + product: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Adds a Product to the specified ProductSet. If the Product is + already present, no change is made. + + One Product can be added to at most 100 ProductSets. + + Possible errors: + + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. + + Args: + request (:class:`~.product_search_service.AddProductToProductSetRequest`): + The request object. Request message for the + `AddProductToProductSet` method. + name (:class:`str`): + Required. The resource name for the ProductSet to + modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`str`): + Required. The resource name for the Product to be added + to this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, product]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.AddProductToProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, product_search_service.AddProductToProductSetRequest + ): + request = product_search_service.AddProductToProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.add_product_to_product_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def remove_product_from_product_set( + self, + request: product_search_service.RemoveProductFromProductSetRequest = None, + *, + name: str = None, + product: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Removes a Product from the specified ProductSet. + + Args: + request (:class:`~.product_search_service.RemoveProductFromProductSetRequest`): + The request object. Request message for the + `RemoveProductFromProductSet` method. + name (:class:`str`): + Required. The resource name for the ProductSet to + modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`str`): + Required. The resource name for the Product to be + removed from this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, product]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.RemoveProductFromProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, product_search_service.RemoveProductFromProductSetRequest + ): + request = product_search_service.RemoveProductFromProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.remove_product_from_product_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def list_products_in_product_set( + self, + request: product_search_service.ListProductsInProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsInProductSetPager: + r"""Lists the Products in a ProductSet, in an unspecified order. If + the ProductSet does not exist, the products field of the + response will be empty. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductsInProductSetRequest`): + The request object. Request message for the + `ListProductsInProductSet` method. + name (:class:`str`): + Required. The ProductSet resource for which to retrieve + Products. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductsInProductSetPager: + Response message for the ``ListProductsInProductSet`` + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.ListProductsInProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, product_search_service.ListProductsInProductSetRequest + ): + request = product_search_service.ListProductsInProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_products_in_product_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductsInProductSetPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def import_product_sets( + self, + request: product_search_service.ImportProductSetsRequest = None, + *, + parent: str = None, + input_config: product_search_service.ImportProductSetsInputConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Asynchronous API that imports a list of reference images to + specified product sets based on a list of image information. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) ``Operation.response`` + contains ``ImportProductSetsResponse``. (results) + + The input source of this method is a csv file on Google Cloud + Storage. For the format of the csv file please see + [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1.ImportProductSetsGcsSource.csv_file_uri]. + + Args: + request (:class:`~.product_search_service.ImportProductSetsRequest`): + The request object. Request message for the + `ImportProductSets` method. + parent (:class:`str`): + Required. The project in which the ProductSets should be + imported. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + input_config (:class:`~.product_search_service.ImportProductSetsInputConfig`): + Required. The input content for the + list of requests. + This corresponds to the ``input_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.product_search_service.ImportProductSetsResponse``: + Response message for the ``ImportProductSets`` method. + + This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, input_config]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.ImportProductSetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.ImportProductSetsRequest): + request = product_search_service.ImportProductSetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if input_config is not None: + request.input_config = input_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_product_sets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + product_search_service.ImportProductSetsResponse, + metadata_type=product_search_service.BatchOperationMetadata, + ) + + # Done; return the response. + return response + + def purge_products( + self, + request: product_search_service.PurgeProductsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Asynchronous API to delete all Products in a ProductSet or all + Products that are in no ProductSet. + + If a Product is a member of the specified ProductSet in addition + to other ProductSets, the Product will still be deleted. + + It is recommended to not delete the specified ProductSet until + after this operation has completed. It is also recommended to + not add any of the Products involved in the batch delete to a + new ProductSet while this operation is running because those + Products may still end up deleted. + + It's not possible to undo the PurgeProducts operation. + Therefore, it is recommended to keep the csv files used in + ImportProductSets (if that was how you originally built the + Product Set) before starting PurgeProducts, in case you need to + re-import the data after deletion. + + If the plan is to purge all of the Products from a ProductSet + and then re-use the empty ProductSet to re-import new Products + into the empty ProductSet, you must wait until the PurgeProducts + operation has finished for that ProductSet. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) + + Args: + request (:class:`~.product_search_service.PurgeProductsRequest`): + The request object. Request message for the + `PurgeProducts` method. + parent (:class:`str`): + Required. The project and location in which the Products + should be deleted. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.empty.Empty``: A generic empty message that + you can re-use to avoid defining duplicated empty + messages in your APIs. A typical example is to use it as + the request or the response type of an API method. For + instance: + + :: + + service Foo { + rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); + } + + The JSON representation for ``Empty`` is empty JSON + object ``{}``. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.PurgeProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.PurgeProductsRequest): + request = product_search_service.PurgeProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty.Empty, + metadata_type=product_search_service.BatchOperationMetadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ProductSearchClient",) diff --git a/google/cloud/vision_v1/services/product_search/pagers.py b/google/cloud/vision_v1/services/product_search/pagers.py new file mode 100644 index 00000000..69bc017f --- /dev/null +++ b/google/cloud/vision_v1/services/product_search/pagers.py @@ -0,0 +1,546 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.vision_v1.types import product_search_service + + +class ListProductSetsPager: + """A pager for iterating through ``list_product_sets`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductSetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``product_sets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProductSets`` requests and continue to iterate + through the ``product_sets`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductSetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., product_search_service.ListProductSetsResponse], + request: product_search_service.ListProductSetsRequest, + response: product_search_service.ListProductSetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductSetsRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductSetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductSetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[product_search_service.ListProductSetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[product_search_service.ProductSet]: + for page in self.pages: + yield from page.product_sets + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListProductSetsAsyncPager: + """A pager for iterating through ``list_product_sets`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductSetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``product_sets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProductSets`` requests and continue to iterate + through the ``product_sets`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductSetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[product_search_service.ListProductSetsResponse] + ], + request: product_search_service.ListProductSetsRequest, + response: product_search_service.ListProductSetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductSetsRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductSetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductSetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[product_search_service.ListProductSetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[product_search_service.ProductSet]: + async def async_generator(): + async for page in self.pages: + for response in page.product_sets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListProductsPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., product_search_service.ListProductsResponse], + request: product_search_service.ListProductsRequest, + response: product_search_service.ListProductsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductsRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[product_search_service.ListProductsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[product_search_service.Product]: + for page in self.pages: + yield from page.products + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListProductsAsyncPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[product_search_service.ListProductsResponse]], + request: product_search_service.ListProductsRequest, + response: product_search_service.ListProductsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductsRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[product_search_service.ListProductsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[product_search_service.Product]: + async def async_generator(): + async for page in self.pages: + for response in page.products: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListReferenceImagesPager: + """A pager for iterating through ``list_reference_images`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListReferenceImagesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``reference_images`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListReferenceImages`` requests and continue to iterate + through the ``reference_images`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListReferenceImagesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., product_search_service.ListReferenceImagesResponse], + request: product_search_service.ListReferenceImagesRequest, + response: product_search_service.ListReferenceImagesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListReferenceImagesRequest`): + The initial request object. + response (:class:`~.product_search_service.ListReferenceImagesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListReferenceImagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[product_search_service.ListReferenceImagesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[product_search_service.ReferenceImage]: + for page in self.pages: + yield from page.reference_images + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListReferenceImagesAsyncPager: + """A pager for iterating through ``list_reference_images`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListReferenceImagesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``reference_images`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListReferenceImages`` requests and continue to iterate + through the ``reference_images`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListReferenceImagesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[product_search_service.ListReferenceImagesResponse] + ], + request: product_search_service.ListReferenceImagesRequest, + response: product_search_service.ListReferenceImagesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListReferenceImagesRequest`): + The initial request object. + response (:class:`~.product_search_service.ListReferenceImagesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListReferenceImagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[product_search_service.ListReferenceImagesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[product_search_service.ReferenceImage]: + async def async_generator(): + async for page in self.pages: + for response in page.reference_images: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListProductsInProductSetPager: + """A pager for iterating through ``list_products_in_product_set`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductsInProductSetResponse` object, and + provides an ``__iter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProductsInProductSet`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductsInProductSetResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., product_search_service.ListProductsInProductSetResponse], + request: product_search_service.ListProductsInProductSetRequest, + response: product_search_service.ListProductsInProductSetResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductsInProductSetRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductsInProductSetResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductsInProductSetRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterable[product_search_service.ListProductsInProductSetResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[product_search_service.Product]: + for page in self.pages: + yield from page.products + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListProductsInProductSetAsyncPager: + """A pager for iterating through ``list_products_in_product_set`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductsInProductSetResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProductsInProductSet`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductsInProductSetResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[product_search_service.ListProductsInProductSetResponse] + ], + request: product_search_service.ListProductsInProductSetRequest, + response: product_search_service.ListProductsInProductSetResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductsInProductSetRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductsInProductSetResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductsInProductSetRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[product_search_service.ListProductsInProductSetResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[product_search_service.Product]: + async def async_generator(): + async for page in self.pages: + for response in page.products: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/vision_v1/services/product_search/transports/__init__.py b/google/cloud/vision_v1/services/product_search/transports/__init__.py new file mode 100644 index 00000000..2d57de48 --- /dev/null +++ b/google/cloud/vision_v1/services/product_search/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import ProductSearchTransport +from .grpc import ProductSearchGrpcTransport +from .grpc_asyncio import ProductSearchGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProductSearchTransport]] +_transport_registry["grpc"] = ProductSearchGrpcTransport +_transport_registry["grpc_asyncio"] = ProductSearchGrpcAsyncIOTransport + + +__all__ = ( + "ProductSearchTransport", + "ProductSearchGrpcTransport", + "ProductSearchGrpcAsyncIOTransport", +) diff --git a/google/cloud/vision_v1/services/product_search/transports/base.py b/google/cloud/vision_v1/services/product_search/transports/base.py new file mode 100644 index 00000000..fd8fa748 --- /dev/null +++ b/google/cloud/vision_v1/services/product_search/transports/base.py @@ -0,0 +1,565 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.vision_v1.types import product_search_service +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ProductSearchTransport(abc.ABC): + """Abstract transport class for ProductSearch.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ) + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_product_set: gapic_v1.method.wrap_method( + self.create_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_product_sets: gapic_v1.method.wrap_method( + self.list_product_sets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_product_set: gapic_v1.method.wrap_method( + self.get_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update_product_set: gapic_v1.method.wrap_method( + self.update_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.delete_product_set: gapic_v1.method.wrap_method( + self.delete_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.create_product: gapic_v1.method.wrap_method( + self.create_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_products: gapic_v1.method.wrap_method( + self.list_products, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_product: gapic_v1.method.wrap_method( + self.get_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update_product: gapic_v1.method.wrap_method( + self.update_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.delete_product: gapic_v1.method.wrap_method( + self.delete_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.create_reference_image: gapic_v1.method.wrap_method( + self.create_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.delete_reference_image: gapic_v1.method.wrap_method( + self.delete_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_reference_images: gapic_v1.method.wrap_method( + self.list_reference_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_reference_image: gapic_v1.method.wrap_method( + self.get_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.add_product_to_product_set: gapic_v1.method.wrap_method( + self.add_product_to_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.remove_product_from_product_set: gapic_v1.method.wrap_method( + self.remove_product_from_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_products_in_product_set: gapic_v1.method.wrap_method( + self.list_products_in_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.import_product_sets: gapic_v1.method.wrap_method( + self.import_product_sets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.purge_products: gapic_v1.method.wrap_method( + self.purge_products, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_product_set( + self, + ) -> typing.Callable[ + [product_search_service.CreateProductSetRequest], + typing.Union[ + product_search_service.ProductSet, + typing.Awaitable[product_search_service.ProductSet], + ], + ]: + raise NotImplementedError() + + @property + def list_product_sets( + self, + ) -> typing.Callable[ + [product_search_service.ListProductSetsRequest], + typing.Union[ + product_search_service.ListProductSetsResponse, + typing.Awaitable[product_search_service.ListProductSetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_product_set( + self, + ) -> typing.Callable[ + [product_search_service.GetProductSetRequest], + typing.Union[ + product_search_service.ProductSet, + typing.Awaitable[product_search_service.ProductSet], + ], + ]: + raise NotImplementedError() + + @property + def update_product_set( + self, + ) -> typing.Callable[ + [product_search_service.UpdateProductSetRequest], + typing.Union[ + product_search_service.ProductSet, + typing.Awaitable[product_search_service.ProductSet], + ], + ]: + raise NotImplementedError() + + @property + def delete_product_set( + self, + ) -> typing.Callable[ + [product_search_service.DeleteProductSetRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def create_product( + self, + ) -> typing.Callable[ + [product_search_service.CreateProductRequest], + typing.Union[ + product_search_service.Product, + typing.Awaitable[product_search_service.Product], + ], + ]: + raise NotImplementedError() + + @property + def list_products( + self, + ) -> typing.Callable[ + [product_search_service.ListProductsRequest], + typing.Union[ + product_search_service.ListProductsResponse, + typing.Awaitable[product_search_service.ListProductsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_product( + self, + ) -> typing.Callable[ + [product_search_service.GetProductRequest], + typing.Union[ + product_search_service.Product, + typing.Awaitable[product_search_service.Product], + ], + ]: + raise NotImplementedError() + + @property + def update_product( + self, + ) -> typing.Callable[ + [product_search_service.UpdateProductRequest], + typing.Union[ + product_search_service.Product, + typing.Awaitable[product_search_service.Product], + ], + ]: + raise NotImplementedError() + + @property + def delete_product( + self, + ) -> typing.Callable[ + [product_search_service.DeleteProductRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def create_reference_image( + self, + ) -> typing.Callable[ + [product_search_service.CreateReferenceImageRequest], + typing.Union[ + product_search_service.ReferenceImage, + typing.Awaitable[product_search_service.ReferenceImage], + ], + ]: + raise NotImplementedError() + + @property + def delete_reference_image( + self, + ) -> typing.Callable[ + [product_search_service.DeleteReferenceImageRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def list_reference_images( + self, + ) -> typing.Callable[ + [product_search_service.ListReferenceImagesRequest], + typing.Union[ + product_search_service.ListReferenceImagesResponse, + typing.Awaitable[product_search_service.ListReferenceImagesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_reference_image( + self, + ) -> typing.Callable[ + [product_search_service.GetReferenceImageRequest], + typing.Union[ + product_search_service.ReferenceImage, + typing.Awaitable[product_search_service.ReferenceImage], + ], + ]: + raise NotImplementedError() + + @property + def add_product_to_product_set( + self, + ) -> typing.Callable[ + [product_search_service.AddProductToProductSetRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def remove_product_from_product_set( + self, + ) -> typing.Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def list_products_in_product_set( + self, + ) -> typing.Callable[ + [product_search_service.ListProductsInProductSetRequest], + typing.Union[ + product_search_service.ListProductsInProductSetResponse, + typing.Awaitable[product_search_service.ListProductsInProductSetResponse], + ], + ]: + raise NotImplementedError() + + @property + def import_product_sets( + self, + ) -> typing.Callable[ + [product_search_service.ImportProductSetsRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def purge_products( + self, + ) -> typing.Callable[ + [product_search_service.PurgeProductsRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + +__all__ = ("ProductSearchTransport",) diff --git a/google/cloud/vision_v1/services/product_search/transports/grpc.py b/google/cloud/vision_v1/services/product_search/transports/grpc.py new file mode 100644 index 00000000..9798f2cd --- /dev/null +++ b/google/cloud/vision_v1/services/product_search/transports/grpc.py @@ -0,0 +1,954 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.vision_v1.types import product_search_service +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO + + +class ProductSearchGrpcTransport(ProductSearchTransport): + """gRPC backend transport for ProductSearch. + + Manages Products and ProductSets of reference images for use in + product search. It uses the following resource model: + + - The API has a collection of + [ProductSet][google.cloud.vision.v1.ProductSet] resources, named + ``projects/*/locations/*/productSets/*``, which acts as a way to + put different products into groups to limit identification. + + In parallel, + + - The API has a collection of + [Product][google.cloud.vision.v1.Product] resources, named + ``projects/*/locations/*/products/*`` + + - Each [Product][google.cloud.vision.v1.Product] has a collection + of [ReferenceImage][google.cloud.vision.v1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def create_product_set( + self, + ) -> Callable[ + [product_search_service.CreateProductSetRequest], + product_search_service.ProductSet, + ]: + r"""Return a callable for the create product set method over gRPC. + + Creates and returns a new ProductSet resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. + + Returns: + Callable[[~.CreateProductSetRequest], + ~.ProductSet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_product_set" not in self._stubs: + self._stubs["create_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/CreateProductSet", + request_serializer=product_search_service.CreateProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["create_product_set"] + + @property + def list_product_sets( + self, + ) -> Callable[ + [product_search_service.ListProductSetsRequest], + product_search_service.ListProductSetsResponse, + ]: + r"""Return a callable for the list product sets method over gRPC. + + Lists ProductSets in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. + + Returns: + Callable[[~.ListProductSetsRequest], + ~.ListProductSetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_product_sets" not in self._stubs: + self._stubs["list_product_sets"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/ListProductSets", + request_serializer=product_search_service.ListProductSetsRequest.serialize, + response_deserializer=product_search_service.ListProductSetsResponse.deserialize, + ) + return self._stubs["list_product_sets"] + + @property + def get_product_set( + self, + ) -> Callable[ + [product_search_service.GetProductSetRequest], product_search_service.ProductSet + ]: + r"""Return a callable for the get product set method over gRPC. + + Gets information associated with a ProductSet. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + + Returns: + Callable[[~.GetProductSetRequest], + ~.ProductSet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_product_set" not in self._stubs: + self._stubs["get_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/GetProductSet", + request_serializer=product_search_service.GetProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["get_product_set"] + + @property + def update_product_set( + self, + ) -> Callable[ + [product_search_service.UpdateProductSetRequest], + product_search_service.ProductSet, + ]: + r"""Return a callable for the update product set method over gRPC. + + Makes changes to a ProductSet resource. Only display_name can be + updated currently. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. + + Returns: + Callable[[~.UpdateProductSetRequest], + ~.ProductSet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_product_set" not in self._stubs: + self._stubs["update_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/UpdateProductSet", + request_serializer=product_search_service.UpdateProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["update_product_set"] + + @property + def delete_product_set( + self, + ) -> Callable[[product_search_service.DeleteProductSetRequest], empty.Empty]: + r"""Return a callable for the delete product set method over gRPC. + + Permanently deletes a ProductSet. Products and + ReferenceImages in the ProductSet are not deleted. + The actual image files are not deleted from Google Cloud + Storage. + + Returns: + Callable[[~.DeleteProductSetRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_product_set" not in self._stubs: + self._stubs["delete_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/DeleteProductSet", + request_serializer=product_search_service.DeleteProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_product_set"] + + @property + def create_product( + self, + ) -> Callable[ + [product_search_service.CreateProductRequest], product_search_service.Product + ]: + r"""Return a callable for the create product method over gRPC. + + Creates and returns a new product resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. + + Returns: + Callable[[~.CreateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_product" not in self._stubs: + self._stubs["create_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/CreateProduct", + request_serializer=product_search_service.CreateProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["create_product"] + + @property + def list_products( + self, + ) -> Callable[ + [product_search_service.ListProductsRequest], + product_search_service.ListProductsResponse, + ]: + r"""Return a callable for the list products method over gRPC. + + Lists products in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Returns: + Callable[[~.ListProductsRequest], + ~.ListProductsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_products" not in self._stubs: + self._stubs["list_products"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/ListProducts", + request_serializer=product_search_service.ListProductsRequest.serialize, + response_deserializer=product_search_service.ListProductsResponse.deserialize, + ) + return self._stubs["list_products"] + + @property + def get_product( + self, + ) -> Callable[ + [product_search_service.GetProductRequest], product_search_service.Product + ]: + r"""Return a callable for the get product method over gRPC. + + Gets information associated with a Product. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + + Returns: + Callable[[~.GetProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_product" not in self._stubs: + self._stubs["get_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/GetProduct", + request_serializer=product_search_service.GetProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["get_product"] + + @property + def update_product( + self, + ) -> Callable[ + [product_search_service.UpdateProductRequest], product_search_service.Product + ]: + r"""Return a callable for the update product method over gRPC. + + Makes changes to a Product resource. Only the ``display_name``, + ``description``, and ``labels`` fields can be updated right now. + + If labels are updated, the change will not be reflected in + queries until the next index time. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. + + Returns: + Callable[[~.UpdateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_product" not in self._stubs: + self._stubs["update_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/UpdateProduct", + request_serializer=product_search_service.UpdateProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["update_product"] + + @property + def delete_product( + self, + ) -> Callable[[product_search_service.DeleteProductRequest], empty.Empty]: + r"""Return a callable for the delete product method over gRPC. + + Permanently deletes a product and its reference + images. + Metadata of the product and all its images will be + deleted right away, but search queries against + ProductSets containing the product may still work until + all related caches are refreshed. + + Returns: + Callable[[~.DeleteProductRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_product" not in self._stubs: + self._stubs["delete_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/DeleteProduct", + request_serializer=product_search_service.DeleteProductRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_product"] + + @property + def create_reference_image( + self, + ) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + product_search_service.ReferenceImage, + ]: + r"""Return a callable for the create reference image method over gRPC. + + Creates and returns a new ReferenceImage resource. + + The ``bounding_poly`` field is optional. If ``bounding_poly`` is + not specified, the system will try to detect regions of interest + in the image that are compatible with the product_category on + the parent product. If it is specified, detection is ALWAYS + skipped. The system converts polygons into non-rotated + rectangles. + + Note that the pipeline will resize the image if the image + resolution is too large to process (above 50MP). + + Possible errors: + + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. + + Returns: + Callable[[~.CreateReferenceImageRequest], + ~.ReferenceImage]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_reference_image" not in self._stubs: + self._stubs["create_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/CreateReferenceImage", + request_serializer=product_search_service.CreateReferenceImageRequest.serialize, + response_deserializer=product_search_service.ReferenceImage.deserialize, + ) + return self._stubs["create_reference_image"] + + @property + def delete_reference_image( + self, + ) -> Callable[[product_search_service.DeleteReferenceImageRequest], empty.Empty]: + r"""Return a callable for the delete reference image method over gRPC. + + Permanently deletes a reference image. + The image metadata will be deleted right away, but + search queries against ProductSets containing the image + may still work until all related caches are refreshed. + + The actual image files are not deleted from Google Cloud + Storage. + + Returns: + Callable[[~.DeleteReferenceImageRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_reference_image" not in self._stubs: + self._stubs["delete_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/DeleteReferenceImage", + request_serializer=product_search_service.DeleteReferenceImageRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_reference_image"] + + @property + def list_reference_images( + self, + ) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + product_search_service.ListReferenceImagesResponse, + ]: + r"""Return a callable for the list reference images method over gRPC. + + Lists reference images. + + Possible errors: + + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. + + Returns: + Callable[[~.ListReferenceImagesRequest], + ~.ListReferenceImagesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_reference_images" not in self._stubs: + self._stubs["list_reference_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/ListReferenceImages", + request_serializer=product_search_service.ListReferenceImagesRequest.serialize, + response_deserializer=product_search_service.ListReferenceImagesResponse.deserialize, + ) + return self._stubs["list_reference_images"] + + @property + def get_reference_image( + self, + ) -> Callable[ + [product_search_service.GetReferenceImageRequest], + product_search_service.ReferenceImage, + ]: + r"""Return a callable for the get reference image method over gRPC. + + Gets information associated with a ReferenceImage. + + Possible errors: + + - Returns NOT_FOUND if the specified image does not exist. + + Returns: + Callable[[~.GetReferenceImageRequest], + ~.ReferenceImage]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_reference_image" not in self._stubs: + self._stubs["get_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/GetReferenceImage", + request_serializer=product_search_service.GetReferenceImageRequest.serialize, + response_deserializer=product_search_service.ReferenceImage.deserialize, + ) + return self._stubs["get_reference_image"] + + @property + def add_product_to_product_set( + self, + ) -> Callable[[product_search_service.AddProductToProductSetRequest], empty.Empty]: + r"""Return a callable for the add product to product set method over gRPC. + + Adds a Product to the specified ProductSet. If the Product is + already present, no change is made. + + One Product can be added to at most 100 ProductSets. + + Possible errors: + + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. + + Returns: + Callable[[~.AddProductToProductSetRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "add_product_to_product_set" not in self._stubs: + self._stubs["add_product_to_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/AddProductToProductSet", + request_serializer=product_search_service.AddProductToProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["add_product_to_product_set"] + + @property + def remove_product_from_product_set( + self, + ) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], empty.Empty + ]: + r"""Return a callable for the remove product from product + set method over gRPC. + + Removes a Product from the specified ProductSet. + + Returns: + Callable[[~.RemoveProductFromProductSetRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "remove_product_from_product_set" not in self._stubs: + self._stubs[ + "remove_product_from_product_set" + ] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/RemoveProductFromProductSet", + request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["remove_product_from_product_set"] + + @property + def list_products_in_product_set( + self, + ) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + product_search_service.ListProductsInProductSetResponse, + ]: + r"""Return a callable for the list products in product set method over gRPC. + + Lists the Products in a ProductSet, in an unspecified order. If + the ProductSet does not exist, the products field of the + response will be empty. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Returns: + Callable[[~.ListProductsInProductSetRequest], + ~.ListProductsInProductSetResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_products_in_product_set" not in self._stubs: + self._stubs["list_products_in_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/ListProductsInProductSet", + request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, + response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, + ) + return self._stubs["list_products_in_product_set"] + + @property + def import_product_sets( + self, + ) -> Callable[ + [product_search_service.ImportProductSetsRequest], operations.Operation + ]: + r"""Return a callable for the import product sets method over gRPC. + + Asynchronous API that imports a list of reference images to + specified product sets based on a list of image information. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) ``Operation.response`` + contains ``ImportProductSetsResponse``. (results) + + The input source of this method is a csv file on Google Cloud + Storage. For the format of the csv file please see + [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1.ImportProductSetsGcsSource.csv_file_uri]. + + Returns: + Callable[[~.ImportProductSetsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_product_sets" not in self._stubs: + self._stubs["import_product_sets"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/ImportProductSets", + request_serializer=product_search_service.ImportProductSetsRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["import_product_sets"] + + @property + def purge_products( + self, + ) -> Callable[[product_search_service.PurgeProductsRequest], operations.Operation]: + r"""Return a callable for the purge products method over gRPC. + + Asynchronous API to delete all Products in a ProductSet or all + Products that are in no ProductSet. + + If a Product is a member of the specified ProductSet in addition + to other ProductSets, the Product will still be deleted. + + It is recommended to not delete the specified ProductSet until + after this operation has completed. It is also recommended to + not add any of the Products involved in the batch delete to a + new ProductSet while this operation is running because those + Products may still end up deleted. + + It's not possible to undo the PurgeProducts operation. + Therefore, it is recommended to keep the csv files used in + ImportProductSets (if that was how you originally built the + Product Set) before starting PurgeProducts, in case you need to + re-import the data after deletion. + + If the plan is to purge all of the Products from a ProductSet + and then re-use the empty ProductSet to re-import new Products + into the empty ProductSet, you must wait until the PurgeProducts + operation has finished for that ProductSet. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) + + Returns: + Callable[[~.PurgeProductsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "purge_products" not in self._stubs: + self._stubs["purge_products"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/PurgeProducts", + request_serializer=product_search_service.PurgeProductsRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["purge_products"] + + +__all__ = ("ProductSearchGrpcTransport",) diff --git a/google/cloud/vision_v1/services/product_search/transports/grpc_asyncio.py b/google/cloud/vision_v1/services/product_search/transports/grpc_asyncio.py new file mode 100644 index 00000000..21143ec9 --- /dev/null +++ b/google/cloud/vision_v1/services/product_search/transports/grpc_asyncio.py @@ -0,0 +1,970 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.vision_v1.types import product_search_service +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO +from .grpc import ProductSearchGrpcTransport + + +class ProductSearchGrpcAsyncIOTransport(ProductSearchTransport): + """gRPC AsyncIO backend transport for ProductSearch. + + Manages Products and ProductSets of reference images for use in + product search. It uses the following resource model: + + - The API has a collection of + [ProductSet][google.cloud.vision.v1.ProductSet] resources, named + ``projects/*/locations/*/productSets/*``, which acts as a way to + put different products into groups to limit identification. + + In parallel, + + - The API has a collection of + [Product][google.cloud.vision.v1.Product] resources, named + ``projects/*/locations/*/products/*`` + + - Each [Product][google.cloud.vision.v1.Product] has a collection + of [ReferenceImage][google.cloud.vision.v1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def create_product_set( + self, + ) -> Callable[ + [product_search_service.CreateProductSetRequest], + Awaitable[product_search_service.ProductSet], + ]: + r"""Return a callable for the create product set method over gRPC. + + Creates and returns a new ProductSet resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. + + Returns: + Callable[[~.CreateProductSetRequest], + Awaitable[~.ProductSet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_product_set" not in self._stubs: + self._stubs["create_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/CreateProductSet", + request_serializer=product_search_service.CreateProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["create_product_set"] + + @property + def list_product_sets( + self, + ) -> Callable[ + [product_search_service.ListProductSetsRequest], + Awaitable[product_search_service.ListProductSetsResponse], + ]: + r"""Return a callable for the list product sets method over gRPC. + + Lists ProductSets in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. + + Returns: + Callable[[~.ListProductSetsRequest], + Awaitable[~.ListProductSetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_product_sets" not in self._stubs: + self._stubs["list_product_sets"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/ListProductSets", + request_serializer=product_search_service.ListProductSetsRequest.serialize, + response_deserializer=product_search_service.ListProductSetsResponse.deserialize, + ) + return self._stubs["list_product_sets"] + + @property + def get_product_set( + self, + ) -> Callable[ + [product_search_service.GetProductSetRequest], + Awaitable[product_search_service.ProductSet], + ]: + r"""Return a callable for the get product set method over gRPC. + + Gets information associated with a ProductSet. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + + Returns: + Callable[[~.GetProductSetRequest], + Awaitable[~.ProductSet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_product_set" not in self._stubs: + self._stubs["get_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/GetProductSet", + request_serializer=product_search_service.GetProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["get_product_set"] + + @property + def update_product_set( + self, + ) -> Callable[ + [product_search_service.UpdateProductSetRequest], + Awaitable[product_search_service.ProductSet], + ]: + r"""Return a callable for the update product set method over gRPC. + + Makes changes to a ProductSet resource. Only display_name can be + updated currently. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. + + Returns: + Callable[[~.UpdateProductSetRequest], + Awaitable[~.ProductSet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_product_set" not in self._stubs: + self._stubs["update_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/UpdateProductSet", + request_serializer=product_search_service.UpdateProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["update_product_set"] + + @property + def delete_product_set( + self, + ) -> Callable[ + [product_search_service.DeleteProductSetRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the delete product set method over gRPC. + + Permanently deletes a ProductSet. Products and + ReferenceImages in the ProductSet are not deleted. + The actual image files are not deleted from Google Cloud + Storage. + + Returns: + Callable[[~.DeleteProductSetRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_product_set" not in self._stubs: + self._stubs["delete_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/DeleteProductSet", + request_serializer=product_search_service.DeleteProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_product_set"] + + @property + def create_product( + self, + ) -> Callable[ + [product_search_service.CreateProductRequest], + Awaitable[product_search_service.Product], + ]: + r"""Return a callable for the create product method over gRPC. + + Creates and returns a new product resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. + + Returns: + Callable[[~.CreateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_product" not in self._stubs: + self._stubs["create_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/CreateProduct", + request_serializer=product_search_service.CreateProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["create_product"] + + @property + def list_products( + self, + ) -> Callable[ + [product_search_service.ListProductsRequest], + Awaitable[product_search_service.ListProductsResponse], + ]: + r"""Return a callable for the list products method over gRPC. + + Lists products in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Returns: + Callable[[~.ListProductsRequest], + Awaitable[~.ListProductsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_products" not in self._stubs: + self._stubs["list_products"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/ListProducts", + request_serializer=product_search_service.ListProductsRequest.serialize, + response_deserializer=product_search_service.ListProductsResponse.deserialize, + ) + return self._stubs["list_products"] + + @property + def get_product( + self, + ) -> Callable[ + [product_search_service.GetProductRequest], + Awaitable[product_search_service.Product], + ]: + r"""Return a callable for the get product method over gRPC. + + Gets information associated with a Product. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + + Returns: + Callable[[~.GetProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_product" not in self._stubs: + self._stubs["get_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/GetProduct", + request_serializer=product_search_service.GetProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["get_product"] + + @property + def update_product( + self, + ) -> Callable[ + [product_search_service.UpdateProductRequest], + Awaitable[product_search_service.Product], + ]: + r"""Return a callable for the update product method over gRPC. + + Makes changes to a Product resource. Only the ``display_name``, + ``description``, and ``labels`` fields can be updated right now. + + If labels are updated, the change will not be reflected in + queries until the next index time. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. + + Returns: + Callable[[~.UpdateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_product" not in self._stubs: + self._stubs["update_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/UpdateProduct", + request_serializer=product_search_service.UpdateProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["update_product"] + + @property + def delete_product( + self, + ) -> Callable[ + [product_search_service.DeleteProductRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the delete product method over gRPC. + + Permanently deletes a product and its reference + images. + Metadata of the product and all its images will be + deleted right away, but search queries against + ProductSets containing the product may still work until + all related caches are refreshed. + + Returns: + Callable[[~.DeleteProductRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_product" not in self._stubs: + self._stubs["delete_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/DeleteProduct", + request_serializer=product_search_service.DeleteProductRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_product"] + + @property + def create_reference_image( + self, + ) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + Awaitable[product_search_service.ReferenceImage], + ]: + r"""Return a callable for the create reference image method over gRPC. + + Creates and returns a new ReferenceImage resource. + + The ``bounding_poly`` field is optional. If ``bounding_poly`` is + not specified, the system will try to detect regions of interest + in the image that are compatible with the product_category on + the parent product. If it is specified, detection is ALWAYS + skipped. The system converts polygons into non-rotated + rectangles. + + Note that the pipeline will resize the image if the image + resolution is too large to process (above 50MP). + + Possible errors: + + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. + + Returns: + Callable[[~.CreateReferenceImageRequest], + Awaitable[~.ReferenceImage]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_reference_image" not in self._stubs: + self._stubs["create_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/CreateReferenceImage", + request_serializer=product_search_service.CreateReferenceImageRequest.serialize, + response_deserializer=product_search_service.ReferenceImage.deserialize, + ) + return self._stubs["create_reference_image"] + + @property + def delete_reference_image( + self, + ) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the delete reference image method over gRPC. + + Permanently deletes a reference image. + The image metadata will be deleted right away, but + search queries against ProductSets containing the image + may still work until all related caches are refreshed. + + The actual image files are not deleted from Google Cloud + Storage. + + Returns: + Callable[[~.DeleteReferenceImageRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_reference_image" not in self._stubs: + self._stubs["delete_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/DeleteReferenceImage", + request_serializer=product_search_service.DeleteReferenceImageRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_reference_image"] + + @property + def list_reference_images( + self, + ) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + Awaitable[product_search_service.ListReferenceImagesResponse], + ]: + r"""Return a callable for the list reference images method over gRPC. + + Lists reference images. + + Possible errors: + + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. + + Returns: + Callable[[~.ListReferenceImagesRequest], + Awaitable[~.ListReferenceImagesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_reference_images" not in self._stubs: + self._stubs["list_reference_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/ListReferenceImages", + request_serializer=product_search_service.ListReferenceImagesRequest.serialize, + response_deserializer=product_search_service.ListReferenceImagesResponse.deserialize, + ) + return self._stubs["list_reference_images"] + + @property + def get_reference_image( + self, + ) -> Callable[ + [product_search_service.GetReferenceImageRequest], + Awaitable[product_search_service.ReferenceImage], + ]: + r"""Return a callable for the get reference image method over gRPC. + + Gets information associated with a ReferenceImage. + + Possible errors: + + - Returns NOT_FOUND if the specified image does not exist. + + Returns: + Callable[[~.GetReferenceImageRequest], + Awaitable[~.ReferenceImage]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_reference_image" not in self._stubs: + self._stubs["get_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/GetReferenceImage", + request_serializer=product_search_service.GetReferenceImageRequest.serialize, + response_deserializer=product_search_service.ReferenceImage.deserialize, + ) + return self._stubs["get_reference_image"] + + @property + def add_product_to_product_set( + self, + ) -> Callable[ + [product_search_service.AddProductToProductSetRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the add product to product set method over gRPC. + + Adds a Product to the specified ProductSet. If the Product is + already present, no change is made. + + One Product can be added to at most 100 ProductSets. + + Possible errors: + + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. + + Returns: + Callable[[~.AddProductToProductSetRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "add_product_to_product_set" not in self._stubs: + self._stubs["add_product_to_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/AddProductToProductSet", + request_serializer=product_search_service.AddProductToProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["add_product_to_product_set"] + + @property + def remove_product_from_product_set( + self, + ) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + Awaitable[empty.Empty], + ]: + r"""Return a callable for the remove product from product + set method over gRPC. + + Removes a Product from the specified ProductSet. + + Returns: + Callable[[~.RemoveProductFromProductSetRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "remove_product_from_product_set" not in self._stubs: + self._stubs[ + "remove_product_from_product_set" + ] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/RemoveProductFromProductSet", + request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["remove_product_from_product_set"] + + @property + def list_products_in_product_set( + self, + ) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + Awaitable[product_search_service.ListProductsInProductSetResponse], + ]: + r"""Return a callable for the list products in product set method over gRPC. + + Lists the Products in a ProductSet, in an unspecified order. If + the ProductSet does not exist, the products field of the + response will be empty. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Returns: + Callable[[~.ListProductsInProductSetRequest], + Awaitable[~.ListProductsInProductSetResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_products_in_product_set" not in self._stubs: + self._stubs["list_products_in_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/ListProductsInProductSet", + request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, + response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, + ) + return self._stubs["list_products_in_product_set"] + + @property + def import_product_sets( + self, + ) -> Callable[ + [product_search_service.ImportProductSetsRequest], + Awaitable[operations.Operation], + ]: + r"""Return a callable for the import product sets method over gRPC. + + Asynchronous API that imports a list of reference images to + specified product sets based on a list of image information. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) ``Operation.response`` + contains ``ImportProductSetsResponse``. (results) + + The input source of this method is a csv file on Google Cloud + Storage. For the format of the csv file please see + [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1.ImportProductSetsGcsSource.csv_file_uri]. + + Returns: + Callable[[~.ImportProductSetsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_product_sets" not in self._stubs: + self._stubs["import_product_sets"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/ImportProductSets", + request_serializer=product_search_service.ImportProductSetsRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["import_product_sets"] + + @property + def purge_products( + self, + ) -> Callable[ + [product_search_service.PurgeProductsRequest], Awaitable[operations.Operation] + ]: + r"""Return a callable for the purge products method over gRPC. + + Asynchronous API to delete all Products in a ProductSet or all + Products that are in no ProductSet. + + If a Product is a member of the specified ProductSet in addition + to other ProductSets, the Product will still be deleted. + + It is recommended to not delete the specified ProductSet until + after this operation has completed. It is also recommended to + not add any of the Products involved in the batch delete to a + new ProductSet while this operation is running because those + Products may still end up deleted. + + It's not possible to undo the PurgeProducts operation. + Therefore, it is recommended to keep the csv files used in + ImportProductSets (if that was how you originally built the + Product Set) before starting PurgeProducts, in case you need to + re-import the data after deletion. + + If the plan is to purge all of the Products from a ProductSet + and then re-use the empty ProductSet to re-import new Products + into the empty ProductSet, you must wait until the PurgeProducts + operation has finished for that ProductSet. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) + + Returns: + Callable[[~.PurgeProductsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "purge_products" not in self._stubs: + self._stubs["purge_products"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1.ProductSearch/PurgeProducts", + request_serializer=product_search_service.PurgeProductsRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["purge_products"] + + +__all__ = ("ProductSearchGrpcAsyncIOTransport",) diff --git a/google/cloud/vision_v1/types.py b/google/cloud/vision_v1/types.py deleted file mode 100644 index 6310a9dc..00000000 --- a/google/cloud/vision_v1/types.py +++ /dev/null @@ -1,74 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.vision_v1.proto import geometry_pb2 -from google.cloud.vision_v1.proto import image_annotator_pb2 -from google.cloud.vision_v1.proto import product_search_pb2 -from google.cloud.vision_v1.proto import product_search_service_pb2 -from google.cloud.vision_v1.proto import text_annotation_pb2 -from google.cloud.vision_v1.proto import web_detection_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import any_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import timestamp_pb2 -from google.protobuf import wrappers_pb2 -from google.rpc import status_pb2 -from google.type import color_pb2 -from google.type import latlng_pb2 - - -_shared_modules = [ - operations_pb2, - any_pb2, - empty_pb2, - field_mask_pb2, - timestamp_pb2, - wrappers_pb2, - status_pb2, - color_pb2, - latlng_pb2, -] - -_local_modules = [ - geometry_pb2, - image_annotator_pb2, - product_search_pb2, - product_search_service_pb2, - text_annotation_pb2, - web_detection_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.vision_v1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/vision_v1/types/__init__.py b/google/cloud/vision_v1/types/__init__.py new file mode 100644 index 00000000..98992ae9 --- /dev/null +++ b/google/cloud/vision_v1/types/__init__.py @@ -0,0 +1,195 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .geometry import ( + Vertex, + NormalizedVertex, + BoundingPoly, + Position, +) +from .product_search_service import ( + Product, + ProductSet, + ReferenceImage, + CreateProductRequest, + ListProductsRequest, + ListProductsResponse, + GetProductRequest, + UpdateProductRequest, + DeleteProductRequest, + CreateProductSetRequest, + ListProductSetsRequest, + ListProductSetsResponse, + GetProductSetRequest, + UpdateProductSetRequest, + DeleteProductSetRequest, + CreateReferenceImageRequest, + ListReferenceImagesRequest, + ListReferenceImagesResponse, + GetReferenceImageRequest, + DeleteReferenceImageRequest, + AddProductToProductSetRequest, + RemoveProductFromProductSetRequest, + ListProductsInProductSetRequest, + ListProductsInProductSetResponse, + ImportProductSetsGcsSource, + ImportProductSetsInputConfig, + ImportProductSetsRequest, + ImportProductSetsResponse, + BatchOperationMetadata, + ProductSetPurgeConfig, + PurgeProductsRequest, +) +from .product_search import ( + ProductSearchParams, + ProductSearchResults, +) +from .text_annotation import ( + TextAnnotation, + Page, + Block, + Paragraph, + Word, + Symbol, +) +from .web_detection import WebDetection +from .image_annotator import ( + Feature, + ImageSource, + Image, + FaceAnnotation, + LocationInfo, + Property, + EntityAnnotation, + LocalizedObjectAnnotation, + SafeSearchAnnotation, + LatLongRect, + ColorInfo, + DominantColorsAnnotation, + ImageProperties, + CropHint, + CropHintsAnnotation, + CropHintsParams, + WebDetectionParams, + ImageContext, + AnnotateImageRequest, + ImageAnnotationContext, + AnnotateImageResponse, + BatchAnnotateImagesRequest, + BatchAnnotateImagesResponse, + AnnotateFileRequest, + AnnotateFileResponse, + BatchAnnotateFilesRequest, + BatchAnnotateFilesResponse, + AsyncAnnotateFileRequest, + AsyncAnnotateFileResponse, + AsyncBatchAnnotateImagesRequest, + AsyncBatchAnnotateImagesResponse, + AsyncBatchAnnotateFilesRequest, + AsyncBatchAnnotateFilesResponse, + InputConfig, + OutputConfig, + GcsSource, + GcsDestination, + OperationMetadata, +) + + +__all__ = ( + "Vertex", + "NormalizedVertex", + "BoundingPoly", + "Position", + "Product", + "ProductSet", + "ReferenceImage", + "CreateProductRequest", + "ListProductsRequest", + "ListProductsResponse", + "GetProductRequest", + "UpdateProductRequest", + "DeleteProductRequest", + "CreateProductSetRequest", + "ListProductSetsRequest", + "ListProductSetsResponse", + "GetProductSetRequest", + "UpdateProductSetRequest", + "DeleteProductSetRequest", + "CreateReferenceImageRequest", + "ListReferenceImagesRequest", + "ListReferenceImagesResponse", + "GetReferenceImageRequest", + "DeleteReferenceImageRequest", + "AddProductToProductSetRequest", + "RemoveProductFromProductSetRequest", + "ListProductsInProductSetRequest", + "ListProductsInProductSetResponse", + "ImportProductSetsGcsSource", + "ImportProductSetsInputConfig", + "ImportProductSetsRequest", + "ImportProductSetsResponse", + "BatchOperationMetadata", + "ProductSetPurgeConfig", + "PurgeProductsRequest", + "ProductSearchParams", + "ProductSearchResults", + "TextAnnotation", + "Page", + "Block", + "Paragraph", + "Word", + "Symbol", + "WebDetection", + "Feature", + "ImageSource", + "Image", + "FaceAnnotation", + "LocationInfo", + "Property", + "EntityAnnotation", + "LocalizedObjectAnnotation", + "SafeSearchAnnotation", + "LatLongRect", + "ColorInfo", + "DominantColorsAnnotation", + "ImageProperties", + "CropHint", + "CropHintsAnnotation", + "CropHintsParams", + "WebDetectionParams", + "ImageContext", + "AnnotateImageRequest", + "ImageAnnotationContext", + "AnnotateImageResponse", + "BatchAnnotateImagesRequest", + "BatchAnnotateImagesResponse", + "AnnotateFileRequest", + "AnnotateFileResponse", + "BatchAnnotateFilesRequest", + "BatchAnnotateFilesResponse", + "AsyncAnnotateFileRequest", + "AsyncAnnotateFileResponse", + "AsyncBatchAnnotateImagesRequest", + "AsyncBatchAnnotateImagesResponse", + "AsyncBatchAnnotateFilesRequest", + "AsyncBatchAnnotateFilesResponse", + "InputConfig", + "OutputConfig", + "GcsSource", + "GcsDestination", + "OperationMetadata", +) diff --git a/google/cloud/vision_v1/types/geometry.py b/google/cloud/vision_v1/types/geometry.py new file mode 100644 index 00000000..e37f9e07 --- /dev/null +++ b/google/cloud/vision_v1/types/geometry.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1", + manifest={"Vertex", "NormalizedVertex", "BoundingPoly", "Position",}, +) + + +class Vertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the vertex coordinates are in the same scale as the + original image. + + Attributes: + x (int): + X coordinate. + y (int): + Y coordinate. + """ + + x = proto.Field(proto.INT32, number=1) + + y = proto.Field(proto.INT32, number=2) + + +class NormalizedVertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the normalized vertex coordinates are relative to the + original image and range from 0 to 1. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate. + """ + + x = proto.Field(proto.FLOAT, number=1) + + y = proto.Field(proto.FLOAT, number=2) + + +class BoundingPoly(proto.Message): + r"""A bounding polygon for the detected image annotation. + + Attributes: + vertices (Sequence[~.geometry.Vertex]): + The bounding polygon vertices. + normalized_vertices (Sequence[~.geometry.NormalizedVertex]): + The bounding polygon normalized vertices. + """ + + vertices = proto.RepeatedField(proto.MESSAGE, number=1, message=Vertex,) + + normalized_vertices = proto.RepeatedField( + proto.MESSAGE, number=2, message=NormalizedVertex, + ) + + +class Position(proto.Message): + r"""A 3D position in the image, used primarily for Face detection + landmarks. A valid Position must have both x and y coordinates. + The position coordinates are in the same scale as the original + image. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate. + z (float): + Z coordinate (or depth). + """ + + x = proto.Field(proto.FLOAT, number=1) + + y = proto.Field(proto.FLOAT, number=2) + + z = proto.Field(proto.FLOAT, number=3) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1/types/image_annotator.py b/google/cloud/vision_v1/types/image_annotator.py new file mode 100644 index 00000000..c7ae671d --- /dev/null +++ b/google/cloud/vision_v1/types/image_annotator.py @@ -0,0 +1,1266 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.vision_v1.types import geometry +from google.cloud.vision_v1.types import product_search +from google.cloud.vision_v1.types import text_annotation +from google.cloud.vision_v1.types import web_detection as gcv_web_detection +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore +from google.type import color_pb2 as gt_color # type: ignore +from google.type import latlng_pb2 as latlng # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1", + manifest={ + "Likelihood", + "Feature", + "ImageSource", + "Image", + "FaceAnnotation", + "LocationInfo", + "Property", + "EntityAnnotation", + "LocalizedObjectAnnotation", + "SafeSearchAnnotation", + "LatLongRect", + "ColorInfo", + "DominantColorsAnnotation", + "ImageProperties", + "CropHint", + "CropHintsAnnotation", + "CropHintsParams", + "WebDetectionParams", + "ImageContext", + "AnnotateImageRequest", + "ImageAnnotationContext", + "AnnotateImageResponse", + "BatchAnnotateImagesRequest", + "BatchAnnotateImagesResponse", + "AnnotateFileRequest", + "AnnotateFileResponse", + "BatchAnnotateFilesRequest", + "BatchAnnotateFilesResponse", + "AsyncAnnotateFileRequest", + "AsyncAnnotateFileResponse", + "AsyncBatchAnnotateImagesRequest", + "AsyncBatchAnnotateImagesResponse", + "AsyncBatchAnnotateFilesRequest", + "AsyncBatchAnnotateFilesResponse", + "InputConfig", + "OutputConfig", + "GcsSource", + "GcsDestination", + "OperationMetadata", + }, +) + + +class Likelihood(proto.Enum): + r"""A bucketized representation of likelihood, which is intended + to give clients highly stable results across model upgrades. + """ + UNKNOWN = 0 + VERY_UNLIKELY = 1 + UNLIKELY = 2 + POSSIBLE = 3 + LIKELY = 4 + VERY_LIKELY = 5 + + +class Feature(proto.Message): + r"""The type of Google Cloud Vision API detection to perform, and the + maximum number of results to return for that type. Multiple + ``Feature`` objects can be specified in the ``features`` list. + + Attributes: + type_ (~.image_annotator.Feature.Type): + The feature type. + max_results (int): + Maximum number of results of this type. Does not apply to + ``TEXT_DETECTION``, ``DOCUMENT_TEXT_DETECTION``, or + ``CROP_HINTS``. + model (str): + Model to use for the feature. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + class Type(proto.Enum): + r"""Type of Google Cloud Vision API feature to be extracted.""" + TYPE_UNSPECIFIED = 0 + FACE_DETECTION = 1 + LANDMARK_DETECTION = 2 + LOGO_DETECTION = 3 + LABEL_DETECTION = 4 + TEXT_DETECTION = 5 + DOCUMENT_TEXT_DETECTION = 11 + SAFE_SEARCH_DETECTION = 6 + IMAGE_PROPERTIES = 7 + CROP_HINTS = 9 + WEB_DETECTION = 10 + PRODUCT_SEARCH = 12 + OBJECT_LOCALIZATION = 19 + + type_ = proto.Field(proto.ENUM, number=1, enum=Type,) + + max_results = proto.Field(proto.INT32, number=2) + + model = proto.Field(proto.STRING, number=3) + + +class ImageSource(proto.Message): + r"""External image source (Google Cloud Storage or web URL image + location). + + Attributes: + gcs_image_uri (str): + **Use ``image_uri`` instead.** + + The Google Cloud Storage URI of the form + ``gs://bucket_name/object_name``. Object versioning is not + supported. See `Google Cloud Storage Request + URIs `__ + for more info. + image_uri (str): + The URI of the source image. Can be either: + + 1. A Google Cloud Storage URI of the form + ``gs://bucket_name/object_name``. Object versioning is + not supported. See `Google Cloud Storage Request + URIs `__ + for more info. + + 2. A publicly-accessible image HTTP/HTTPS URL. When fetching + images from HTTP/HTTPS URLs, Google cannot guarantee that + the request will be completed. Your request may fail if + the specified host denies the request (e.g. due to + request throttling or DOS prevention), or if Google + throttles requests to the site for abuse prevention. You + should not depend on externally-hosted images for + production applications. + + When both ``gcs_image_uri`` and ``image_uri`` are specified, + ``image_uri`` takes precedence. + """ + + gcs_image_uri = proto.Field(proto.STRING, number=1) + + image_uri = proto.Field(proto.STRING, number=2) + + +class Image(proto.Message): + r"""Client image to perform Google Cloud Vision API tasks over. + + Attributes: + content (bytes): + Image content, represented as a stream of bytes. Note: As + with all ``bytes`` fields, protobuffers use a pure binary + representation, whereas JSON representations use base64. + source (~.image_annotator.ImageSource): + Google Cloud Storage image location, or publicly-accessible + image URL. If both ``content`` and ``source`` are provided + for an image, ``content`` takes precedence and is used to + perform the image annotation request. + """ + + content = proto.Field(proto.BYTES, number=1) + + source = proto.Field(proto.MESSAGE, number=2, message=ImageSource,) + + +class FaceAnnotation(proto.Message): + r"""A face annotation object contains the results of face + detection. + + Attributes: + bounding_poly (~.geometry.BoundingPoly): + The bounding polygon around the face. The coordinates of the + bounding box are in the original image's scale. The bounding + box is computed to "frame" the face in accordance with human + expectations. It is based on the landmarker results. Note + that one or more x and/or y coordinates may not be generated + in the ``BoundingPoly`` (the polygon will be unbounded) if + only a partial face appears in the image to be annotated. + fd_bounding_poly (~.geometry.BoundingPoly): + The ``fd_bounding_poly`` bounding polygon is tighter than + the ``boundingPoly``, and encloses only the skin part of the + face. Typically, it is used to eliminate the face from any + image analysis that detects the "amount of skin" visible in + an image. It is not based on the landmarker results, only on + the initial face detection, hence the fd (face detection) + prefix. + landmarks (Sequence[~.image_annotator.FaceAnnotation.Landmark]): + Detected face landmarks. + roll_angle (float): + Roll angle, which indicates the amount of + clockwise/anti-clockwise rotation of the face relative to + the image vertical about the axis perpendicular to the face. + Range [-180,180]. + pan_angle (float): + Yaw angle, which indicates the leftward/rightward angle that + the face is pointing relative to the vertical plane + perpendicular to the image. Range [-180,180]. + tilt_angle (float): + Pitch angle, which indicates the upwards/downwards angle + that the face is pointing relative to the image's horizontal + plane. Range [-180,180]. + detection_confidence (float): + Detection confidence. Range [0, 1]. + landmarking_confidence (float): + Face landmarking confidence. Range [0, 1]. + joy_likelihood (~.image_annotator.Likelihood): + Joy likelihood. + sorrow_likelihood (~.image_annotator.Likelihood): + Sorrow likelihood. + anger_likelihood (~.image_annotator.Likelihood): + Anger likelihood. + surprise_likelihood (~.image_annotator.Likelihood): + Surprise likelihood. + under_exposed_likelihood (~.image_annotator.Likelihood): + Under-exposed likelihood. + blurred_likelihood (~.image_annotator.Likelihood): + Blurred likelihood. + headwear_likelihood (~.image_annotator.Likelihood): + Headwear likelihood. + """ + + class Landmark(proto.Message): + r"""A face-specific landmark (for example, a face feature). + + Attributes: + type_ (~.image_annotator.FaceAnnotation.Landmark.Type): + Face landmark type. + position (~.geometry.Position): + Face landmark position. + """ + + class Type(proto.Enum): + r"""Face landmark (feature) type. Left and right are defined from the + vantage of the viewer of the image without considering mirror + projections typical of photos. So, ``LEFT_EYE``, typically, is the + person's right eye. + """ + UNKNOWN_LANDMARK = 0 + LEFT_EYE = 1 + RIGHT_EYE = 2 + LEFT_OF_LEFT_EYEBROW = 3 + RIGHT_OF_LEFT_EYEBROW = 4 + LEFT_OF_RIGHT_EYEBROW = 5 + RIGHT_OF_RIGHT_EYEBROW = 6 + MIDPOINT_BETWEEN_EYES = 7 + NOSE_TIP = 8 + UPPER_LIP = 9 + LOWER_LIP = 10 + MOUTH_LEFT = 11 + MOUTH_RIGHT = 12 + MOUTH_CENTER = 13 + NOSE_BOTTOM_RIGHT = 14 + NOSE_BOTTOM_LEFT = 15 + NOSE_BOTTOM_CENTER = 16 + LEFT_EYE_TOP_BOUNDARY = 17 + LEFT_EYE_RIGHT_CORNER = 18 + LEFT_EYE_BOTTOM_BOUNDARY = 19 + LEFT_EYE_LEFT_CORNER = 20 + RIGHT_EYE_TOP_BOUNDARY = 21 + RIGHT_EYE_RIGHT_CORNER = 22 + RIGHT_EYE_BOTTOM_BOUNDARY = 23 + RIGHT_EYE_LEFT_CORNER = 24 + LEFT_EYEBROW_UPPER_MIDPOINT = 25 + RIGHT_EYEBROW_UPPER_MIDPOINT = 26 + LEFT_EAR_TRAGION = 27 + RIGHT_EAR_TRAGION = 28 + LEFT_EYE_PUPIL = 29 + RIGHT_EYE_PUPIL = 30 + FOREHEAD_GLABELLA = 31 + CHIN_GNATHION = 32 + CHIN_LEFT_GONION = 33 + CHIN_RIGHT_GONION = 34 + + type_ = proto.Field(proto.ENUM, number=3, enum="FaceAnnotation.Landmark.Type",) + + position = proto.Field(proto.MESSAGE, number=4, message=geometry.Position,) + + bounding_poly = proto.Field(proto.MESSAGE, number=1, message=geometry.BoundingPoly,) + + fd_bounding_poly = proto.Field( + proto.MESSAGE, number=2, message=geometry.BoundingPoly, + ) + + landmarks = proto.RepeatedField(proto.MESSAGE, number=3, message=Landmark,) + + roll_angle = proto.Field(proto.FLOAT, number=4) + + pan_angle = proto.Field(proto.FLOAT, number=5) + + tilt_angle = proto.Field(proto.FLOAT, number=6) + + detection_confidence = proto.Field(proto.FLOAT, number=7) + + landmarking_confidence = proto.Field(proto.FLOAT, number=8) + + joy_likelihood = proto.Field(proto.ENUM, number=9, enum="Likelihood",) + + sorrow_likelihood = proto.Field(proto.ENUM, number=10, enum="Likelihood",) + + anger_likelihood = proto.Field(proto.ENUM, number=11, enum="Likelihood",) + + surprise_likelihood = proto.Field(proto.ENUM, number=12, enum="Likelihood",) + + under_exposed_likelihood = proto.Field(proto.ENUM, number=13, enum="Likelihood",) + + blurred_likelihood = proto.Field(proto.ENUM, number=14, enum="Likelihood",) + + headwear_likelihood = proto.Field(proto.ENUM, number=15, enum="Likelihood",) + + +class LocationInfo(proto.Message): + r"""Detected entity location information. + + Attributes: + lat_lng (~.latlng.LatLng): + lat/long location coordinates. + """ + + lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng.LatLng,) + + +class Property(proto.Message): + r"""A ``Property`` consists of a user-supplied name/value pair. + + Attributes: + name (str): + Name of the property. + value (str): + Value of the property. + uint64_value (int): + Value of numeric properties. + """ + + name = proto.Field(proto.STRING, number=1) + + value = proto.Field(proto.STRING, number=2) + + uint64_value = proto.Field(proto.UINT64, number=3) + + +class EntityAnnotation(proto.Message): + r"""Set of detected entity features. + + Attributes: + mid (str): + Opaque entity ID. Some IDs may be available in `Google + Knowledge Graph Search + API `__. + locale (str): + The language code for the locale in which the entity textual + ``description`` is expressed. + description (str): + Entity textual description, expressed in its ``locale`` + language. + score (float): + Overall score of the result. Range [0, 1]. + confidence (float): + **Deprecated. Use ``score`` instead.** The accuracy of the + entity detection in an image. For example, for an image in + which the "Eiffel Tower" entity is detected, this field + represents the confidence that there is a tower in the query + image. Range [0, 1]. + topicality (float): + The relevancy of the ICA (Image Content Annotation) label to + the image. For example, the relevancy of "tower" is likely + higher to an image containing the detected "Eiffel Tower" + than to an image containing a detected distant towering + building, even though the confidence that there is a tower + in each image may be the same. Range [0, 1]. + bounding_poly (~.geometry.BoundingPoly): + Image region to which this entity belongs. Not produced for + ``LABEL_DETECTION`` features. + locations (Sequence[~.image_annotator.LocationInfo]): + The location information for the detected entity. Multiple + ``LocationInfo`` elements can be present because one + location may indicate the location of the scene in the + image, and another location may indicate the location of the + place where the image was taken. Location information is + usually present for landmarks. + properties (Sequence[~.image_annotator.Property]): + Some entities may have optional user-supplied ``Property`` + (name/value) fields, such a score or string that qualifies + the entity. + """ + + mid = proto.Field(proto.STRING, number=1) + + locale = proto.Field(proto.STRING, number=2) + + description = proto.Field(proto.STRING, number=3) + + score = proto.Field(proto.FLOAT, number=4) + + confidence = proto.Field(proto.FLOAT, number=5) + + topicality = proto.Field(proto.FLOAT, number=6) + + bounding_poly = proto.Field(proto.MESSAGE, number=7, message=geometry.BoundingPoly,) + + locations = proto.RepeatedField(proto.MESSAGE, number=8, message=LocationInfo,) + + properties = proto.RepeatedField(proto.MESSAGE, number=9, message=Property,) + + +class LocalizedObjectAnnotation(proto.Message): + r"""Set of detected objects with bounding boxes. + + Attributes: + mid (str): + Object ID that should align with + EntityAnnotation mid. + language_code (str): + The BCP-47 language code, such as "en-US" or "sr-Latn". For + more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + name (str): + Object name, expressed in its ``language_code`` language. + score (float): + Score of the result. Range [0, 1]. + bounding_poly (~.geometry.BoundingPoly): + Image region to which this object belongs. + This must be populated. + """ + + mid = proto.Field(proto.STRING, number=1) + + language_code = proto.Field(proto.STRING, number=2) + + name = proto.Field(proto.STRING, number=3) + + score = proto.Field(proto.FLOAT, number=4) + + bounding_poly = proto.Field(proto.MESSAGE, number=5, message=geometry.BoundingPoly,) + + +class SafeSearchAnnotation(proto.Message): + r"""Set of features pertaining to the image, computed by computer + vision methods over safe-search verticals (for example, adult, + spoof, medical, violence). + + Attributes: + adult (~.image_annotator.Likelihood): + Represents the adult content likelihood for + the image. Adult content may contain elements + such as nudity, pornographic images or cartoons, + or sexual activities. + spoof (~.image_annotator.Likelihood): + Spoof likelihood. The likelihood that an + modification was made to the image's canonical + version to make it appear funny or offensive. + medical (~.image_annotator.Likelihood): + Likelihood that this is a medical image. + violence (~.image_annotator.Likelihood): + Likelihood that this image contains violent + content. + racy (~.image_annotator.Likelihood): + Likelihood that the request image contains + racy content. Racy content may include (but is + not limited to) skimpy or sheer clothing, + strategically covered nudity, lewd or + provocative poses, or close-ups of sensitive + body areas. + adult_confidence (float): + Confidence of adult_score. Range [0, 1]. 0 means not + confident, 1 means very confident. + spoof_confidence (float): + Confidence of spoof_score. Range [0, 1]. 0 means not + confident, 1 means very confident. + medical_confidence (float): + Confidence of medical_score. Range [0, 1]. 0 means not + confident, 1 means very confident. + violence_confidence (float): + Confidence of violence_score. Range [0, 1]. 0 means not + confident, 1 means very confident. + racy_confidence (float): + Confidence of racy_score. Range [0, 1]. 0 means not + confident, 1 means very confident. + nsfw_confidence (float): + Confidence of nsfw_score. Range [0, 1]. 0 means not + confident, 1 means very confident. + """ + + adult = proto.Field(proto.ENUM, number=1, enum="Likelihood",) + + spoof = proto.Field(proto.ENUM, number=2, enum="Likelihood",) + + medical = proto.Field(proto.ENUM, number=3, enum="Likelihood",) + + violence = proto.Field(proto.ENUM, number=4, enum="Likelihood",) + + racy = proto.Field(proto.ENUM, number=9, enum="Likelihood",) + + adult_confidence = proto.Field(proto.FLOAT, number=16) + + spoof_confidence = proto.Field(proto.FLOAT, number=18) + + medical_confidence = proto.Field(proto.FLOAT, number=20) + + violence_confidence = proto.Field(proto.FLOAT, number=22) + + racy_confidence = proto.Field(proto.FLOAT, number=24) + + nsfw_confidence = proto.Field(proto.FLOAT, number=26) + + +class LatLongRect(proto.Message): + r"""Rectangle determined by min and max ``LatLng`` pairs. + + Attributes: + min_lat_lng (~.latlng.LatLng): + Min lat/long pair. + max_lat_lng (~.latlng.LatLng): + Max lat/long pair. + """ + + min_lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng.LatLng,) + + max_lat_lng = proto.Field(proto.MESSAGE, number=2, message=latlng.LatLng,) + + +class ColorInfo(proto.Message): + r"""Color information consists of RGB channels, score, and the + fraction of the image that the color occupies in the image. + + Attributes: + color (~.gt_color.Color): + RGB components of the color. + score (float): + Image-specific score for this color. Value in range [0, 1]. + pixel_fraction (float): + The fraction of pixels the color occupies in the image. + Value in range [0, 1]. + """ + + color = proto.Field(proto.MESSAGE, number=1, message=gt_color.Color,) + + score = proto.Field(proto.FLOAT, number=2) + + pixel_fraction = proto.Field(proto.FLOAT, number=3) + + +class DominantColorsAnnotation(proto.Message): + r"""Set of dominant colors and their corresponding scores. + + Attributes: + colors (Sequence[~.image_annotator.ColorInfo]): + RGB color values with their score and pixel + fraction. + """ + + colors = proto.RepeatedField(proto.MESSAGE, number=1, message=ColorInfo,) + + +class ImageProperties(proto.Message): + r"""Stores image properties, such as dominant colors. + + Attributes: + dominant_colors (~.image_annotator.DominantColorsAnnotation): + If present, dominant colors completed + successfully. + """ + + dominant_colors = proto.Field( + proto.MESSAGE, number=1, message=DominantColorsAnnotation, + ) + + +class CropHint(proto.Message): + r"""Single crop hint that is used to generate a new crop when + serving an image. + + Attributes: + bounding_poly (~.geometry.BoundingPoly): + The bounding polygon for the crop region. The + coordinates of the bounding box are in the + original image's scale. + confidence (float): + Confidence of this being a salient region. Range [0, 1]. + importance_fraction (float): + Fraction of importance of this salient region + with respect to the original image. + """ + + bounding_poly = proto.Field(proto.MESSAGE, number=1, message=geometry.BoundingPoly,) + + confidence = proto.Field(proto.FLOAT, number=2) + + importance_fraction = proto.Field(proto.FLOAT, number=3) + + +class CropHintsAnnotation(proto.Message): + r"""Set of crop hints that are used to generate new crops when + serving images. + + Attributes: + crop_hints (Sequence[~.image_annotator.CropHint]): + Crop hint results. + """ + + crop_hints = proto.RepeatedField(proto.MESSAGE, number=1, message=CropHint,) + + +class CropHintsParams(proto.Message): + r"""Parameters for crop hints annotation request. + + Attributes: + aspect_ratios (Sequence[float]): + Aspect ratios in floats, representing the + ratio of the width to the height of the image. + For example, if the desired aspect ratio is 4/3, + the corresponding float value should be 1.33333. + If not specified, the best possible crop is + returned. The number of provided aspect ratios + is limited to a maximum of 16; any aspect ratios + provided after the 16th are ignored. + """ + + aspect_ratios = proto.RepeatedField(proto.FLOAT, number=1) + + +class WebDetectionParams(proto.Message): + r"""Parameters for web detection request. + + Attributes: + include_geo_results (bool): + Whether to include results derived from the + geo information in the image. + """ + + include_geo_results = proto.Field(proto.BOOL, number=2) + + +class ImageContext(proto.Message): + r"""Image context and/or feature-specific parameters. + + Attributes: + lat_long_rect (~.image_annotator.LatLongRect): + Not used. + language_hints (Sequence[str]): + List of languages to use for TEXT_DETECTION. In most cases, + an empty value yields the best results since it enables + automatic language detection. For languages based on the + Latin alphabet, setting ``language_hints`` is not needed. In + rare cases, when the language of the text in the image is + known, setting a hint will help get better results (although + it will be a significant hindrance if the hint is wrong). + Text detection returns an error if one or more of the + specified languages is not one of the `supported + languages `__. + crop_hints_params (~.image_annotator.CropHintsParams): + Parameters for crop hints annotation request. + product_search_params (~.product_search.ProductSearchParams): + Parameters for product search. + web_detection_params (~.image_annotator.WebDetectionParams): + Parameters for web detection. + """ + + lat_long_rect = proto.Field(proto.MESSAGE, number=1, message=LatLongRect,) + + language_hints = proto.RepeatedField(proto.STRING, number=2) + + crop_hints_params = proto.Field(proto.MESSAGE, number=4, message=CropHintsParams,) + + product_search_params = proto.Field( + proto.MESSAGE, number=5, message=product_search.ProductSearchParams, + ) + + web_detection_params = proto.Field( + proto.MESSAGE, number=6, message=WebDetectionParams, + ) + + +class AnnotateImageRequest(proto.Message): + r"""Request for performing Google Cloud Vision API tasks over a + user-provided image, with user-requested features, and with + context information. + + Attributes: + image (~.image_annotator.Image): + The image to be processed. + features (Sequence[~.image_annotator.Feature]): + Requested features. + image_context (~.image_annotator.ImageContext): + Additional context that may accompany the + image. + """ + + image = proto.Field(proto.MESSAGE, number=1, message=Image,) + + features = proto.RepeatedField(proto.MESSAGE, number=2, message=Feature,) + + image_context = proto.Field(proto.MESSAGE, number=3, message=ImageContext,) + + +class ImageAnnotationContext(proto.Message): + r"""If an image was produced from a file (e.g. a PDF), this + message gives information about the source of that image. + + Attributes: + uri (str): + The URI of the file used to produce the + image. + page_number (int): + If the file was a PDF or TIFF, this field + gives the page number within the file used to + produce the image. + """ + + uri = proto.Field(proto.STRING, number=1) + + page_number = proto.Field(proto.INT32, number=2) + + +class AnnotateImageResponse(proto.Message): + r"""Response to an image annotation request. + + Attributes: + face_annotations (Sequence[~.image_annotator.FaceAnnotation]): + If present, face detection has completed + successfully. + landmark_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, landmark detection has completed + successfully. + logo_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, logo detection has completed + successfully. + label_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, label detection has completed + successfully. + localized_object_annotations (Sequence[~.image_annotator.LocalizedObjectAnnotation]): + If present, localized object detection has + completed successfully. This will be sorted + descending by confidence score. + text_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, text (OCR) detection has + completed successfully. + full_text_annotation (~.text_annotation.TextAnnotation): + If present, text (OCR) detection or document + (OCR) text detection has completed successfully. + This annotation provides the structural + hierarchy for the OCR detected text. + safe_search_annotation (~.image_annotator.SafeSearchAnnotation): + If present, safe-search annotation has + completed successfully. + image_properties_annotation (~.image_annotator.ImageProperties): + If present, image properties were extracted + successfully. + crop_hints_annotation (~.image_annotator.CropHintsAnnotation): + If present, crop hints have completed + successfully. + web_detection (~.gcv_web_detection.WebDetection): + If present, web detection has completed + successfully. + product_search_results (~.product_search.ProductSearchResults): + If present, product search has completed + successfully. + error (~.status.Status): + If set, represents the error message for the operation. Note + that filled-in image annotations are guaranteed to be + correct, even when ``error`` is set. + context (~.image_annotator.ImageAnnotationContext): + If present, contextual information is needed + to understand where this image comes from. + """ + + face_annotations = proto.RepeatedField( + proto.MESSAGE, number=1, message=FaceAnnotation, + ) + + landmark_annotations = proto.RepeatedField( + proto.MESSAGE, number=2, message=EntityAnnotation, + ) + + logo_annotations = proto.RepeatedField( + proto.MESSAGE, number=3, message=EntityAnnotation, + ) + + label_annotations = proto.RepeatedField( + proto.MESSAGE, number=4, message=EntityAnnotation, + ) + + localized_object_annotations = proto.RepeatedField( + proto.MESSAGE, number=22, message=LocalizedObjectAnnotation, + ) + + text_annotations = proto.RepeatedField( + proto.MESSAGE, number=5, message=EntityAnnotation, + ) + + full_text_annotation = proto.Field( + proto.MESSAGE, number=12, message=text_annotation.TextAnnotation, + ) + + safe_search_annotation = proto.Field( + proto.MESSAGE, number=6, message=SafeSearchAnnotation, + ) + + image_properties_annotation = proto.Field( + proto.MESSAGE, number=8, message=ImageProperties, + ) + + crop_hints_annotation = proto.Field( + proto.MESSAGE, number=11, message=CropHintsAnnotation, + ) + + web_detection = proto.Field( + proto.MESSAGE, number=13, message=gcv_web_detection.WebDetection, + ) + + product_search_results = proto.Field( + proto.MESSAGE, number=14, message=product_search.ProductSearchResults, + ) + + error = proto.Field(proto.MESSAGE, number=9, message=status.Status,) + + context = proto.Field(proto.MESSAGE, number=21, message=ImageAnnotationContext,) + + +class BatchAnnotateImagesRequest(proto.Message): + r"""Multiple image annotation requests are batched into a single + service call. + + Attributes: + requests (Sequence[~.image_annotator.AnnotateImageRequest]): + Required. Individual image annotation + requests for this batch. + parent (str): + Optional. Target project and location to make a call. + + Format: ``projects/{project-id}/locations/{location-id}``. + + If no parent is specified, a region will be chosen + automatically. + + Supported location-ids: ``us``: USA country only, ``asia``: + East asia areas, like Japan, Taiwan, ``eu``: The European + Union. + + Example: ``projects/project-A/locations/eu``. + """ + + requests = proto.RepeatedField( + proto.MESSAGE, number=1, message=AnnotateImageRequest, + ) + + parent = proto.Field(proto.STRING, number=4) + + +class BatchAnnotateImagesResponse(proto.Message): + r"""Response to a batch image annotation request. + + Attributes: + responses (Sequence[~.image_annotator.AnnotateImageResponse]): + Individual responses to image annotation + requests within the batch. + """ + + responses = proto.RepeatedField( + proto.MESSAGE, number=1, message=AnnotateImageResponse, + ) + + +class AnnotateFileRequest(proto.Message): + r"""A request to annotate one single file, e.g. a PDF, TIFF or + GIF file. + + Attributes: + input_config (~.image_annotator.InputConfig): + Required. Information about the input file. + features (Sequence[~.image_annotator.Feature]): + Required. Requested features. + image_context (~.image_annotator.ImageContext): + Additional context that may accompany the + image(s) in the file. + pages (Sequence[int]): + Pages of the file to perform image + annotation. + Pages starts from 1, we assume the first page of + the file is page 1. At most 5 pages are + supported per request. Pages can be negative. + Page 1 means the first page. + Page 2 means the second page. + Page -1 means the last page. + Page -2 means the second to the last page. + + If the file is GIF instead of PDF or TIFF, page + refers to GIF frames. + If this field is empty, by default the service + performs image annotation for the first 5 pages + of the file. + """ + + input_config = proto.Field(proto.MESSAGE, number=1, message="InputConfig",) + + features = proto.RepeatedField(proto.MESSAGE, number=2, message=Feature,) + + image_context = proto.Field(proto.MESSAGE, number=3, message=ImageContext,) + + pages = proto.RepeatedField(proto.INT32, number=4) + + +class AnnotateFileResponse(proto.Message): + r"""Response to a single file annotation request. A file may + contain one or more images, which individually have their own + responses. + + Attributes: + input_config (~.image_annotator.InputConfig): + Information about the file for which this + response is generated. + responses (Sequence[~.image_annotator.AnnotateImageResponse]): + Individual responses to images found within the file. This + field will be empty if the ``error`` field is set. + total_pages (int): + This field gives the total number of pages in + the file. + error (~.status.Status): + If set, represents the error message for the failed request. + The ``responses`` field will not be set in this case. + """ + + input_config = proto.Field(proto.MESSAGE, number=1, message="InputConfig",) + + responses = proto.RepeatedField( + proto.MESSAGE, number=2, message=AnnotateImageResponse, + ) + + total_pages = proto.Field(proto.INT32, number=3) + + error = proto.Field(proto.MESSAGE, number=4, message=status.Status,) + + +class BatchAnnotateFilesRequest(proto.Message): + r"""A list of requests to annotate files using the + BatchAnnotateFiles API. + + Attributes: + requests (Sequence[~.image_annotator.AnnotateFileRequest]): + Required. The list of file annotation + requests. Right now we support only one + AnnotateFileRequest in + BatchAnnotateFilesRequest. + parent (str): + Optional. Target project and location to make a call. + + Format: ``projects/{project-id}/locations/{location-id}``. + + If no parent is specified, a region will be chosen + automatically. + + Supported location-ids: ``us``: USA country only, ``asia``: + East asia areas, like Japan, Taiwan, ``eu``: The European + Union. + + Example: ``projects/project-A/locations/eu``. + """ + + requests = proto.RepeatedField( + proto.MESSAGE, number=1, message=AnnotateFileRequest, + ) + + parent = proto.Field(proto.STRING, number=3) + + +class BatchAnnotateFilesResponse(proto.Message): + r"""A list of file annotation responses. + + Attributes: + responses (Sequence[~.image_annotator.AnnotateFileResponse]): + The list of file annotation responses, each + response corresponding to each + AnnotateFileRequest in + BatchAnnotateFilesRequest. + """ + + responses = proto.RepeatedField( + proto.MESSAGE, number=1, message=AnnotateFileResponse, + ) + + +class AsyncAnnotateFileRequest(proto.Message): + r"""An offline file annotation request. + + Attributes: + input_config (~.image_annotator.InputConfig): + Required. Information about the input file. + features (Sequence[~.image_annotator.Feature]): + Required. Requested features. + image_context (~.image_annotator.ImageContext): + Additional context that may accompany the + image(s) in the file. + output_config (~.image_annotator.OutputConfig): + Required. The desired output location and + metadata (e.g. format). + """ + + input_config = proto.Field(proto.MESSAGE, number=1, message="InputConfig",) + + features = proto.RepeatedField(proto.MESSAGE, number=2, message=Feature,) + + image_context = proto.Field(proto.MESSAGE, number=3, message=ImageContext,) + + output_config = proto.Field(proto.MESSAGE, number=4, message="OutputConfig",) + + +class AsyncAnnotateFileResponse(proto.Message): + r"""The response for a single offline file annotation request. + + Attributes: + output_config (~.image_annotator.OutputConfig): + The output location and metadata from + AsyncAnnotateFileRequest. + """ + + output_config = proto.Field(proto.MESSAGE, number=1, message="OutputConfig",) + + +class AsyncBatchAnnotateImagesRequest(proto.Message): + r"""Request for async image annotation for a list of images. + + Attributes: + requests (Sequence[~.image_annotator.AnnotateImageRequest]): + Required. Individual image annotation + requests for this batch. + output_config (~.image_annotator.OutputConfig): + Required. The desired output location and + metadata (e.g. format). + parent (str): + Optional. Target project and location to make a call. + + Format: ``projects/{project-id}/locations/{location-id}``. + + If no parent is specified, a region will be chosen + automatically. + + Supported location-ids: ``us``: USA country only, ``asia``: + East asia areas, like Japan, Taiwan, ``eu``: The European + Union. + + Example: ``projects/project-A/locations/eu``. + """ + + requests = proto.RepeatedField( + proto.MESSAGE, number=1, message=AnnotateImageRequest, + ) + + output_config = proto.Field(proto.MESSAGE, number=2, message="OutputConfig",) + + parent = proto.Field(proto.STRING, number=4) + + +class AsyncBatchAnnotateImagesResponse(proto.Message): + r"""Response to an async batch image annotation request. + + Attributes: + output_config (~.image_annotator.OutputConfig): + The output location and metadata from + AsyncBatchAnnotateImagesRequest. + """ + + output_config = proto.Field(proto.MESSAGE, number=1, message="OutputConfig",) + + +class AsyncBatchAnnotateFilesRequest(proto.Message): + r"""Multiple async file annotation requests are batched into a + single service call. + + Attributes: + requests (Sequence[~.image_annotator.AsyncAnnotateFileRequest]): + Required. Individual async file annotation + requests for this batch. + parent (str): + Optional. Target project and location to make a call. + + Format: ``projects/{project-id}/locations/{location-id}``. + + If no parent is specified, a region will be chosen + automatically. + + Supported location-ids: ``us``: USA country only, ``asia``: + East asia areas, like Japan, Taiwan, ``eu``: The European + Union. + + Example: ``projects/project-A/locations/eu``. + """ + + requests = proto.RepeatedField( + proto.MESSAGE, number=1, message=AsyncAnnotateFileRequest, + ) + + parent = proto.Field(proto.STRING, number=4) + + +class AsyncBatchAnnotateFilesResponse(proto.Message): + r"""Response to an async batch file annotation request. + + Attributes: + responses (Sequence[~.image_annotator.AsyncAnnotateFileResponse]): + The list of file annotation responses, one + for each request in + AsyncBatchAnnotateFilesRequest. + """ + + responses = proto.RepeatedField( + proto.MESSAGE, number=1, message=AsyncAnnotateFileResponse, + ) + + +class InputConfig(proto.Message): + r"""The desired input location and metadata. + + Attributes: + gcs_source (~.image_annotator.GcsSource): + The Google Cloud Storage location to read the + input from. + content (bytes): + File content, represented as a stream of bytes. Note: As + with all ``bytes`` fields, protobuffers use a pure binary + representation, whereas JSON representations use base64. + + Currently, this field only works for BatchAnnotateFiles + requests. It does not work for AsyncBatchAnnotateFiles + requests. + mime_type (str): + The type of the file. Currently only + "application/pdf", "image/tiff" and "image/gif" + are supported. Wildcards are not supported. + """ + + gcs_source = proto.Field(proto.MESSAGE, number=1, message="GcsSource",) + + content = proto.Field(proto.BYTES, number=3) + + mime_type = proto.Field(proto.STRING, number=2) + + +class OutputConfig(proto.Message): + r"""The desired output location and metadata. + + Attributes: + gcs_destination (~.image_annotator.GcsDestination): + The Google Cloud Storage location to write + the output(s) to. + batch_size (int): + The max number of response protos to put into each output + JSON file on Google Cloud Storage. The valid range is [1, + 100]. If not specified, the default value is 20. + + For example, for one pdf file with 100 pages, 100 response + protos will be generated. If ``batch_size`` = 20, then 5 + json files each containing 20 response protos will be + written under the prefix ``gcs_destination``.\ ``uri``. + + Currently, batch_size only applies to GcsDestination, with + potential future support for other output configurations. + """ + + gcs_destination = proto.Field(proto.MESSAGE, number=1, message="GcsDestination",) + + batch_size = proto.Field(proto.INT32, number=2) + + +class GcsSource(proto.Message): + r"""The Google Cloud Storage location where the input will be + read from. + + Attributes: + uri (str): + Google Cloud Storage URI for the input file. + This must only be a Google Cloud Storage object. + Wildcards are not currently supported. + """ + + uri = proto.Field(proto.STRING, number=1) + + +class GcsDestination(proto.Message): + r"""The Google Cloud Storage location where the output will be + written to. + + Attributes: + uri (str): + Google Cloud Storage URI prefix where the results will be + stored. Results will be in JSON format and preceded by its + corresponding input URI prefix. This field can either + represent a gcs file prefix or gcs directory. In either + case, the uri should be unique because in order to get all + of the output files, you will need to do a wildcard gcs + search on the uri prefix you provide. + + Examples: + + - File Prefix: gs://bucket-name/here/filenameprefix The + output files will be created in gs://bucket-name/here/ + and the names of the output files will begin with + "filenameprefix". + + - Directory Prefix: gs://bucket-name/some/location/ The + output files will be created in + gs://bucket-name/some/location/ and the names of the + output files could be anything because there was no + filename prefix specified. + + If multiple outputs, each response is still + AnnotateFileResponse, each of which contains some subset of + the full list of AnnotateImageResponse. Multiple outputs can + happen if, for example, the output JSON is too large and + overflows into multiple sharded files. + """ + + uri = proto.Field(proto.STRING, number=1) + + +class OperationMetadata(proto.Message): + r"""Contains metadata for the BatchAnnotateImages operation. + + Attributes: + state (~.image_annotator.OperationMetadata.State): + Current state of the batch operation. + create_time (~.timestamp.Timestamp): + The time when the batch request was received. + update_time (~.timestamp.Timestamp): + The time when the operation result was last + updated. + """ + + class State(proto.Enum): + r"""Batch operation states.""" + STATE_UNSPECIFIED = 0 + CREATED = 1 + RUNNING = 2 + DONE = 3 + CANCELLED = 4 + + state = proto.Field(proto.ENUM, number=1, enum=State,) + + create_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + + update_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1/types/product_search.py b/google/cloud/vision_v1/types/product_search.py new file mode 100644 index 00000000..6ae8f236 --- /dev/null +++ b/google/cloud/vision_v1/types/product_search.py @@ -0,0 +1,185 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.vision_v1.types import geometry +from google.cloud.vision_v1.types import product_search_service +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1", + manifest={"ProductSearchParams", "ProductSearchResults",}, +) + + +class ProductSearchParams(proto.Message): + r"""Parameters for a product search request. + + Attributes: + bounding_poly (~.geometry.BoundingPoly): + The bounding polygon around the area of + interest in the image. Optional. If it is not + specified, system discretion will be applied. + product_set (str): + The resource name of a + [ProductSet][google.cloud.vision.v1.ProductSet] to be + searched for similar images. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID``. + product_categories (Sequence[str]): + The list of product categories to search in. + Currently, we only consider the first category, + and either "homegoods-v2", "apparel-v2", + "toys-v2", "packagedgoods-v1", or "general-v1" + should be specified. The legacy categories + "homegoods", "apparel", and "toys" are still + supported but will be deprecated. For new + products, please use "homegoods-v2", + "apparel-v2", or "toys-v2" for better product + search accuracy. It is recommended to migrate + existing products to these categories as well. + filter (str): + The filtering expression. This can be used to + restrict search results based on Product labels. + We currently support an AND of OR of key-value + expressions, where each expression within an OR + must have the same key. An '=' should be used to + connect the key and value. + For example, "(color = red OR color = blue) AND + brand = Google" is acceptable, but "(color = red + OR brand = Google)" is not acceptable. "color: + red" is not acceptable because it uses a ':' + instead of an '='. + """ + + bounding_poly = proto.Field(proto.MESSAGE, number=9, message=geometry.BoundingPoly,) + + product_set = proto.Field(proto.STRING, number=6) + + product_categories = proto.RepeatedField(proto.STRING, number=7) + + filter = proto.Field(proto.STRING, number=8) + + +class ProductSearchResults(proto.Message): + r"""Results for a product search request. + + Attributes: + index_time (~.timestamp.Timestamp): + Timestamp of the index which provided these + results. Products added to the product set and + products removed from the product set after this + time are not reflected in the current results. + results (Sequence[~.product_search.ProductSearchResults.Result]): + List of results, one for each product match. + product_grouped_results (Sequence[~.product_search.ProductSearchResults.GroupedResult]): + List of results grouped by products detected + in the query image. Each entry corresponds to + one bounding polygon in the query image, and + contains the matching products specific to that + region. There may be duplicate product matches + in the union of all the per-product results. + """ + + class Result(proto.Message): + r"""Information about a product. + + Attributes: + product (~.product_search_service.Product): + The Product. + score (float): + A confidence level on the match, ranging from + 0 (no confidence) to 1 (full confidence). + image (str): + The resource name of the image from the + product that is the closest match to the query. + """ + + product = proto.Field( + proto.MESSAGE, number=1, message=product_search_service.Product, + ) + + score = proto.Field(proto.FLOAT, number=2) + + image = proto.Field(proto.STRING, number=3) + + class ObjectAnnotation(proto.Message): + r"""Prediction for what the object in the bounding box is. + + Attributes: + mid (str): + Object ID that should align with + EntityAnnotation mid. + language_code (str): + The BCP-47 language code, such as "en-US" or "sr-Latn". For + more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + name (str): + Object name, expressed in its ``language_code`` language. + score (float): + Score of the result. Range [0, 1]. + """ + + mid = proto.Field(proto.STRING, number=1) + + language_code = proto.Field(proto.STRING, number=2) + + name = proto.Field(proto.STRING, number=3) + + score = proto.Field(proto.FLOAT, number=4) + + class GroupedResult(proto.Message): + r"""Information about the products similar to a single product in + a query image. + + Attributes: + bounding_poly (~.geometry.BoundingPoly): + The bounding polygon around the product + detected in the query image. + results (Sequence[~.product_search.ProductSearchResults.Result]): + List of results, one for each product match. + object_annotations (Sequence[~.product_search.ProductSearchResults.ObjectAnnotation]): + List of generic predictions for the object in + the bounding box. + """ + + bounding_poly = proto.Field( + proto.MESSAGE, number=1, message=geometry.BoundingPoly, + ) + + results = proto.RepeatedField( + proto.MESSAGE, number=2, message="ProductSearchResults.Result", + ) + + object_annotations = proto.RepeatedField( + proto.MESSAGE, number=3, message="ProductSearchResults.ObjectAnnotation", + ) + + index_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + results = proto.RepeatedField(proto.MESSAGE, number=5, message=Result,) + + product_grouped_results = proto.RepeatedField( + proto.MESSAGE, number=6, message=GroupedResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1/types/product_search_service.py b/google/cloud/vision_v1/types/product_search_service.py new file mode 100644 index 00000000..0c88a647 --- /dev/null +++ b/google/cloud/vision_v1/types/product_search_service.py @@ -0,0 +1,891 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.vision_v1.types import geometry +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1", + manifest={ + "Product", + "ProductSet", + "ReferenceImage", + "CreateProductRequest", + "ListProductsRequest", + "ListProductsResponse", + "GetProductRequest", + "UpdateProductRequest", + "DeleteProductRequest", + "CreateProductSetRequest", + "ListProductSetsRequest", + "ListProductSetsResponse", + "GetProductSetRequest", + "UpdateProductSetRequest", + "DeleteProductSetRequest", + "CreateReferenceImageRequest", + "ListReferenceImagesRequest", + "ListReferenceImagesResponse", + "GetReferenceImageRequest", + "DeleteReferenceImageRequest", + "AddProductToProductSetRequest", + "RemoveProductFromProductSetRequest", + "ListProductsInProductSetRequest", + "ListProductsInProductSetResponse", + "ImportProductSetsGcsSource", + "ImportProductSetsInputConfig", + "ImportProductSetsRequest", + "ImportProductSetsResponse", + "BatchOperationMetadata", + "ProductSetPurgeConfig", + "PurgeProductsRequest", + }, +) + + +class Product(proto.Message): + r"""A Product contains ReferenceImages. + + Attributes: + name (str): + The resource name of the product. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + + This field is ignored when creating a product. + display_name (str): + The user-provided name for this Product. Must + not be empty. Must be at most 4096 characters + long. + description (str): + User-provided metadata to be stored with this + product. Must be at most 4096 characters long. + product_category (str): + Immutable. The category for the product + identified by the reference image. This should + be either "homegoods-v2", "apparel-v2", or + "toys-v2". The legacy categories "homegoods", + "apparel", and "toys" are still supported, but + these should not be used for new products. + product_labels (Sequence[~.product_search_service.Product.KeyValue]): + Key-value pairs that can be attached to a product. At query + time, constraints can be specified based on the + product_labels. + + Note that integer values can be provided as strings, e.g. + "1199". Only strings with integer values can match a + range-based restriction which is to be supported soon. + + Multiple values can be assigned to the same key. One product + may have up to 500 product_labels. + + Notice that the total number of distinct product_labels over + all products in one ProductSet cannot exceed 1M, otherwise + the product search pipeline will refuse to work for that + ProductSet. + """ + + class KeyValue(proto.Message): + r"""A product label represented as a key-value pair. + + Attributes: + key (str): + The key of the label attached to the product. + Cannot be empty and cannot exceed 128 bytes. + value (str): + The value of the label attached to the + product. Cannot be empty and cannot exceed 128 + bytes. + """ + + key = proto.Field(proto.STRING, number=1) + + value = proto.Field(proto.STRING, number=2) + + name = proto.Field(proto.STRING, number=1) + + display_name = proto.Field(proto.STRING, number=2) + + description = proto.Field(proto.STRING, number=3) + + product_category = proto.Field(proto.STRING, number=4) + + product_labels = proto.RepeatedField(proto.MESSAGE, number=5, message=KeyValue,) + + +class ProductSet(proto.Message): + r"""A ProductSet contains Products. A ProductSet can contain a + maximum of 1 million reference images. If the limit is exceeded, + periodic indexing will fail. + + Attributes: + name (str): + The resource name of the ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID``. + + This field is ignored when creating a ProductSet. + display_name (str): + The user-provided name for this ProductSet. + Must not be empty. Must be at most 4096 + characters long. + index_time (~.timestamp.Timestamp): + Output only. The time at which this + ProductSet was last indexed. Query results will + reflect all updates before this time. If this + ProductSet has never been indexed, this + timestamp is the default value + "1970-01-01T00:00:00Z". + + This field is ignored when creating a + ProductSet. + index_error (~.status.Status): + Output only. If there was an error with + indexing the product set, the field is + populated. + This field is ignored when creating a + ProductSet. + """ + + name = proto.Field(proto.STRING, number=1) + + display_name = proto.Field(proto.STRING, number=2) + + index_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + index_error = proto.Field(proto.MESSAGE, number=4, message=status.Status,) + + +class ReferenceImage(proto.Message): + r"""A ``ReferenceImage`` represents a product image and its associated + metadata, such as bounding boxes. + + Attributes: + name (str): + The resource name of the reference image. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. + + This field is ignored when creating a reference image. + uri (str): + Required. The Google Cloud Storage URI of the reference + image. + + The URI must start with ``gs://``. + bounding_polys (Sequence[~.geometry.BoundingPoly]): + Optional. Bounding polygons around the areas + of interest in the reference image. If this + field is empty, the system will try to detect + regions of interest. At most 10 bounding + polygons will be used. + The provided shape is converted into a non- + rotated rectangle. Once converted, the small + edge of the rectangle must be greater than or + equal to 300 pixels. The aspect ratio must be + 1:4 or less (i.e. 1:3 is ok; 1:5 is not). + """ + + name = proto.Field(proto.STRING, number=1) + + uri = proto.Field(proto.STRING, number=2) + + bounding_polys = proto.RepeatedField( + proto.MESSAGE, number=3, message=geometry.BoundingPoly, + ) + + +class CreateProductRequest(proto.Message): + r"""Request message for the ``CreateProduct`` method. + + Attributes: + parent (str): + Required. The project in which the Product should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + product (~.product_search_service.Product): + Required. The product to create. + product_id (str): + A user-supplied resource id for this Product. If set, the + server will attempt to use this value as the resource id. If + it is already in use, an error is returned with code + ALREADY_EXISTS. Must be at most 128 characters long. It + cannot contain the character ``/``. + """ + + parent = proto.Field(proto.STRING, number=1) + + product = proto.Field(proto.MESSAGE, number=2, message=Product,) + + product_id = proto.Field(proto.STRING, number=3) + + +class ListProductsRequest(proto.Message): + r"""Request message for the ``ListProducts`` method. + + Attributes: + parent (str): + Required. The project OR ProductSet from which Products + should be listed. + + Format: ``projects/PROJECT_ID/locations/LOC_ID`` + page_size (int): + The maximum number of items to return. + Default 10, maximum 100. + page_token (str): + The next_page_token returned from a previous List request, + if any. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListProductsResponse(proto.Message): + r"""Response message for the ``ListProducts`` method. + + Attributes: + products (Sequence[~.product_search_service.Product]): + List of products. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + products = proto.RepeatedField(proto.MESSAGE, number=1, message=Product,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetProductRequest(proto.Message): + r"""Request message for the ``GetProduct`` method. + + Attributes: + name (str): + Required. Resource name of the Product to get. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + +class UpdateProductRequest(proto.Message): + r"""Request message for the ``UpdateProduct`` method. + + Attributes: + product (~.product_search_service.Product): + Required. The Product resource which replaces + the one on the server. product.name is + immutable. + update_mask (~.field_mask.FieldMask): + The [FieldMask][google.protobuf.FieldMask] that specifies + which fields to update. If update_mask isn't specified, all + mutable fields are to be updated. Valid mask paths include + ``product_labels``, ``display_name``, and ``description``. + """ + + product = proto.Field(proto.MESSAGE, number=1, message=Product,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class DeleteProductRequest(proto.Message): + r"""Request message for the ``DeleteProduct`` method. + + Attributes: + name (str): + Required. Resource name of product to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + +class CreateProductSetRequest(proto.Message): + r"""Request message for the ``CreateProductSet`` method. + + Attributes: + parent (str): + Required. The project in which the ProductSet should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + product_set (~.product_search_service.ProductSet): + Required. The ProductSet to create. + product_set_id (str): + A user-supplied resource id for this ProductSet. If set, the + server will attempt to use this value as the resource id. If + it is already in use, an error is returned with code + ALREADY_EXISTS. Must be at most 128 characters long. It + cannot contain the character ``/``. + """ + + parent = proto.Field(proto.STRING, number=1) + + product_set = proto.Field(proto.MESSAGE, number=2, message=ProductSet,) + + product_set_id = proto.Field(proto.STRING, number=3) + + +class ListProductSetsRequest(proto.Message): + r"""Request message for the ``ListProductSets`` method. + + Attributes: + parent (str): + Required. The project from which ProductSets should be + listed. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + page_size (int): + The maximum number of items to return. + Default 10, maximum 100. + page_token (str): + The next_page_token returned from a previous List request, + if any. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListProductSetsResponse(proto.Message): + r"""Response message for the ``ListProductSets`` method. + + Attributes: + product_sets (Sequence[~.product_search_service.ProductSet]): + List of ProductSets. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + product_sets = proto.RepeatedField(proto.MESSAGE, number=1, message=ProductSet,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetProductSetRequest(proto.Message): + r"""Request message for the ``GetProductSet`` method. + + Attributes: + name (str): + Required. Resource name of the ProductSet to get. + + Format is: + ``projects/PROJECT_ID/locations/LOG_ID/productSets/PRODUCT_SET_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + +class UpdateProductSetRequest(proto.Message): + r"""Request message for the ``UpdateProductSet`` method. + + Attributes: + product_set (~.product_search_service.ProductSet): + Required. The ProductSet resource which + replaces the one on the server. + update_mask (~.field_mask.FieldMask): + The [FieldMask][google.protobuf.FieldMask] that specifies + which fields to update. If update_mask isn't specified, all + mutable fields are to be updated. Valid mask path is + ``display_name``. + """ + + product_set = proto.Field(proto.MESSAGE, number=1, message=ProductSet,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class DeleteProductSetRequest(proto.Message): + r"""Request message for the ``DeleteProductSet`` method. + + Attributes: + name (str): + Required. Resource name of the ProductSet to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + +class CreateReferenceImageRequest(proto.Message): + r"""Request message for the ``CreateReferenceImage`` method. + + Attributes: + parent (str): + Required. Resource name of the product in which to create + the reference image. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + reference_image (~.product_search_service.ReferenceImage): + Required. The reference image to create. + If an image ID is specified, it is ignored. + reference_image_id (str): + A user-supplied resource id for the ReferenceImage to be + added. If set, the server will attempt to use this value as + the resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + """ + + parent = proto.Field(proto.STRING, number=1) + + reference_image = proto.Field(proto.MESSAGE, number=2, message=ReferenceImage,) + + reference_image_id = proto.Field(proto.STRING, number=3) + + +class ListReferenceImagesRequest(proto.Message): + r"""Request message for the ``ListReferenceImages`` method. + + Attributes: + parent (str): + Required. Resource name of the product containing the + reference images. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + page_size (int): + The maximum number of items to return. + Default 10, maximum 100. + page_token (str): + A token identifying a page of results to be returned. This + is the value of ``nextPageToken`` returned in a previous + reference image list request. + + Defaults to the first page if not specified. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListReferenceImagesResponse(proto.Message): + r"""Response message for the ``ListReferenceImages`` method. + + Attributes: + reference_images (Sequence[~.product_search_service.ReferenceImage]): + The list of reference images. + page_size (int): + The maximum number of items to return. + Default 10, maximum 100. + next_page_token (str): + The next_page_token returned from a previous List request, + if any. + """ + + @property + def raw_page(self): + return self + + reference_images = proto.RepeatedField( + proto.MESSAGE, number=1, message=ReferenceImage, + ) + + page_size = proto.Field(proto.INT32, number=2) + + next_page_token = proto.Field(proto.STRING, number=3) + + +class GetReferenceImageRequest(proto.Message): + r"""Request message for the ``GetReferenceImage`` method. + + Attributes: + name (str): + Required. The resource name of the ReferenceImage to get. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class DeleteReferenceImageRequest(proto.Message): + r"""Request message for the ``DeleteReferenceImage`` method. + + Attributes: + name (str): + Required. The resource name of the reference image to + delete. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + +class AddProductToProductSetRequest(proto.Message): + r"""Request message for the ``AddProductToProductSet`` method. + + Attributes: + name (str): + Required. The resource name for the ProductSet to modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + product (str): + Required. The resource name for the Product to be added to + this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + product = proto.Field(proto.STRING, number=2) + + +class RemoveProductFromProductSetRequest(proto.Message): + r"""Request message for the ``RemoveProductFromProductSet`` method. + + Attributes: + name (str): + Required. The resource name for the ProductSet to modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + product (str): + Required. The resource name for the Product to be removed + from this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + product = proto.Field(proto.STRING, number=2) + + +class ListProductsInProductSetRequest(proto.Message): + r"""Request message for the ``ListProductsInProductSet`` method. + + Attributes: + name (str): + Required. The ProductSet resource for which to retrieve + Products. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + page_size (int): + The maximum number of items to return. + Default 10, maximum 100. + page_token (str): + The next_page_token returned from a previous List request, + if any. + """ + + name = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListProductsInProductSetResponse(proto.Message): + r"""Response message for the ``ListProductsInProductSet`` method. + + Attributes: + products (Sequence[~.product_search_service.Product]): + The list of Products. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + products = proto.RepeatedField(proto.MESSAGE, number=1, message=Product,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class ImportProductSetsGcsSource(proto.Message): + r"""The Google Cloud Storage location for a csv file which + preserves a list of ImportProductSetRequests in each line. + + Attributes: + csv_file_uri (str): + The Google Cloud Storage URI of the input csv file. + + The URI must start with ``gs://``. + + The format of the input csv file should be one image per + line. In each line, there are 8 columns. + + 1. image-uri + 2. image-id + 3. product-set-id + 4. product-id + 5. product-category + 6. product-display-name + 7. labels + 8. bounding-poly + + The ``image-uri``, ``product-set-id``, ``product-id``, and + ``product-category`` columns are required. All other columns + are optional. + + If the ``ProductSet`` or ``Product`` specified by the + ``product-set-id`` and ``product-id`` values does not exist, + then the system will create a new ``ProductSet`` or + ``Product`` for the image. In this case, the + ``product-display-name`` column refers to + [display_name][google.cloud.vision.v1.Product.display_name], + the ``product-category`` column refers to + [product_category][google.cloud.vision.v1.Product.product_category], + and the ``labels`` column refers to + [product_labels][google.cloud.vision.v1.Product.product_labels]. + + The ``image-id`` column is optional but must be unique if + provided. If it is empty, the system will automatically + assign a unique id to the image. + + The ``product-display-name`` column is optional. If it is + empty, the system sets the + [display_name][google.cloud.vision.v1.Product.display_name] + field for the product to a space (" "). You can update the + ``display_name`` later by using the API. + + If a ``Product`` with the specified ``product-id`` already + exists, then the system ignores the + ``product-display-name``, ``product-category``, and + ``labels`` columns. + + The ``labels`` column (optional) is a line containing a list + of comma-separated key-value pairs, in the following format: + + :: + + "key_1=value_1,key_2=value_2,...,key_n=value_n" + + The ``bounding-poly`` column (optional) identifies one + region of interest from the image in the same manner as + ``CreateReferenceImage``. If you do not specify the + ``bounding-poly`` column, then the system will try to detect + regions of interest automatically. + + At most one ``bounding-poly`` column is allowed per line. If + the image contains multiple regions of interest, add a line + to the CSV file that includes the same product information, + and the ``bounding-poly`` values for each region of + interest. + + The ``bounding-poly`` column must contain an even number of + comma-separated numbers, in the format + "p1_x,p1_y,p2_x,p2_y,...,pn_x,pn_y". Use non-negative + integers for absolute bounding polygons, and float values in + [0, 1] for normalized bounding polygons. + + The system will resize the image if the image resolution is + too large to process (larger than 20MP). + """ + + csv_file_uri = proto.Field(proto.STRING, number=1) + + +class ImportProductSetsInputConfig(proto.Message): + r"""The input content for the ``ImportProductSets`` method. + + Attributes: + gcs_source (~.product_search_service.ImportProductSetsGcsSource): + The Google Cloud Storage location for a csv + file which preserves a list of + ImportProductSetRequests in each line. + """ + + gcs_source = proto.Field( + proto.MESSAGE, number=1, oneof="source", message=ImportProductSetsGcsSource, + ) + + +class ImportProductSetsRequest(proto.Message): + r"""Request message for the ``ImportProductSets`` method. + + Attributes: + parent (str): + Required. The project in which the ProductSets should be + imported. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + input_config (~.product_search_service.ImportProductSetsInputConfig): + Required. The input content for the list of + requests. + """ + + parent = proto.Field(proto.STRING, number=1) + + input_config = proto.Field( + proto.MESSAGE, number=2, message=ImportProductSetsInputConfig, + ) + + +class ImportProductSetsResponse(proto.Message): + r"""Response message for the ``ImportProductSets`` method. + + This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + Attributes: + reference_images (Sequence[~.product_search_service.ReferenceImage]): + The list of reference_images that are imported successfully. + statuses (Sequence[~.status.Status]): + The rpc status for each ImportProductSet request, including + both successes and errors. + + The number of statuses here matches the number of lines in + the csv file, and statuses[i] stores the success or failure + status of processing the i-th line of the csv, starting from + line 0. + """ + + reference_images = proto.RepeatedField( + proto.MESSAGE, number=1, message=ReferenceImage, + ) + + statuses = proto.RepeatedField(proto.MESSAGE, number=2, message=status.Status,) + + +class BatchOperationMetadata(proto.Message): + r"""Metadata for the batch operations such as the current state. + + This is included in the ``metadata`` field of the ``Operation`` + returned by the ``GetOperation`` call of the + ``google::longrunning::Operations`` service. + + Attributes: + state (~.product_search_service.BatchOperationMetadata.State): + The current state of the batch operation. + submit_time (~.timestamp.Timestamp): + The time when the batch request was submitted + to the server. + end_time (~.timestamp.Timestamp): + The time when the batch request is finished and + [google.longrunning.Operation.done][google.longrunning.Operation.done] + is set to true. + """ + + class State(proto.Enum): + r"""Enumerates the possible states that the batch request can be + in. + """ + STATE_UNSPECIFIED = 0 + PROCESSING = 1 + SUCCESSFUL = 2 + FAILED = 3 + CANCELLED = 4 + + state = proto.Field(proto.ENUM, number=1, enum=State,) + + submit_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +class ProductSetPurgeConfig(proto.Message): + r"""Config to control which ProductSet contains the Products to + be deleted. + + Attributes: + product_set_id (str): + The ProductSet that contains the Products to delete. If a + Product is a member of product_set_id in addition to other + ProductSets, the Product will still be deleted. + """ + + product_set_id = proto.Field(proto.STRING, number=1) + + +class PurgeProductsRequest(proto.Message): + r"""Request message for the ``PurgeProducts`` method. + + Attributes: + product_set_purge_config (~.product_search_service.ProductSetPurgeConfig): + Specify which ProductSet contains the + Products to be deleted. + delete_orphan_products (bool): + If delete_orphan_products is true, all Products that are not + in any ProductSet will be deleted. + parent (str): + Required. The project and location in which the Products + should be deleted. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + force (bool): + The default value is false. Override this + value to true to actually perform the purge. + """ + + product_set_purge_config = proto.Field( + proto.MESSAGE, number=2, oneof="target", message=ProductSetPurgeConfig, + ) + + delete_orphan_products = proto.Field(proto.BOOL, number=3, oneof="target") + + parent = proto.Field(proto.STRING, number=1) + + force = proto.Field(proto.BOOL, number=4) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1/types/text_annotation.py b/google/cloud/vision_v1/types/text_annotation.py new file mode 100644 index 00000000..7d647765 --- /dev/null +++ b/google/cloud/vision_v1/types/text_annotation.py @@ -0,0 +1,320 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.vision_v1.types import geometry + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1", + manifest={"TextAnnotation", "Page", "Block", "Paragraph", "Word", "Symbol",}, +) + + +class TextAnnotation(proto.Message): + r"""TextAnnotation contains a structured representation of OCR extracted + text. The hierarchy of an OCR extracted text structure is like this: + TextAnnotation -> Page -> Block -> Paragraph -> Word -> Symbol Each + structural component, starting from Page, may further have their own + properties. Properties describe detected languages, breaks etc.. + Please refer to the + [TextAnnotation.TextProperty][google.cloud.vision.v1.TextAnnotation.TextProperty] + message definition below for more detail. + + Attributes: + pages (Sequence[~.text_annotation.Page]): + List of pages detected by OCR. + text (str): + UTF-8 text detected on the pages. + """ + + class DetectedLanguage(proto.Message): + r"""Detected language for a structural component. + + Attributes: + language_code (str): + The BCP-47 language code, such as "en-US" or "sr-Latn". For + more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + confidence (float): + Confidence of detected language. Range [0, 1]. + """ + + language_code = proto.Field(proto.STRING, number=1) + + confidence = proto.Field(proto.FLOAT, number=2) + + class DetectedBreak(proto.Message): + r"""Detected start or end of a structural component. + + Attributes: + type_ (~.text_annotation.TextAnnotation.DetectedBreak.BreakType): + Detected break type. + is_prefix (bool): + True if break prepends the element. + """ + + class BreakType(proto.Enum): + r"""Enum to denote the type of break found. New line, space etc.""" + UNKNOWN = 0 + SPACE = 1 + SURE_SPACE = 2 + EOL_SURE_SPACE = 3 + HYPHEN = 4 + LINE_BREAK = 5 + + type_ = proto.Field( + proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", + ) + + is_prefix = proto.Field(proto.BOOL, number=2) + + class TextProperty(proto.Message): + r"""Additional information detected on the structural component. + + Attributes: + detected_languages (Sequence[~.text_annotation.TextAnnotation.DetectedLanguage]): + A list of detected languages together with + confidence. + detected_break (~.text_annotation.TextAnnotation.DetectedBreak): + Detected start or end of a text segment. + """ + + detected_languages = proto.RepeatedField( + proto.MESSAGE, number=1, message="TextAnnotation.DetectedLanguage", + ) + + detected_break = proto.Field( + proto.MESSAGE, number=2, message="TextAnnotation.DetectedBreak", + ) + + pages = proto.RepeatedField(proto.MESSAGE, number=1, message="Page",) + + text = proto.Field(proto.STRING, number=2) + + +class Page(proto.Message): + r"""Detected page from OCR. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected on the page. + width (int): + Page width. For PDFs the unit is points. For + images (including TIFFs) the unit is pixels. + height (int): + Page height. For PDFs the unit is points. For + images (including TIFFs) the unit is pixels. + blocks (Sequence[~.text_annotation.Block]): + List of blocks of text, images etc on this + page. + confidence (float): + Confidence of the OCR results on the page. Range [0, 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + width = proto.Field(proto.INT32, number=2) + + height = proto.Field(proto.INT32, number=3) + + blocks = proto.RepeatedField(proto.MESSAGE, number=4, message="Block",) + + confidence = proto.Field(proto.FLOAT, number=5) + + +class Block(proto.Message): + r"""Logical element on the page. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the + block. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the block. The vertices are in the + order of top-left, top-right, bottom-right, bottom-left. + When a rotation of the bounding box is detected the rotation + is represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: + + :: + + 0----1 + | | + 3----2 + + - when it's rotated 180 degrees around the top-left corner + it becomes: + + :: + + 2----3 + | | + 1----0 + + and the vertex order will still be (0, 1, 2, 3). + paragraphs (Sequence[~.text_annotation.Paragraph]): + List of paragraphs in this block (if this + blocks is of type text). + block_type (~.text_annotation.Block.BlockType): + Detected block type (text, image etc) for + this block. + confidence (float): + Confidence of the OCR results on the block. Range [0, 1]. + """ + + class BlockType(proto.Enum): + r"""Type of a block (text, image etc) as identified by OCR.""" + UNKNOWN = 0 + TEXT = 1 + TABLE = 2 + PICTURE = 3 + RULER = 4 + BARCODE = 5 + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + paragraphs = proto.RepeatedField(proto.MESSAGE, number=3, message="Paragraph",) + + block_type = proto.Field(proto.ENUM, number=4, enum=BlockType,) + + confidence = proto.Field(proto.FLOAT, number=5) + + +class Paragraph(proto.Message): + r"""Structural unit of text representing a number of words in + certain order. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the + paragraph. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the paragraph. The vertices are in the + order of top-left, top-right, bottom-right, bottom-left. + When a rotation of the bounding box is detected the rotation + is represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertex order will + still be (0, 1, 2, 3). + words (Sequence[~.text_annotation.Word]): + List of all words in this paragraph. + confidence (float): + Confidence of the OCR results for the paragraph. Range [0, + 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + words = proto.RepeatedField(proto.MESSAGE, number=3, message="Word",) + + confidence = proto.Field(proto.FLOAT, number=4) + + +class Word(proto.Message): + r"""A word representation. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the word. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the word. The vertices are in the order + of top-left, top-right, bottom-right, bottom-left. When a + rotation of the bounding box is detected the rotation is + represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertex order will + still be (0, 1, 2, 3). + symbols (Sequence[~.text_annotation.Symbol]): + List of symbols in the word. + The order of the symbols follows the natural + reading order. + confidence (float): + Confidence of the OCR results for the word. Range [0, 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + symbols = proto.RepeatedField(proto.MESSAGE, number=3, message="Symbol",) + + confidence = proto.Field(proto.FLOAT, number=4) + + +class Symbol(proto.Message): + r"""A single symbol representation. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the + symbol. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the symbol. The vertices are in the + order of top-left, top-right, bottom-right, bottom-left. + When a rotation of the bounding box is detected the rotation + is represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertex order will + still be (0, 1, 2, 3). + text (str): + The actual UTF-8 representation of the + symbol. + confidence (float): + Confidence of the OCR results for the symbol. Range [0, 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + text = proto.Field(proto.STRING, number=3) + + confidence = proto.Field(proto.FLOAT, number=4) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1/types/web_detection.py b/google/cloud/vision_v1/types/web_detection.py new file mode 100644 index 00000000..9395af29 --- /dev/null +++ b/google/cloud/vision_v1/types/web_detection.py @@ -0,0 +1,163 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1", manifest={"WebDetection",}, +) + + +class WebDetection(proto.Message): + r"""Relevant information for the image from the Internet. + + Attributes: + web_entities (Sequence[~.web_detection.WebDetection.WebEntity]): + Deduced entities from similar images on the + Internet. + full_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Fully matching images from the Internet. + Can include resized copies of the query image. + partial_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Partial matching images from the Internet. + Those images are similar enough to share some + key-point features. For example an original + image will likely have partial matching for its + crops. + pages_with_matching_images (Sequence[~.web_detection.WebDetection.WebPage]): + Web pages containing the matching images from + the Internet. + visually_similar_images (Sequence[~.web_detection.WebDetection.WebImage]): + The visually similar image results. + best_guess_labels (Sequence[~.web_detection.WebDetection.WebLabel]): + The service's best guess as to the topic of + the request image. Inferred from similar images + on the open web. + """ + + class WebEntity(proto.Message): + r"""Entity deduced from similar images on the Internet. + + Attributes: + entity_id (str): + Opaque entity ID. + score (float): + Overall relevancy score for the entity. + Not normalized and not comparable across + different image queries. + description (str): + Canonical description of the entity, in + English. + """ + + entity_id = proto.Field(proto.STRING, number=1) + + score = proto.Field(proto.FLOAT, number=2) + + description = proto.Field(proto.STRING, number=3) + + class WebImage(proto.Message): + r"""Metadata for online images. + + Attributes: + url (str): + The result image URL. + score (float): + (Deprecated) Overall relevancy score for the + image. + """ + + url = proto.Field(proto.STRING, number=1) + + score = proto.Field(proto.FLOAT, number=2) + + class WebPage(proto.Message): + r"""Metadata for web pages. + + Attributes: + url (str): + The result web page URL. + score (float): + (Deprecated) Overall relevancy score for the + web page. + page_title (str): + Title for the web page, may contain HTML + markups. + full_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Fully matching images on the page. + Can include resized copies of the query image. + partial_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Partial matching images on the page. + Those images are similar enough to share some + key-point features. For example an original + image will likely have partial matching for its + crops. + """ + + url = proto.Field(proto.STRING, number=1) + + score = proto.Field(proto.FLOAT, number=2) + + page_title = proto.Field(proto.STRING, number=3) + + full_matching_images = proto.RepeatedField( + proto.MESSAGE, number=4, message="WebDetection.WebImage", + ) + + partial_matching_images = proto.RepeatedField( + proto.MESSAGE, number=5, message="WebDetection.WebImage", + ) + + class WebLabel(proto.Message): + r"""Label to provide extra metadata for the web detection. + + Attributes: + label (str): + Label for extra metadata. + language_code (str): + The BCP-47 language code for ``label``, such as "en-US" or + "sr-Latn". For more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + """ + + label = proto.Field(proto.STRING, number=1) + + language_code = proto.Field(proto.STRING, number=2) + + web_entities = proto.RepeatedField(proto.MESSAGE, number=1, message=WebEntity,) + + full_matching_images = proto.RepeatedField( + proto.MESSAGE, number=2, message=WebImage, + ) + + partial_matching_images = proto.RepeatedField( + proto.MESSAGE, number=3, message=WebImage, + ) + + pages_with_matching_images = proto.RepeatedField( + proto.MESSAGE, number=4, message=WebPage, + ) + + visually_similar_images = proto.RepeatedField( + proto.MESSAGE, number=6, message=WebImage, + ) + + best_guess_labels = proto.RepeatedField(proto.MESSAGE, number=8, message=WebLabel,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p1beta1/__init__.py b/google/cloud/vision_v1p1beta1/__init__.py index 1c17eb73..cd412fc8 100644 --- a/google/cloud/vision_v1p1beta1/__init__.py +++ b/google/cloud/vision_v1p1beta1/__init__.py @@ -1,49 +1,96 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - - -from __future__ import absolute_import +# from google.cloud.vision_helpers.decorators import add_single_feature_methods from google.cloud.vision_helpers import VisionHelpers -import sys -import warnings - -from google.cloud.vision_v1p1beta1 import types -from google.cloud.vision_v1p1beta1.gapic import enums -from google.cloud.vision_v1p1beta1.gapic import image_annotator_client as iac - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) +from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient +from .types.geometry import BoundingPoly +from .types.geometry import Position +from .types.geometry import Vertex +from .types.image_annotator import AnnotateImageRequest +from .types.image_annotator import AnnotateImageResponse +from .types.image_annotator import BatchAnnotateImagesRequest +from .types.image_annotator import BatchAnnotateImagesResponse +from .types.image_annotator import ColorInfo +from .types.image_annotator import CropHint +from .types.image_annotator import CropHintsAnnotation +from .types.image_annotator import CropHintsParams +from .types.image_annotator import DominantColorsAnnotation +from .types.image_annotator import EntityAnnotation +from .types.image_annotator import FaceAnnotation +from .types.image_annotator import Feature +from .types.image_annotator import Image +from .types.image_annotator import ImageContext +from .types.image_annotator import ImageProperties +from .types.image_annotator import ImageSource +from .types.image_annotator import LatLongRect +from .types.image_annotator import Likelihood +from .types.image_annotator import LocationInfo +from .types.image_annotator import Property +from .types.image_annotator import SafeSearchAnnotation +from .types.image_annotator import WebDetectionParams +from .types.text_annotation import Block +from .types.text_annotation import Page +from .types.text_annotation import Paragraph +from .types.text_annotation import Symbol +from .types.text_annotation import TextAnnotation +from .types.text_annotation import Word +from .types.web_detection import WebDetection @add_single_feature_methods -class ImageAnnotatorClient(VisionHelpers, iac.ImageAnnotatorClient): - __doc__ = iac.ImageAnnotatorClient.__doc__ - enums = enums +class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): + __doc__ = IacImageAnnotatorClient.__doc__ + Feature = Feature __all__ = ( - "enums", - "types", + "AnnotateImageRequest", + "AnnotateImageResponse", + "BatchAnnotateImagesRequest", + "BatchAnnotateImagesResponse", + "Block", + "BoundingPoly", + "ColorInfo", + "CropHint", + "CropHintsAnnotation", + "CropHintsParams", + "DominantColorsAnnotation", + "EntityAnnotation", + "FaceAnnotation", + "Feature", + "Image", + "ImageContext", + "ImageProperties", + "ImageSource", + "LatLongRect", + "Likelihood", + "LocationInfo", + "Page", + "Paragraph", + "Position", + "Property", + "SafeSearchAnnotation", + "Symbol", + "TextAnnotation", + "Vertex", + "WebDetection", + "WebDetectionParams", + "Word", "ImageAnnotatorClient", ) diff --git a/google/cloud/vision_v1p1beta1/gapic/__init__.py b/google/cloud/vision_v1p1beta1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/vision_v1p1beta1/gapic/enums.py b/google/cloud/vision_v1p1beta1/gapic/enums.py deleted file mode 100644 index 61a1cf96..00000000 --- a/google/cloud/vision_v1p1beta1/gapic/enums.py +++ /dev/null @@ -1,204 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class Likelihood(enum.IntEnum): - """ - A bucketized representation of likelihood, which is intended to give clients - highly stable results across model upgrades. - - Attributes: - UNKNOWN (int): Unknown likelihood. - VERY_UNLIKELY (int): It is very unlikely that the image belongs to the specified vertical. - UNLIKELY (int): It is unlikely that the image belongs to the specified vertical. - POSSIBLE (int): It is possible that the image belongs to the specified vertical. - LIKELY (int): It is likely that the image belongs to the specified vertical. - VERY_LIKELY (int): It is very likely that the image belongs to the specified vertical. - """ - - UNKNOWN = 0 - VERY_UNLIKELY = 1 - UNLIKELY = 2 - POSSIBLE = 3 - LIKELY = 4 - VERY_LIKELY = 5 - - -class Block(object): - class BlockType(enum.IntEnum): - """ - Type of a block (text, image etc) as identified by OCR. - - Attributes: - UNKNOWN (int): Unknown block type. - TEXT (int): Regular text block. - TABLE (int): Table block. - PICTURE (int): Image block. - RULER (int): Horizontal/vertical line box. - BARCODE (int): Barcode block. - """ - - UNKNOWN = 0 - TEXT = 1 - TABLE = 2 - PICTURE = 3 - RULER = 4 - BARCODE = 5 - - -class FaceAnnotation(object): - class Landmark(object): - class Type(enum.IntEnum): - """ - Face landmark (feature) type. Left and right are defined from the - vantage of the viewer of the image without considering mirror - projections typical of photos. So, ``LEFT_EYE``, typically, is the - person's right eye. - - Attributes: - UNKNOWN_LANDMARK (int): Unknown face landmark detected. Should not be filled. - LEFT_EYE (int): Left eye. - RIGHT_EYE (int): Right eye. - LEFT_OF_LEFT_EYEBROW (int): Left of left eyebrow. - RIGHT_OF_LEFT_EYEBROW (int): Right of left eyebrow. - LEFT_OF_RIGHT_EYEBROW (int): Left of right eyebrow. - RIGHT_OF_RIGHT_EYEBROW (int): Right of right eyebrow. - MIDPOINT_BETWEEN_EYES (int): Midpoint between eyes. - NOSE_TIP (int): Nose tip. - UPPER_LIP (int): Upper lip. - LOWER_LIP (int): Lower lip. - MOUTH_LEFT (int): Mouth left. - MOUTH_RIGHT (int): Mouth right. - MOUTH_CENTER (int): Mouth center. - NOSE_BOTTOM_RIGHT (int): Nose, bottom right. - NOSE_BOTTOM_LEFT (int): Nose, bottom left. - NOSE_BOTTOM_CENTER (int): Nose, bottom center. - LEFT_EYE_TOP_BOUNDARY (int): Left eye, top boundary. - LEFT_EYE_RIGHT_CORNER (int): Left eye, right corner. - LEFT_EYE_BOTTOM_BOUNDARY (int): Left eye, bottom boundary. - LEFT_EYE_LEFT_CORNER (int): Left eye, left corner. - RIGHT_EYE_TOP_BOUNDARY (int): Right eye, top boundary. - RIGHT_EYE_RIGHT_CORNER (int): Right eye, right corner. - RIGHT_EYE_BOTTOM_BOUNDARY (int): Right eye, bottom boundary. - RIGHT_EYE_LEFT_CORNER (int): Right eye, left corner. - LEFT_EYEBROW_UPPER_MIDPOINT (int): Left eyebrow, upper midpoint. - RIGHT_EYEBROW_UPPER_MIDPOINT (int): Right eyebrow, upper midpoint. - LEFT_EAR_TRAGION (int): Left ear tragion. - RIGHT_EAR_TRAGION (int): Right ear tragion. - LEFT_EYE_PUPIL (int): Left eye pupil. - RIGHT_EYE_PUPIL (int): Right eye pupil. - FOREHEAD_GLABELLA (int): Forehead glabella. - CHIN_GNATHION (int): Chin gnathion. - CHIN_LEFT_GONION (int): Chin left gonion. - CHIN_RIGHT_GONION (int): Chin right gonion. - """ - - UNKNOWN_LANDMARK = 0 - LEFT_EYE = 1 - RIGHT_EYE = 2 - LEFT_OF_LEFT_EYEBROW = 3 - RIGHT_OF_LEFT_EYEBROW = 4 - LEFT_OF_RIGHT_EYEBROW = 5 - RIGHT_OF_RIGHT_EYEBROW = 6 - MIDPOINT_BETWEEN_EYES = 7 - NOSE_TIP = 8 - UPPER_LIP = 9 - LOWER_LIP = 10 - MOUTH_LEFT = 11 - MOUTH_RIGHT = 12 - MOUTH_CENTER = 13 - NOSE_BOTTOM_RIGHT = 14 - NOSE_BOTTOM_LEFT = 15 - NOSE_BOTTOM_CENTER = 16 - LEFT_EYE_TOP_BOUNDARY = 17 - LEFT_EYE_RIGHT_CORNER = 18 - LEFT_EYE_BOTTOM_BOUNDARY = 19 - LEFT_EYE_LEFT_CORNER = 20 - RIGHT_EYE_TOP_BOUNDARY = 21 - RIGHT_EYE_RIGHT_CORNER = 22 - RIGHT_EYE_BOTTOM_BOUNDARY = 23 - RIGHT_EYE_LEFT_CORNER = 24 - LEFT_EYEBROW_UPPER_MIDPOINT = 25 - RIGHT_EYEBROW_UPPER_MIDPOINT = 26 - LEFT_EAR_TRAGION = 27 - RIGHT_EAR_TRAGION = 28 - LEFT_EYE_PUPIL = 29 - RIGHT_EYE_PUPIL = 30 - FOREHEAD_GLABELLA = 31 - CHIN_GNATHION = 32 - CHIN_LEFT_GONION = 33 - CHIN_RIGHT_GONION = 34 - - -class Feature(object): - class Type(enum.IntEnum): - """ - Type of image feature. - - Attributes: - TYPE_UNSPECIFIED (int): Unspecified feature type. - FACE_DETECTION (int): Run face detection. - LANDMARK_DETECTION (int): Run landmark detection. - LOGO_DETECTION (int): Run logo detection. - LABEL_DETECTION (int): Run label detection. - TEXT_DETECTION (int): Run OCR. - DOCUMENT_TEXT_DETECTION (int): Run dense text document OCR. Takes precedence when both - DOCUMENT_TEXT_DETECTION and TEXT_DETECTION are present. - SAFE_SEARCH_DETECTION (int): Run computer vision models to compute image safe-search properties. - IMAGE_PROPERTIES (int): Compute a set of image properties, such as the image's dominant colors. - CROP_HINTS (int): Run crop hints. - WEB_DETECTION (int): Run web detection. - """ - - TYPE_UNSPECIFIED = 0 - FACE_DETECTION = 1 - LANDMARK_DETECTION = 2 - LOGO_DETECTION = 3 - LABEL_DETECTION = 4 - TEXT_DETECTION = 5 - DOCUMENT_TEXT_DETECTION = 11 - SAFE_SEARCH_DETECTION = 6 - IMAGE_PROPERTIES = 7 - CROP_HINTS = 9 - WEB_DETECTION = 10 - - -class TextAnnotation(object): - class DetectedBreak(object): - class BreakType(enum.IntEnum): - """ - Enum to denote the type of break found. New line, space etc. - - Attributes: - UNKNOWN (int): Unknown break label type. - SPACE (int): Regular space. - SURE_SPACE (int): Sure space (very wide). - EOL_SURE_SPACE (int): Line-wrapping break. - HYPHEN (int): End-line hyphen that is not present in text; does not co-occur with - ``SPACE``, ``LEADER_SPACE``, or ``LINE_BREAK``. - LINE_BREAK (int): Line break that ends a paragraph. - """ - - UNKNOWN = 0 - SPACE = 1 - SURE_SPACE = 2 - EOL_SURE_SPACE = 3 - HYPHEN = 4 - LINE_BREAK = 5 diff --git a/google/cloud/vision_v1p1beta1/gapic/image_annotator_client.py b/google/cloud/vision_v1p1beta1/gapic/image_annotator_client.py deleted file mode 100644 index 808ca2dc..00000000 --- a/google/cloud/vision_v1p1beta1/gapic/image_annotator_client.py +++ /dev/null @@ -1,247 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.vision.v1p1beta1 ImageAnnotator API.""" - -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.grpc_helpers -import grpc - -from google.cloud.vision_v1p1beta1.gapic import enums -from google.cloud.vision_v1p1beta1.gapic import image_annotator_client_config -from google.cloud.vision_v1p1beta1.gapic.transports import ( - image_annotator_grpc_transport, -) -from google.cloud.vision_v1p1beta1.proto import image_annotator_pb2 -from google.cloud.vision_v1p1beta1.proto import image_annotator_pb2_grpc - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-vision",).version - - -class ImageAnnotatorClient(object): - """ - Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - SERVICE_ADDRESS = "vision.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.vision.v1p1beta1.ImageAnnotator" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ImageAnnotatorClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.ImageAnnotatorGrpcTransport, - Callable[[~.Credentials, type], ~.ImageAnnotatorGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = image_annotator_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=image_annotator_grpc_transport.ImageAnnotatorGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = image_annotator_grpc_transport.ImageAnnotatorGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def batch_annotate_images( - self, - requests, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Run image detection and annotation for a batch of images. - - Example: - >>> from google.cloud import vision_v1p1beta1 - >>> - >>> client = vision_v1p1beta1.ImageAnnotatorClient() - >>> - >>> # TODO: Initialize `requests`: - >>> requests = [] - >>> - >>> response = client.batch_annotate_images(requests) - - Args: - requests (list[Union[dict, ~google.cloud.vision_v1p1beta1.types.AnnotateImageRequest]]): Required. Individual image annotation requests for this batch. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p1beta1.types.AnnotateImageRequest` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p1beta1.types.BatchAnnotateImagesResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "batch_annotate_images" not in self._inner_api_calls: - self._inner_api_calls[ - "batch_annotate_images" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.batch_annotate_images, - default_retry=self._method_configs["BatchAnnotateImages"].retry, - default_timeout=self._method_configs["BatchAnnotateImages"].timeout, - client_info=self._client_info, - ) - - request = image_annotator_pb2.BatchAnnotateImagesRequest(requests=requests,) - return self._inner_api_calls["batch_annotate_images"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/vision_v1p1beta1/gapic/image_annotator_client_config.py b/google/cloud/vision_v1p1beta1/gapic/image_annotator_client_config.py deleted file mode 100644 index bd83e3ab..00000000 --- a/google/cloud/vision_v1p1beta1/gapic/image_annotator_client_config.py +++ /dev/null @@ -1,37 +0,0 @@ -config = { - "interfaces": { - "google.cloud.vision.v1p1beta1.ImageAnnotator": { - "retry_codes": { - "retry_policy_1_codes": ["UNAVAILABLE", "DEADLINE_EXCEEDED"], - "no_retry_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 600000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 600000, - "total_timeout_millis": 600000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - }, - "methods": { - "BatchAnnotateImages": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - } - }, - } - } -} diff --git a/google/cloud/vision_v1p1beta1/gapic/transports/__init__.py b/google/cloud/vision_v1p1beta1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/vision_v1p1beta1/gapic/transports/image_annotator_grpc_transport.py b/google/cloud/vision_v1p1beta1/gapic/transports/image_annotator_grpc_transport.py deleted file mode 100644 index 65f3229f..00000000 --- a/google/cloud/vision_v1p1beta1/gapic/transports/image_annotator_grpc_transport.py +++ /dev/null @@ -1,126 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers - -from google.cloud.vision_v1p1beta1.proto import image_annotator_pb2_grpc - - -class ImageAnnotatorGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.vision.v1p1beta1 ImageAnnotator API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ) - - def __init__( - self, channel=None, credentials=None, address="vision.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "image_annotator_stub": image_annotator_pb2_grpc.ImageAnnotatorStub( - channel - ), - } - - @classmethod - def create_channel( - cls, address="vision.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def batch_annotate_images(self): - """Return the gRPC stub for :meth:`ImageAnnotatorClient.batch_annotate_images`. - - Run image detection and annotation for a batch of images. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["image_annotator_stub"].BatchAnnotateImages diff --git a/google/cloud/vision_v1p1beta1/proto/__init__.py b/google/cloud/vision_v1p1beta1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/vision_v1p1beta1/proto/geometry_pb2.py b/google/cloud/vision_v1p1beta1/proto/geometry_pb2.py deleted file mode 100644 index aead3c27..00000000 --- a/google/cloud/vision_v1p1beta1/proto/geometry_pb2.py +++ /dev/null @@ -1,269 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p1beta1/proto/geometry.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p1beta1/proto/geometry.proto", - package="google.cloud.vision.v1p1beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p1beta1B\rGeometryProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p1beta1;vision\370\001\001", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n2google/cloud/vision_v1p1beta1/proto/geometry.proto\x12\x1dgoogle.cloud.vision.v1p1beta1"\x1e\n\x06Vertex\x12\t\n\x01x\x18\x01 \x01(\x05\x12\t\n\x01y\x18\x02 \x01(\x05"G\n\x0c\x42oundingPoly\x12\x37\n\x08vertices\x18\x01 \x03(\x0b\x32%.google.cloud.vision.v1p1beta1.Vertex"+\n\x08Position\x12\t\n\x01x\x18\x01 \x01(\x02\x12\t\n\x01y\x18\x02 \x01(\x02\x12\t\n\x01z\x18\x03 \x01(\x02\x42|\n!com.google.cloud.vision.v1p1beta1B\rGeometryProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p1beta1;vision\xf8\x01\x01\x62\x06proto3', -) - - -_VERTEX = _descriptor.Descriptor( - name="Vertex", - full_name="google.cloud.vision.v1p1beta1.Vertex", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="x", - full_name="google.cloud.vision.v1p1beta1.Vertex.x", - index=0, - number=1, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="y", - full_name="google.cloud.vision.v1p1beta1.Vertex.y", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=85, - serialized_end=115, -) - - -_BOUNDINGPOLY = _descriptor.Descriptor( - name="BoundingPoly", - full_name="google.cloud.vision.v1p1beta1.BoundingPoly", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="vertices", - full_name="google.cloud.vision.v1p1beta1.BoundingPoly.vertices", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=117, - serialized_end=188, -) - - -_POSITION = _descriptor.Descriptor( - name="Position", - full_name="google.cloud.vision.v1p1beta1.Position", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="x", - full_name="google.cloud.vision.v1p1beta1.Position.x", - index=0, - number=1, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="y", - full_name="google.cloud.vision.v1p1beta1.Position.y", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="z", - full_name="google.cloud.vision.v1p1beta1.Position.z", - index=2, - number=3, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=190, - serialized_end=233, -) - -_BOUNDINGPOLY.fields_by_name["vertices"].message_type = _VERTEX -DESCRIPTOR.message_types_by_name["Vertex"] = _VERTEX -DESCRIPTOR.message_types_by_name["BoundingPoly"] = _BOUNDINGPOLY -DESCRIPTOR.message_types_by_name["Position"] = _POSITION -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Vertex = _reflection.GeneratedProtocolMessageType( - "Vertex", - (_message.Message,), - { - "DESCRIPTOR": _VERTEX, - "__module__": "google.cloud.vision_v1p1beta1.proto.geometry_pb2", - "__doc__": """X coordinate. - - Attributes: - y: - Y coordinate. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.Vertex) - }, -) -_sym_db.RegisterMessage(Vertex) - -BoundingPoly = _reflection.GeneratedProtocolMessageType( - "BoundingPoly", - (_message.Message,), - { - "DESCRIPTOR": _BOUNDINGPOLY, - "__module__": "google.cloud.vision_v1p1beta1.proto.geometry_pb2", - "__doc__": """A bounding polygon for the detected image annotation. - - Attributes: - vertices: - The bounding polygon vertices. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.BoundingPoly) - }, -) -_sym_db.RegisterMessage(BoundingPoly) - -Position = _reflection.GeneratedProtocolMessageType( - "Position", - (_message.Message,), - { - "DESCRIPTOR": _POSITION, - "__module__": "google.cloud.vision_v1p1beta1.proto.geometry_pb2", - "__doc__": """A 3D position in the image, used primarily for Face detection - landmarks. A valid Position must have both x and y coordinates. The - position coordinates are in the same scale as the original image. - - Attributes: - x: - X coordinate. - y: - Y coordinate. - z: - Z coordinate (or depth). - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.Position) - }, -) -_sym_db.RegisterMessage(Position) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p1beta1/proto/geometry_pb2_grpc.py b/google/cloud/vision_v1p1beta1/proto/geometry_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/vision_v1p1beta1/proto/geometry_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/vision_v1p1beta1/proto/image_annotator_pb2.py b/google/cloud/vision_v1p1beta1/proto/image_annotator_pb2.py deleted file mode 100644 index e9c60c54..00000000 --- a/google/cloud/vision_v1p1beta1/proto/image_annotator_pb2.py +++ /dev/null @@ -1,3178 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p1beta1/proto/image_annotator.proto -"""Generated protocol buffer code.""" -from google.protobuf.internal import enum_type_wrapper -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.cloud.vision_v1p1beta1.proto import ( - geometry_pb2 as google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2, -) -from google.cloud.vision_v1p1beta1.proto import ( - text_annotation_pb2 as google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_text__annotation__pb2, -) -from google.cloud.vision_v1p1beta1.proto import ( - web_detection_pb2 as google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_web__detection__pb2, -) -from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2 -from google.type import color_pb2 as google_dot_type_dot_color__pb2 -from google.type import latlng_pb2 as google_dot_type_dot_latlng__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p1beta1/proto/image_annotator.proto", - package="google.cloud.vision.v1p1beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p1beta1B\023ImageAnnotatorProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p1beta1;vision\370\001\001", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n9google/cloud/vision_v1p1beta1/proto/image_annotator.proto\x12\x1dgoogle.cloud.vision.v1p1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x32google/cloud/vision_v1p1beta1/proto/geometry.proto\x1a\x39google/cloud/vision_v1p1beta1/proto/text_annotation.proto\x1a\x37google/cloud/vision_v1p1beta1/proto/web_detection.proto\x1a\x17google/rpc/status.proto\x1a\x17google/type/color.proto\x1a\x18google/type/latlng.proto"\xe1\x02\n\x07\x46\x65\x61ture\x12\x39\n\x04type\x18\x01 \x01(\x0e\x32+.google.cloud.vision.v1p1beta1.Feature.Type\x12\x13\n\x0bmax_results\x18\x02 \x01(\x05\x12\r\n\x05model\x18\x03 \x01(\t"\xf6\x01\n\x04Type\x12\x14\n\x10TYPE_UNSPECIFIED\x10\x00\x12\x12\n\x0e\x46\x41\x43\x45_DETECTION\x10\x01\x12\x16\n\x12LANDMARK_DETECTION\x10\x02\x12\x12\n\x0eLOGO_DETECTION\x10\x03\x12\x13\n\x0fLABEL_DETECTION\x10\x04\x12\x12\n\x0eTEXT_DETECTION\x10\x05\x12\x1b\n\x17\x44OCUMENT_TEXT_DETECTION\x10\x0b\x12\x19\n\x15SAFE_SEARCH_DETECTION\x10\x06\x12\x14\n\x10IMAGE_PROPERTIES\x10\x07\x12\x0e\n\nCROP_HINTS\x10\t\x12\x11\n\rWEB_DETECTION\x10\n"7\n\x0bImageSource\x12\x15\n\rgcs_image_uri\x18\x01 \x01(\t\x12\x11\n\timage_uri\x18\x02 \x01(\t"T\n\x05Image\x12\x0f\n\x07\x63ontent\x18\x01 \x01(\x0c\x12:\n\x06source\x18\x02 \x01(\x0b\x32*.google.cloud.vision.v1p1beta1.ImageSource"\x9b\x0e\n\x0e\x46\x61\x63\x65\x41nnotation\x12\x42\n\rbounding_poly\x18\x01 \x01(\x0b\x32+.google.cloud.vision.v1p1beta1.BoundingPoly\x12\x45\n\x10\x66\x64_bounding_poly\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p1beta1.BoundingPoly\x12I\n\tlandmarks\x18\x03 \x03(\x0b\x32\x36.google.cloud.vision.v1p1beta1.FaceAnnotation.Landmark\x12\x12\n\nroll_angle\x18\x04 \x01(\x02\x12\x11\n\tpan_angle\x18\x05 \x01(\x02\x12\x12\n\ntilt_angle\x18\x06 \x01(\x02\x12\x1c\n\x14\x64\x65tection_confidence\x18\x07 \x01(\x02\x12\x1e\n\x16landmarking_confidence\x18\x08 \x01(\x02\x12\x41\n\x0ejoy_likelihood\x18\t \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12\x44\n\x11sorrow_likelihood\x18\n \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12\x43\n\x10\x61nger_likelihood\x18\x0b \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12\x46\n\x13surprise_likelihood\x18\x0c \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12K\n\x18under_exposed_likelihood\x18\r \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12\x45\n\x12\x62lurred_likelihood\x18\x0e \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12\x46\n\x13headwear_likelihood\x18\x0f \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x1a\xc7\x07\n\x08Landmark\x12I\n\x04type\x18\x03 \x01(\x0e\x32;.google.cloud.vision.v1p1beta1.FaceAnnotation.Landmark.Type\x12\x39\n\x08position\x18\x04 \x01(\x0b\x32\'.google.cloud.vision.v1p1beta1.Position"\xb4\x06\n\x04Type\x12\x14\n\x10UNKNOWN_LANDMARK\x10\x00\x12\x0c\n\x08LEFT_EYE\x10\x01\x12\r\n\tRIGHT_EYE\x10\x02\x12\x18\n\x14LEFT_OF_LEFT_EYEBROW\x10\x03\x12\x19\n\x15RIGHT_OF_LEFT_EYEBROW\x10\x04\x12\x19\n\x15LEFT_OF_RIGHT_EYEBROW\x10\x05\x12\x1a\n\x16RIGHT_OF_RIGHT_EYEBROW\x10\x06\x12\x19\n\x15MIDPOINT_BETWEEN_EYES\x10\x07\x12\x0c\n\x08NOSE_TIP\x10\x08\x12\r\n\tUPPER_LIP\x10\t\x12\r\n\tLOWER_LIP\x10\n\x12\x0e\n\nMOUTH_LEFT\x10\x0b\x12\x0f\n\x0bMOUTH_RIGHT\x10\x0c\x12\x10\n\x0cMOUTH_CENTER\x10\r\x12\x15\n\x11NOSE_BOTTOM_RIGHT\x10\x0e\x12\x14\n\x10NOSE_BOTTOM_LEFT\x10\x0f\x12\x16\n\x12NOSE_BOTTOM_CENTER\x10\x10\x12\x19\n\x15LEFT_EYE_TOP_BOUNDARY\x10\x11\x12\x19\n\x15LEFT_EYE_RIGHT_CORNER\x10\x12\x12\x1c\n\x18LEFT_EYE_BOTTOM_BOUNDARY\x10\x13\x12\x18\n\x14LEFT_EYE_LEFT_CORNER\x10\x14\x12\x1a\n\x16RIGHT_EYE_TOP_BOUNDARY\x10\x15\x12\x1a\n\x16RIGHT_EYE_RIGHT_CORNER\x10\x16\x12\x1d\n\x19RIGHT_EYE_BOTTOM_BOUNDARY\x10\x17\x12\x19\n\x15RIGHT_EYE_LEFT_CORNER\x10\x18\x12\x1f\n\x1bLEFT_EYEBROW_UPPER_MIDPOINT\x10\x19\x12 \n\x1cRIGHT_EYEBROW_UPPER_MIDPOINT\x10\x1a\x12\x14\n\x10LEFT_EAR_TRAGION\x10\x1b\x12\x15\n\x11RIGHT_EAR_TRAGION\x10\x1c\x12\x12\n\x0eLEFT_EYE_PUPIL\x10\x1d\x12\x13\n\x0fRIGHT_EYE_PUPIL\x10\x1e\x12\x15\n\x11\x46OREHEAD_GLABELLA\x10\x1f\x12\x11\n\rCHIN_GNATHION\x10 \x12\x14\n\x10\x43HIN_LEFT_GONION\x10!\x12\x15\n\x11\x43HIN_RIGHT_GONION\x10""4\n\x0cLocationInfo\x12$\n\x07lat_lng\x18\x01 \x01(\x0b\x32\x13.google.type.LatLng"=\n\x08Property\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t\x12\x14\n\x0cuint64_value\x18\x03 \x01(\x04"\xbc\x02\n\x10\x45ntityAnnotation\x12\x0b\n\x03mid\x18\x01 \x01(\t\x12\x0e\n\x06locale\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\x12\r\n\x05score\x18\x04 \x01(\x02\x12\x12\n\nconfidence\x18\x05 \x01(\x02\x12\x12\n\ntopicality\x18\x06 \x01(\x02\x12\x42\n\rbounding_poly\x18\x07 \x01(\x0b\x32+.google.cloud.vision.v1p1beta1.BoundingPoly\x12>\n\tlocations\x18\x08 \x03(\x0b\x32+.google.cloud.vision.v1p1beta1.LocationInfo\x12;\n\nproperties\x18\t \x03(\x0b\x32\'.google.cloud.vision.v1p1beta1.Property"\xbc\x02\n\x14SafeSearchAnnotation\x12\x38\n\x05\x61\x64ult\x18\x01 \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12\x38\n\x05spoof\x18\x02 \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12:\n\x07medical\x18\x03 \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12;\n\x08violence\x18\x04 \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood\x12\x37\n\x04racy\x18\t \x01(\x0e\x32).google.cloud.vision.v1p1beta1.Likelihood"a\n\x0bLatLongRect\x12(\n\x0bmin_lat_lng\x18\x01 \x01(\x0b\x32\x13.google.type.LatLng\x12(\n\x0bmax_lat_lng\x18\x02 \x01(\x0b\x32\x13.google.type.LatLng"U\n\tColorInfo\x12!\n\x05\x63olor\x18\x01 \x01(\x0b\x32\x12.google.type.Color\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x16\n\x0epixel_fraction\x18\x03 \x01(\x02"T\n\x18\x44ominantColorsAnnotation\x12\x38\n\x06\x63olors\x18\x01 \x03(\x0b\x32(.google.cloud.vision.v1p1beta1.ColorInfo"c\n\x0fImageProperties\x12P\n\x0f\x64ominant_colors\x18\x01 \x01(\x0b\x32\x37.google.cloud.vision.v1p1beta1.DominantColorsAnnotation"\x7f\n\x08\x43ropHint\x12\x42\n\rbounding_poly\x18\x01 \x01(\x0b\x32+.google.cloud.vision.v1p1beta1.BoundingPoly\x12\x12\n\nconfidence\x18\x02 \x01(\x02\x12\x1b\n\x13importance_fraction\x18\x03 \x01(\x02"R\n\x13\x43ropHintsAnnotation\x12;\n\ncrop_hints\x18\x01 \x03(\x0b\x32\'.google.cloud.vision.v1p1beta1.CropHint"(\n\x0f\x43ropHintsParams\x12\x15\n\raspect_ratios\x18\x01 \x03(\x02"1\n\x12WebDetectionParams\x12\x1b\n\x13include_geo_results\x18\x02 \x01(\x08"\x85\x02\n\x0cImageContext\x12\x41\n\rlat_long_rect\x18\x01 \x01(\x0b\x32*.google.cloud.vision.v1p1beta1.LatLongRect\x12\x16\n\x0elanguage_hints\x18\x02 \x03(\t\x12I\n\x11\x63rop_hints_params\x18\x04 \x01(\x0b\x32..google.cloud.vision.v1p1beta1.CropHintsParams\x12O\n\x14web_detection_params\x18\x06 \x01(\x0b\x32\x31.google.cloud.vision.v1p1beta1.WebDetectionParams"\xc9\x01\n\x14\x41nnotateImageRequest\x12\x33\n\x05image\x18\x01 \x01(\x0b\x32$.google.cloud.vision.v1p1beta1.Image\x12\x38\n\x08\x66\x65\x61tures\x18\x02 \x03(\x0b\x32&.google.cloud.vision.v1p1beta1.Feature\x12\x42\n\rimage_context\x18\x03 \x01(\x0b\x32+.google.cloud.vision.v1p1beta1.ImageContext"\xc2\x06\n\x15\x41nnotateImageResponse\x12G\n\x10\x66\x61\x63\x65_annotations\x18\x01 \x03(\x0b\x32-.google.cloud.vision.v1p1beta1.FaceAnnotation\x12M\n\x14landmark_annotations\x18\x02 \x03(\x0b\x32/.google.cloud.vision.v1p1beta1.EntityAnnotation\x12I\n\x10logo_annotations\x18\x03 \x03(\x0b\x32/.google.cloud.vision.v1p1beta1.EntityAnnotation\x12J\n\x11label_annotations\x18\x04 \x03(\x0b\x32/.google.cloud.vision.v1p1beta1.EntityAnnotation\x12I\n\x10text_annotations\x18\x05 \x03(\x0b\x32/.google.cloud.vision.v1p1beta1.EntityAnnotation\x12K\n\x14\x66ull_text_annotation\x18\x0c \x01(\x0b\x32-.google.cloud.vision.v1p1beta1.TextAnnotation\x12S\n\x16safe_search_annotation\x18\x06 \x01(\x0b\x32\x33.google.cloud.vision.v1p1beta1.SafeSearchAnnotation\x12S\n\x1bimage_properties_annotation\x18\x08 \x01(\x0b\x32..google.cloud.vision.v1p1beta1.ImageProperties\x12Q\n\x15\x63rop_hints_annotation\x18\x0b \x01(\x0b\x32\x32.google.cloud.vision.v1p1beta1.CropHintsAnnotation\x12\x42\n\rweb_detection\x18\r \x01(\x0b\x32+.google.cloud.vision.v1p1beta1.WebDetection\x12!\n\x05\x65rror\x18\t \x01(\x0b\x32\x12.google.rpc.Status"h\n\x1a\x42\x61tchAnnotateImagesRequest\x12J\n\x08requests\x18\x01 \x03(\x0b\x32\x33.google.cloud.vision.v1p1beta1.AnnotateImageRequestB\x03\xe0\x41\x02"f\n\x1b\x42\x61tchAnnotateImagesResponse\x12G\n\tresponses\x18\x01 \x03(\x0b\x32\x34.google.cloud.vision.v1p1beta1.AnnotateImageResponse*e\n\nLikelihood\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x11\n\rVERY_UNLIKELY\x10\x01\x12\x0c\n\x08UNLIKELY\x10\x02\x12\x0c\n\x08POSSIBLE\x10\x03\x12\n\n\x06LIKELY\x10\x04\x12\x0f\n\x0bVERY_LIKELY\x10\x05\x32\xc9\x02\n\x0eImageAnnotator\x12\xbe\x01\n\x13\x42\x61tchAnnotateImages\x12\x39.google.cloud.vision.v1p1beta1.BatchAnnotateImagesRequest\x1a:.google.cloud.vision.v1p1beta1.BatchAnnotateImagesResponse"0\x82\xd3\xe4\x93\x02\x1f"\x1a/v1p1beta1/images:annotate:\x01*\xda\x41\x08requests\x1av\xca\x41\x15vision.googleapis.com\xd2\x41[https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-visionB\x82\x01\n!com.google.cloud.vision.v1p1beta1B\x13ImageAnnotatorProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p1beta1;vision\xf8\x01\x01\x62\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_text__annotation__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_web__detection__pb2.DESCRIPTOR, - google_dot_rpc_dot_status__pb2.DESCRIPTOR, - google_dot_type_dot_color__pb2.DESCRIPTOR, - google_dot_type_dot_latlng__pb2.DESCRIPTOR, - ], -) - -_LIKELIHOOD = _descriptor.EnumDescriptor( - name="Likelihood", - full_name="google.cloud.vision.v1p1beta1.Likelihood", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNKNOWN", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="VERY_UNLIKELY", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="UNLIKELY", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="POSSIBLE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LIKELY", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="VERY_LIKELY", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=5694, - serialized_end=5795, -) -_sym_db.RegisterEnumDescriptor(_LIKELIHOOD) - -Likelihood = enum_type_wrapper.EnumTypeWrapper(_LIKELIHOOD) -UNKNOWN = 0 -VERY_UNLIKELY = 1 -UNLIKELY = 2 -POSSIBLE = 3 -LIKELY = 4 -VERY_LIKELY = 5 - - -_FEATURE_TYPE = _descriptor.EnumDescriptor( - name="Type", - full_name="google.cloud.vision.v1p1beta1.Feature.Type", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="TYPE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FACE_DETECTION", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LANDMARK_DETECTION", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LOGO_DETECTION", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LABEL_DETECTION", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="TEXT_DETECTION", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DOCUMENT_TEXT_DETECTION", - index=6, - number=11, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SAFE_SEARCH_DETECTION", - index=7, - number=6, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="IMAGE_PROPERTIES", - index=8, - number=7, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CROP_HINTS", - index=9, - number=9, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="WEB_DETECTION", - index=10, - number=10, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=532, - serialized_end=778, -) -_sym_db.RegisterEnumDescriptor(_FEATURE_TYPE) - -_FACEANNOTATION_LANDMARK_TYPE = _descriptor.EnumDescriptor( - name="Type", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.Landmark.Type", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNKNOWN_LANDMARK", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_OF_LEFT_EYEBROW", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_OF_LEFT_EYEBROW", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_OF_RIGHT_EYEBROW", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_OF_RIGHT_EYEBROW", - index=6, - number=6, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MIDPOINT_BETWEEN_EYES", - index=7, - number=7, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NOSE_TIP", - index=8, - number=8, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="UPPER_LIP", - index=9, - number=9, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LOWER_LIP", - index=10, - number=10, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MOUTH_LEFT", - index=11, - number=11, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MOUTH_RIGHT", - index=12, - number=12, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MOUTH_CENTER", - index=13, - number=13, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NOSE_BOTTOM_RIGHT", - index=14, - number=14, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NOSE_BOTTOM_LEFT", - index=15, - number=15, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NOSE_BOTTOM_CENTER", - index=16, - number=16, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_TOP_BOUNDARY", - index=17, - number=17, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_RIGHT_CORNER", - index=18, - number=18, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_BOTTOM_BOUNDARY", - index=19, - number=19, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_LEFT_CORNER", - index=20, - number=20, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_TOP_BOUNDARY", - index=21, - number=21, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_RIGHT_CORNER", - index=22, - number=22, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_BOTTOM_BOUNDARY", - index=23, - number=23, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_LEFT_CORNER", - index=24, - number=24, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYEBROW_UPPER_MIDPOINT", - index=25, - number=25, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYEBROW_UPPER_MIDPOINT", - index=26, - number=26, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EAR_TRAGION", - index=27, - number=27, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EAR_TRAGION", - index=28, - number=28, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_PUPIL", - index=29, - number=29, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_PUPIL", - index=30, - number=30, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FOREHEAD_GLABELLA", - index=31, - number=31, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CHIN_GNATHION", - index=32, - number=32, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CHIN_LEFT_GONION", - index=33, - number=33, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CHIN_RIGHT_GONION", - index=34, - number=34, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=1923, - serialized_end=2743, -) -_sym_db.RegisterEnumDescriptor(_FACEANNOTATION_LANDMARK_TYPE) - - -_FEATURE = _descriptor.Descriptor( - name="Feature", - full_name="google.cloud.vision.v1p1beta1.Feature", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="type", - full_name="google.cloud.vision.v1p1beta1.Feature.type", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="max_results", - full_name="google.cloud.vision.v1p1beta1.Feature.max_results", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="model", - full_name="google.cloud.vision.v1p1beta1.Feature.model", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_FEATURE_TYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=425, - serialized_end=778, -) - - -_IMAGESOURCE = _descriptor.Descriptor( - name="ImageSource", - full_name="google.cloud.vision.v1p1beta1.ImageSource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_image_uri", - full_name="google.cloud.vision.v1p1beta1.ImageSource.gcs_image_uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_uri", - full_name="google.cloud.vision.v1p1beta1.ImageSource.image_uri", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=780, - serialized_end=835, -) - - -_IMAGE = _descriptor.Descriptor( - name="Image", - full_name="google.cloud.vision.v1p1beta1.Image", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="content", - full_name="google.cloud.vision.v1p1beta1.Image.content", - index=0, - number=1, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"", - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source", - full_name="google.cloud.vision.v1p1beta1.Image.source", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=837, - serialized_end=921, -) - - -_FACEANNOTATION_LANDMARK = _descriptor.Descriptor( - name="Landmark", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.Landmark", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="type", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.Landmark.type", - index=0, - number=3, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="position", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.Landmark.position", - index=1, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_FACEANNOTATION_LANDMARK_TYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1776, - serialized_end=2743, -) - -_FACEANNOTATION = _descriptor.Descriptor( - name="FaceAnnotation", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.bounding_poly", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="fd_bounding_poly", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.fd_bounding_poly", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="landmarks", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.landmarks", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="roll_angle", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.roll_angle", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="pan_angle", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.pan_angle", - index=4, - number=5, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="tilt_angle", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.tilt_angle", - index=5, - number=6, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="detection_confidence", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.detection_confidence", - index=6, - number=7, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="landmarking_confidence", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.landmarking_confidence", - index=7, - number=8, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="joy_likelihood", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.joy_likelihood", - index=8, - number=9, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="sorrow_likelihood", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.sorrow_likelihood", - index=9, - number=10, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="anger_likelihood", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.anger_likelihood", - index=10, - number=11, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="surprise_likelihood", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.surprise_likelihood", - index=11, - number=12, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="under_exposed_likelihood", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.under_exposed_likelihood", - index=12, - number=13, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="blurred_likelihood", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.blurred_likelihood", - index=13, - number=14, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="headwear_likelihood", - full_name="google.cloud.vision.v1p1beta1.FaceAnnotation.headwear_likelihood", - index=14, - number=15, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_FACEANNOTATION_LANDMARK,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=924, - serialized_end=2743, -) - - -_LOCATIONINFO = _descriptor.Descriptor( - name="LocationInfo", - full_name="google.cloud.vision.v1p1beta1.LocationInfo", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="lat_lng", - full_name="google.cloud.vision.v1p1beta1.LocationInfo.lat_lng", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2745, - serialized_end=2797, -) - - -_PROPERTY = _descriptor.Descriptor( - name="Property", - full_name="google.cloud.vision.v1p1beta1.Property", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p1beta1.Property.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.vision.v1p1beta1.Property.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="uint64_value", - full_name="google.cloud.vision.v1p1beta1.Property.uint64_value", - index=2, - number=3, - type=4, - cpp_type=4, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2799, - serialized_end=2860, -) - - -_ENTITYANNOTATION = _descriptor.Descriptor( - name="EntityAnnotation", - full_name="google.cloud.vision.v1p1beta1.EntityAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="mid", - full_name="google.cloud.vision.v1p1beta1.EntityAnnotation.mid", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="locale", - full_name="google.cloud.vision.v1p1beta1.EntityAnnotation.locale", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.vision.v1p1beta1.EntityAnnotation.description", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p1beta1.EntityAnnotation.score", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p1beta1.EntityAnnotation.confidence", - index=4, - number=5, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="topicality", - full_name="google.cloud.vision.v1p1beta1.EntityAnnotation.topicality", - index=5, - number=6, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p1beta1.EntityAnnotation.bounding_poly", - index=6, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="locations", - full_name="google.cloud.vision.v1p1beta1.EntityAnnotation.locations", - index=7, - number=8, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="properties", - full_name="google.cloud.vision.v1p1beta1.EntityAnnotation.properties", - index=8, - number=9, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2863, - serialized_end=3179, -) - - -_SAFESEARCHANNOTATION = _descriptor.Descriptor( - name="SafeSearchAnnotation", - full_name="google.cloud.vision.v1p1beta1.SafeSearchAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="adult", - full_name="google.cloud.vision.v1p1beta1.SafeSearchAnnotation.adult", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="spoof", - full_name="google.cloud.vision.v1p1beta1.SafeSearchAnnotation.spoof", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="medical", - full_name="google.cloud.vision.v1p1beta1.SafeSearchAnnotation.medical", - index=2, - number=3, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="violence", - full_name="google.cloud.vision.v1p1beta1.SafeSearchAnnotation.violence", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="racy", - full_name="google.cloud.vision.v1p1beta1.SafeSearchAnnotation.racy", - index=4, - number=9, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3182, - serialized_end=3498, -) - - -_LATLONGRECT = _descriptor.Descriptor( - name="LatLongRect", - full_name="google.cloud.vision.v1p1beta1.LatLongRect", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="min_lat_lng", - full_name="google.cloud.vision.v1p1beta1.LatLongRect.min_lat_lng", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="max_lat_lng", - full_name="google.cloud.vision.v1p1beta1.LatLongRect.max_lat_lng", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3500, - serialized_end=3597, -) - - -_COLORINFO = _descriptor.Descriptor( - name="ColorInfo", - full_name="google.cloud.vision.v1p1beta1.ColorInfo", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="color", - full_name="google.cloud.vision.v1p1beta1.ColorInfo.color", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p1beta1.ColorInfo.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="pixel_fraction", - full_name="google.cloud.vision.v1p1beta1.ColorInfo.pixel_fraction", - index=2, - number=3, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3599, - serialized_end=3684, -) - - -_DOMINANTCOLORSANNOTATION = _descriptor.Descriptor( - name="DominantColorsAnnotation", - full_name="google.cloud.vision.v1p1beta1.DominantColorsAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="colors", - full_name="google.cloud.vision.v1p1beta1.DominantColorsAnnotation.colors", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3686, - serialized_end=3770, -) - - -_IMAGEPROPERTIES = _descriptor.Descriptor( - name="ImageProperties", - full_name="google.cloud.vision.v1p1beta1.ImageProperties", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="dominant_colors", - full_name="google.cloud.vision.v1p1beta1.ImageProperties.dominant_colors", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3772, - serialized_end=3871, -) - - -_CROPHINT = _descriptor.Descriptor( - name="CropHint", - full_name="google.cloud.vision.v1p1beta1.CropHint", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p1beta1.CropHint.bounding_poly", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p1beta1.CropHint.confidence", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="importance_fraction", - full_name="google.cloud.vision.v1p1beta1.CropHint.importance_fraction", - index=2, - number=3, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3873, - serialized_end=4000, -) - - -_CROPHINTSANNOTATION = _descriptor.Descriptor( - name="CropHintsAnnotation", - full_name="google.cloud.vision.v1p1beta1.CropHintsAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="crop_hints", - full_name="google.cloud.vision.v1p1beta1.CropHintsAnnotation.crop_hints", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4002, - serialized_end=4084, -) - - -_CROPHINTSPARAMS = _descriptor.Descriptor( - name="CropHintsParams", - full_name="google.cloud.vision.v1p1beta1.CropHintsParams", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="aspect_ratios", - full_name="google.cloud.vision.v1p1beta1.CropHintsParams.aspect_ratios", - index=0, - number=1, - type=2, - cpp_type=6, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4086, - serialized_end=4126, -) - - -_WEBDETECTIONPARAMS = _descriptor.Descriptor( - name="WebDetectionParams", - full_name="google.cloud.vision.v1p1beta1.WebDetectionParams", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="include_geo_results", - full_name="google.cloud.vision.v1p1beta1.WebDetectionParams.include_geo_results", - index=0, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4128, - serialized_end=4177, -) - - -_IMAGECONTEXT = _descriptor.Descriptor( - name="ImageContext", - full_name="google.cloud.vision.v1p1beta1.ImageContext", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="lat_long_rect", - full_name="google.cloud.vision.v1p1beta1.ImageContext.lat_long_rect", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="language_hints", - full_name="google.cloud.vision.v1p1beta1.ImageContext.language_hints", - index=1, - number=2, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="crop_hints_params", - full_name="google.cloud.vision.v1p1beta1.ImageContext.crop_hints_params", - index=2, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="web_detection_params", - full_name="google.cloud.vision.v1p1beta1.ImageContext.web_detection_params", - index=3, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4180, - serialized_end=4441, -) - - -_ANNOTATEIMAGEREQUEST = _descriptor.Descriptor( - name="AnnotateImageRequest", - full_name="google.cloud.vision.v1p1beta1.AnnotateImageRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="image", - full_name="google.cloud.vision.v1p1beta1.AnnotateImageRequest.image", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="features", - full_name="google.cloud.vision.v1p1beta1.AnnotateImageRequest.features", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_context", - full_name="google.cloud.vision.v1p1beta1.AnnotateImageRequest.image_context", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4444, - serialized_end=4645, -) - - -_ANNOTATEIMAGERESPONSE = _descriptor.Descriptor( - name="AnnotateImageResponse", - full_name="google.cloud.vision.v1p1beta1.AnnotateImageResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="face_annotations", - full_name="google.cloud.vision.v1p1beta1.AnnotateImageResponse.face_annotations", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="landmark_annotations", - full_name="google.cloud.vision.v1p1beta1.AnnotateImageResponse.landmark_annotations", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="logo_annotations", - full_name="google.cloud.vision.v1p1beta1.AnnotateImageResponse.logo_annotations", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="label_annotations", - full_name="google.cloud.vision.v1p1beta1.AnnotateImageResponse.label_annotations", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="text_annotations", - full_name="google.cloud.vision.v1p1beta1.AnnotateImageResponse.text_annotations", - index=4, - number=5, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="full_text_annotation", - full_name="google.cloud.vision.v1p1beta1.AnnotateImageResponse.full_text_annotation", - index=5, - number=12, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="safe_search_annotation", - full_name="google.cloud.vision.v1p1beta1.AnnotateImageResponse.safe_search_annotation", - index=6, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_properties_annotation", - full_name="google.cloud.vision.v1p1beta1.AnnotateImageResponse.image_properties_annotation", - index=7, - number=8, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="crop_hints_annotation", - full_name="google.cloud.vision.v1p1beta1.AnnotateImageResponse.crop_hints_annotation", - index=8, - number=11, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="web_detection", - full_name="google.cloud.vision.v1p1beta1.AnnotateImageResponse.web_detection", - index=9, - number=13, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="error", - full_name="google.cloud.vision.v1p1beta1.AnnotateImageResponse.error", - index=10, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4648, - serialized_end=5482, -) - - -_BATCHANNOTATEIMAGESREQUEST = _descriptor.Descriptor( - name="BatchAnnotateImagesRequest", - full_name="google.cloud.vision.v1p1beta1.BatchAnnotateImagesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="requests", - full_name="google.cloud.vision.v1p1beta1.BatchAnnotateImagesRequest.requests", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5484, - serialized_end=5588, -) - - -_BATCHANNOTATEIMAGESRESPONSE = _descriptor.Descriptor( - name="BatchAnnotateImagesResponse", - full_name="google.cloud.vision.v1p1beta1.BatchAnnotateImagesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="responses", - full_name="google.cloud.vision.v1p1beta1.BatchAnnotateImagesResponse.responses", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5590, - serialized_end=5692, -) - -_FEATURE.fields_by_name["type"].enum_type = _FEATURE_TYPE -_FEATURE_TYPE.containing_type = _FEATURE -_IMAGE.fields_by_name["source"].message_type = _IMAGESOURCE -_FACEANNOTATION_LANDMARK.fields_by_name[ - "type" -].enum_type = _FACEANNOTATION_LANDMARK_TYPE -_FACEANNOTATION_LANDMARK.fields_by_name[ - "position" -].message_type = ( - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2._POSITION -) -_FACEANNOTATION_LANDMARK.containing_type = _FACEANNOTATION -_FACEANNOTATION_LANDMARK_TYPE.containing_type = _FACEANNOTATION_LANDMARK -_FACEANNOTATION.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_FACEANNOTATION.fields_by_name[ - "fd_bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_FACEANNOTATION.fields_by_name["landmarks"].message_type = _FACEANNOTATION_LANDMARK -_FACEANNOTATION.fields_by_name["joy_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["sorrow_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["anger_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["surprise_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["under_exposed_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["blurred_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["headwear_likelihood"].enum_type = _LIKELIHOOD -_LOCATIONINFO.fields_by_name[ - "lat_lng" -].message_type = google_dot_type_dot_latlng__pb2._LATLNG -_ENTITYANNOTATION.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_ENTITYANNOTATION.fields_by_name["locations"].message_type = _LOCATIONINFO -_ENTITYANNOTATION.fields_by_name["properties"].message_type = _PROPERTY -_SAFESEARCHANNOTATION.fields_by_name["adult"].enum_type = _LIKELIHOOD -_SAFESEARCHANNOTATION.fields_by_name["spoof"].enum_type = _LIKELIHOOD -_SAFESEARCHANNOTATION.fields_by_name["medical"].enum_type = _LIKELIHOOD -_SAFESEARCHANNOTATION.fields_by_name["violence"].enum_type = _LIKELIHOOD -_SAFESEARCHANNOTATION.fields_by_name["racy"].enum_type = _LIKELIHOOD -_LATLONGRECT.fields_by_name[ - "min_lat_lng" -].message_type = google_dot_type_dot_latlng__pb2._LATLNG -_LATLONGRECT.fields_by_name[ - "max_lat_lng" -].message_type = google_dot_type_dot_latlng__pb2._LATLNG -_COLORINFO.fields_by_name["color"].message_type = google_dot_type_dot_color__pb2._COLOR -_DOMINANTCOLORSANNOTATION.fields_by_name["colors"].message_type = _COLORINFO -_IMAGEPROPERTIES.fields_by_name[ - "dominant_colors" -].message_type = _DOMINANTCOLORSANNOTATION -_CROPHINT.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_CROPHINTSANNOTATION.fields_by_name["crop_hints"].message_type = _CROPHINT -_IMAGECONTEXT.fields_by_name["lat_long_rect"].message_type = _LATLONGRECT -_IMAGECONTEXT.fields_by_name["crop_hints_params"].message_type = _CROPHINTSPARAMS -_IMAGECONTEXT.fields_by_name["web_detection_params"].message_type = _WEBDETECTIONPARAMS -_ANNOTATEIMAGEREQUEST.fields_by_name["image"].message_type = _IMAGE -_ANNOTATEIMAGEREQUEST.fields_by_name["features"].message_type = _FEATURE -_ANNOTATEIMAGEREQUEST.fields_by_name["image_context"].message_type = _IMAGECONTEXT -_ANNOTATEIMAGERESPONSE.fields_by_name["face_annotations"].message_type = _FACEANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "landmark_annotations" -].message_type = _ENTITYANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "logo_annotations" -].message_type = _ENTITYANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "label_annotations" -].message_type = _ENTITYANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "text_annotations" -].message_type = _ENTITYANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "full_text_annotation" -].message_type = ( - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_text__annotation__pb2._TEXTANNOTATION -) -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "safe_search_annotation" -].message_type = _SAFESEARCHANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "image_properties_annotation" -].message_type = _IMAGEPROPERTIES -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "crop_hints_annotation" -].message_type = _CROPHINTSANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "web_detection" -].message_type = ( - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_web__detection__pb2._WEBDETECTION -) -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "error" -].message_type = google_dot_rpc_dot_status__pb2._STATUS -_BATCHANNOTATEIMAGESREQUEST.fields_by_name[ - "requests" -].message_type = _ANNOTATEIMAGEREQUEST -_BATCHANNOTATEIMAGESRESPONSE.fields_by_name[ - "responses" -].message_type = _ANNOTATEIMAGERESPONSE -DESCRIPTOR.message_types_by_name["Feature"] = _FEATURE -DESCRIPTOR.message_types_by_name["ImageSource"] = _IMAGESOURCE -DESCRIPTOR.message_types_by_name["Image"] = _IMAGE -DESCRIPTOR.message_types_by_name["FaceAnnotation"] = _FACEANNOTATION -DESCRIPTOR.message_types_by_name["LocationInfo"] = _LOCATIONINFO -DESCRIPTOR.message_types_by_name["Property"] = _PROPERTY -DESCRIPTOR.message_types_by_name["EntityAnnotation"] = _ENTITYANNOTATION -DESCRIPTOR.message_types_by_name["SafeSearchAnnotation"] = _SAFESEARCHANNOTATION -DESCRIPTOR.message_types_by_name["LatLongRect"] = _LATLONGRECT -DESCRIPTOR.message_types_by_name["ColorInfo"] = _COLORINFO -DESCRIPTOR.message_types_by_name["DominantColorsAnnotation"] = _DOMINANTCOLORSANNOTATION -DESCRIPTOR.message_types_by_name["ImageProperties"] = _IMAGEPROPERTIES -DESCRIPTOR.message_types_by_name["CropHint"] = _CROPHINT -DESCRIPTOR.message_types_by_name["CropHintsAnnotation"] = _CROPHINTSANNOTATION -DESCRIPTOR.message_types_by_name["CropHintsParams"] = _CROPHINTSPARAMS -DESCRIPTOR.message_types_by_name["WebDetectionParams"] = _WEBDETECTIONPARAMS -DESCRIPTOR.message_types_by_name["ImageContext"] = _IMAGECONTEXT -DESCRIPTOR.message_types_by_name["AnnotateImageRequest"] = _ANNOTATEIMAGEREQUEST -DESCRIPTOR.message_types_by_name["AnnotateImageResponse"] = _ANNOTATEIMAGERESPONSE -DESCRIPTOR.message_types_by_name[ - "BatchAnnotateImagesRequest" -] = _BATCHANNOTATEIMAGESREQUEST -DESCRIPTOR.message_types_by_name[ - "BatchAnnotateImagesResponse" -] = _BATCHANNOTATEIMAGESRESPONSE -DESCRIPTOR.enum_types_by_name["Likelihood"] = _LIKELIHOOD -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Feature = _reflection.GeneratedProtocolMessageType( - "Feature", - (_message.Message,), - { - "DESCRIPTOR": _FEATURE, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Users describe the type of Google Cloud Vision API tasks to perform - over images by using *Feature*\ s. Each Feature indicates a type of - image detection task to perform. Features encode the Cloud Vision API - vertical to operate on and the number of top-scoring results to - return. - - Attributes: - type: - The feature type. - max_results: - Maximum number of results of this type. - model: - Model to use for the feature. Supported values: - “builtin/stable” (the default if unset) and “builtin/latest”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.Feature) - }, -) -_sym_db.RegisterMessage(Feature) - -ImageSource = _reflection.GeneratedProtocolMessageType( - "ImageSource", - (_message.Message,), - { - "DESCRIPTOR": _IMAGESOURCE, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """External image source (Google Cloud Storage image location). - - Attributes: - gcs_image_uri: - NOTE: For new code ``image_uri`` below is preferred. Google - Cloud Storage image URI, which must be in the following form: - ``gs://bucket_name/object_name`` (for details, see `Google - Cloud Storage Request URIs - `__). - NOTE: Cloud Storage object versioning is not supported. - image_uri: - Image URI which supports: 1) Google Cloud Storage image URI, - which must be in the following form: - ``gs://bucket_name/object_name`` (for details, see `Google - Cloud Storage Request URIs - `__). - NOTE: Cloud Storage object versioning is not supported. 2) - Publicly accessible image HTTP/HTTPS URL. This is preferred - over the legacy ``gcs_image_uri`` above. When both - ``gcs_image_uri`` and ``image_uri`` are specified, - ``image_uri`` takes precedence. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.ImageSource) - }, -) -_sym_db.RegisterMessage(ImageSource) - -Image = _reflection.GeneratedProtocolMessageType( - "Image", - (_message.Message,), - { - "DESCRIPTOR": _IMAGE, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Client image to perform Google Cloud Vision API tasks over. - - Attributes: - content: - Image content, represented as a stream of bytes. Note: as with - all ``bytes`` fields, protobuffers use a pure binary - representation, whereas JSON representations use base64. - source: - Google Cloud Storage image location. If both ``content`` and - ``source`` are provided for an image, ``content`` takes - precedence and is used to perform the image annotation - request. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.Image) - }, -) -_sym_db.RegisterMessage(Image) - -FaceAnnotation = _reflection.GeneratedProtocolMessageType( - "FaceAnnotation", - (_message.Message,), - { - "Landmark": _reflection.GeneratedProtocolMessageType( - "Landmark", - (_message.Message,), - { - "DESCRIPTOR": _FACEANNOTATION_LANDMARK, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """A face-specific landmark (for example, a face feature). - - Attributes: - type: - Face landmark type. - position: - Face landmark position. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.FaceAnnotation.Landmark) - }, - ), - "DESCRIPTOR": _FACEANNOTATION, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """A face annotation object contains the results of face detection. - - Attributes: - bounding_poly: - The bounding polygon around the face. The coordinates of the - bounding box are in the original image’s scale, as returned in - ``ImageParams``. The bounding box is computed to “frame” the - face in accordance with human expectations. It is based on the - landmarker results. Note that one or more x and/or y - coordinates may not be generated in the ``BoundingPoly`` (the - polygon will be unbounded) if only a partial face appears in - the image to be annotated. - fd_bounding_poly: - The ``fd_bounding_poly`` bounding polygon is tighter than the - ``boundingPoly``, and encloses only the skin part of the face. - Typically, it is used to eliminate the face from any image - analysis that detects the “amount of skin” visible in an - image. It is not based on the landmarker results, only on the - initial face detection, hence the fd (face detection) prefix. - landmarks: - Detected face landmarks. - roll_angle: - Roll angle, which indicates the amount of clockwise/anti- - clockwise rotation of the face relative to the image vertical - about the axis perpendicular to the face. Range [-180,180]. - pan_angle: - Yaw angle, which indicates the leftward/rightward angle that - the face is pointing relative to the vertical plane - perpendicular to the image. Range [-180,180]. - tilt_angle: - Pitch angle, which indicates the upwards/downwards angle that - the face is pointing relative to the image’s horizontal plane. - Range [-180,180]. - detection_confidence: - Detection confidence. Range [0, 1]. - landmarking_confidence: - Face landmarking confidence. Range [0, 1]. - joy_likelihood: - Joy likelihood. - sorrow_likelihood: - Sorrow likelihood. - anger_likelihood: - Anger likelihood. - surprise_likelihood: - Surprise likelihood. - under_exposed_likelihood: - Under-exposed likelihood. - blurred_likelihood: - Blurred likelihood. - headwear_likelihood: - Headwear likelihood. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.FaceAnnotation) - }, -) -_sym_db.RegisterMessage(FaceAnnotation) -_sym_db.RegisterMessage(FaceAnnotation.Landmark) - -LocationInfo = _reflection.GeneratedProtocolMessageType( - "LocationInfo", - (_message.Message,), - { - "DESCRIPTOR": _LOCATIONINFO, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Detected entity location information. - - Attributes: - lat_lng: - lat/long location coordinates. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.LocationInfo) - }, -) -_sym_db.RegisterMessage(LocationInfo) - -Property = _reflection.GeneratedProtocolMessageType( - "Property", - (_message.Message,), - { - "DESCRIPTOR": _PROPERTY, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """A ``Property`` consists of a user-supplied name/value pair. - - Attributes: - name: - Name of the property. - value: - Value of the property. - uint64_value: - Value of numeric properties. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.Property) - }, -) -_sym_db.RegisterMessage(Property) - -EntityAnnotation = _reflection.GeneratedProtocolMessageType( - "EntityAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _ENTITYANNOTATION, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Set of detected entity features. - - Attributes: - mid: - Opaque entity ID. Some IDs may be available in `Google - Knowledge Graph Search API - `__. - locale: - The language code for the locale in which the entity textual - ``description`` is expressed. - description: - Entity textual description, expressed in its ``locale`` - language. - score: - Overall score of the result. Range [0, 1]. - confidence: - The accuracy of the entity detection in an image. For example, - for an image in which the “Eiffel Tower” entity is detected, - this field represents the confidence that there is a tower in - the query image. Range [0, 1]. - topicality: - The relevancy of the ICA (Image Content Annotation) label to - the image. For example, the relevancy of “tower” is likely - higher to an image containing the detected “Eiffel Tower” than - to an image containing a detected distant towering building, - even though the confidence that there is a tower in each image - may be the same. Range [0, 1]. - bounding_poly: - Image region to which this entity belongs. Not produced for - ``LABEL_DETECTION`` features. - locations: - The location information for the detected entity. Multiple - ``LocationInfo`` elements can be present because one location - may indicate the location of the scene in the image, and - another location may indicate the location of the place where - the image was taken. Location information is usually present - for landmarks. - properties: - Some entities may have optional user-supplied ``Property`` - (name/value) fields, such a score or string that qualifies the - entity. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.EntityAnnotation) - }, -) -_sym_db.RegisterMessage(EntityAnnotation) - -SafeSearchAnnotation = _reflection.GeneratedProtocolMessageType( - "SafeSearchAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _SAFESEARCHANNOTATION, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Set of features pertaining to the image, computed by computer vision - methods over safe-search verticals (for example, adult, spoof, - medical, violence). - - Attributes: - adult: - Represents the adult content likelihood for the image. Adult - content may contain elements such as nudity, pornographic - images or cartoons, or sexual activities. - spoof: - Spoof likelihood. The likelihood that an modification was made - to the image’s canonical version to make it appear funny or - offensive. - medical: - Likelihood that this is a medical image. - violence: - Likelihood that this image contains violent content. - racy: - Likelihood that the request image contains racy content. Racy - content may include (but is not limited to) skimpy or sheer - clothing, strategically covered nudity, lewd or provocative - poses, or close-ups of sensitive body areas. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.SafeSearchAnnotation) - }, -) -_sym_db.RegisterMessage(SafeSearchAnnotation) - -LatLongRect = _reflection.GeneratedProtocolMessageType( - "LatLongRect", - (_message.Message,), - { - "DESCRIPTOR": _LATLONGRECT, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Rectangle determined by min and max ``LatLng`` pairs. - - Attributes: - min_lat_lng: - Min lat/long pair. - max_lat_lng: - Max lat/long pair. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.LatLongRect) - }, -) -_sym_db.RegisterMessage(LatLongRect) - -ColorInfo = _reflection.GeneratedProtocolMessageType( - "ColorInfo", - (_message.Message,), - { - "DESCRIPTOR": _COLORINFO, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Color information consists of RGB channels, score, and the fraction of - the image that the color occupies in the image. - - Attributes: - color: - RGB components of the color. - score: - Image-specific score for this color. Value in range [0, 1]. - pixel_fraction: - The fraction of pixels the color occupies in the image. Value - in range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.ColorInfo) - }, -) -_sym_db.RegisterMessage(ColorInfo) - -DominantColorsAnnotation = _reflection.GeneratedProtocolMessageType( - "DominantColorsAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _DOMINANTCOLORSANNOTATION, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Set of dominant colors and their corresponding scores. - - Attributes: - colors: - RGB color values with their score and pixel fraction. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.DominantColorsAnnotation) - }, -) -_sym_db.RegisterMessage(DominantColorsAnnotation) - -ImageProperties = _reflection.GeneratedProtocolMessageType( - "ImageProperties", - (_message.Message,), - { - "DESCRIPTOR": _IMAGEPROPERTIES, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Stores image properties, such as dominant colors. - - Attributes: - dominant_colors: - If present, dominant colors completed successfully. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.ImageProperties) - }, -) -_sym_db.RegisterMessage(ImageProperties) - -CropHint = _reflection.GeneratedProtocolMessageType( - "CropHint", - (_message.Message,), - { - "DESCRIPTOR": _CROPHINT, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Single crop hint that is used to generate a new crop when serving an - image. - - Attributes: - bounding_poly: - The bounding polygon for the crop region. The coordinates of - the bounding box are in the original image’s scale, as - returned in ``ImageParams``. - confidence: - Confidence of this being a salient region. Range [0, 1]. - importance_fraction: - Fraction of importance of this salient region with respect to - the original image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.CropHint) - }, -) -_sym_db.RegisterMessage(CropHint) - -CropHintsAnnotation = _reflection.GeneratedProtocolMessageType( - "CropHintsAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _CROPHINTSANNOTATION, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Set of crop hints that are used to generate new crops when serving - images. - - Attributes: - crop_hints: - Crop hint results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.CropHintsAnnotation) - }, -) -_sym_db.RegisterMessage(CropHintsAnnotation) - -CropHintsParams = _reflection.GeneratedProtocolMessageType( - "CropHintsParams", - (_message.Message,), - { - "DESCRIPTOR": _CROPHINTSPARAMS, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Parameters for crop hints annotation request. - - Attributes: - aspect_ratios: - Aspect ratios in floats, representing the ratio of the width - to the height of the image. For example, if the desired aspect - ratio is 4/3, the corresponding float value should be 1.33333. - If not specified, the best possible crop is returned. The - number of provided aspect ratios is limited to a maximum of - 16; any aspect ratios provided after the 16th are ignored. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.CropHintsParams) - }, -) -_sym_db.RegisterMessage(CropHintsParams) - -WebDetectionParams = _reflection.GeneratedProtocolMessageType( - "WebDetectionParams", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTIONPARAMS, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Parameters for web detection request. - - Attributes: - include_geo_results: - Whether to include results derived from the geo information in - the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.WebDetectionParams) - }, -) -_sym_db.RegisterMessage(WebDetectionParams) - -ImageContext = _reflection.GeneratedProtocolMessageType( - "ImageContext", - (_message.Message,), - { - "DESCRIPTOR": _IMAGECONTEXT, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Image context and/or feature-specific parameters. - - Attributes: - lat_long_rect: - lat/long rectangle that specifies the location of the image. - language_hints: - List of languages to use for TEXT_DETECTION. In most cases, an - empty value yields the best results since it enables automatic - language detection. For languages based on the Latin alphabet, - setting ``language_hints`` is not needed. In rare cases, when - the language of the text in the image is known, setting a hint - will help get better results (although it will be a - significant hindrance if the hint is wrong). Text detection - returns an error if one or more of the specified languages is - not one of the `supported languages - `__. - crop_hints_params: - Parameters for crop hints annotation request. - web_detection_params: - Parameters for web detection. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.ImageContext) - }, -) -_sym_db.RegisterMessage(ImageContext) - -AnnotateImageRequest = _reflection.GeneratedProtocolMessageType( - "AnnotateImageRequest", - (_message.Message,), - { - "DESCRIPTOR": _ANNOTATEIMAGEREQUEST, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Request for performing Google Cloud Vision API tasks over a user- - provided image, with user-requested features. - - Attributes: - image: - The image to be processed. - features: - Requested features. - image_context: - Additional context that may accompany the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.AnnotateImageRequest) - }, -) -_sym_db.RegisterMessage(AnnotateImageRequest) - -AnnotateImageResponse = _reflection.GeneratedProtocolMessageType( - "AnnotateImageResponse", - (_message.Message,), - { - "DESCRIPTOR": _ANNOTATEIMAGERESPONSE, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Response to an image annotation request. - - Attributes: - face_annotations: - If present, face detection has completed successfully. - landmark_annotations: - If present, landmark detection has completed successfully. - logo_annotations: - If present, logo detection has completed successfully. - label_annotations: - If present, label detection has completed successfully. - text_annotations: - If present, text (OCR) detection has completed successfully. - full_text_annotation: - If present, text (OCR) detection or document (OCR) text - detection has completed successfully. This annotation provides - the structural hierarchy for the OCR detected text. - safe_search_annotation: - If present, safe-search annotation has completed successfully. - image_properties_annotation: - If present, image properties were extracted successfully. - crop_hints_annotation: - If present, crop hints have completed successfully. - web_detection: - If present, web detection has completed successfully. - error: - If set, represents the error message for the operation. Note - that filled-in image annotations are guaranteed to be correct, - even when ``error`` is set. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.AnnotateImageResponse) - }, -) -_sym_db.RegisterMessage(AnnotateImageResponse) - -BatchAnnotateImagesRequest = _reflection.GeneratedProtocolMessageType( - "BatchAnnotateImagesRequest", - (_message.Message,), - { - "DESCRIPTOR": _BATCHANNOTATEIMAGESREQUEST, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Multiple image annotation requests are batched into a single service - call. - - Attributes: - requests: - Required. Individual image annotation requests for this batch. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.BatchAnnotateImagesRequest) - }, -) -_sym_db.RegisterMessage(BatchAnnotateImagesRequest) - -BatchAnnotateImagesResponse = _reflection.GeneratedProtocolMessageType( - "BatchAnnotateImagesResponse", - (_message.Message,), - { - "DESCRIPTOR": _BATCHANNOTATEIMAGESRESPONSE, - "__module__": "google.cloud.vision_v1p1beta1.proto.image_annotator_pb2", - "__doc__": """Response to a batch image annotation request. - - Attributes: - responses: - Individual responses to image annotation requests within the - batch. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.BatchAnnotateImagesResponse) - }, -) -_sym_db.RegisterMessage(BatchAnnotateImagesResponse) - - -DESCRIPTOR._options = None -_BATCHANNOTATEIMAGESREQUEST.fields_by_name["requests"]._options = None - -_IMAGEANNOTATOR = _descriptor.ServiceDescriptor( - name="ImageAnnotator", - full_name="google.cloud.vision.v1p1beta1.ImageAnnotator", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\025vision.googleapis.com\322A[https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-vision", - create_key=_descriptor._internal_create_key, - serialized_start=5798, - serialized_end=6127, - methods=[ - _descriptor.MethodDescriptor( - name="BatchAnnotateImages", - full_name="google.cloud.vision.v1p1beta1.ImageAnnotator.BatchAnnotateImages", - index=0, - containing_service=None, - input_type=_BATCHANNOTATEIMAGESREQUEST, - output_type=_BATCHANNOTATEIMAGESRESPONSE, - serialized_options=b'\202\323\344\223\002\037"\032/v1p1beta1/images:annotate:\001*\332A\010requests', - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_IMAGEANNOTATOR) - -DESCRIPTOR.services_by_name["ImageAnnotator"] = _IMAGEANNOTATOR - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p1beta1/proto/image_annotator_pb2_grpc.py b/google/cloud/vision_v1p1beta1/proto/image_annotator_pb2_grpc.py deleted file mode 100644 index ff536f98..00000000 --- a/google/cloud/vision_v1p1beta1/proto/image_annotator_pb2_grpc.py +++ /dev/null @@ -1,89 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.vision_v1p1beta1.proto import ( - image_annotator_pb2 as google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_image__annotator__pb2, -) - - -class ImageAnnotatorStub(object): - """Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.BatchAnnotateImages = channel.unary_unary( - "/google.cloud.vision.v1p1beta1.ImageAnnotator/BatchAnnotateImages", - request_serializer=google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesResponse.FromString, - ) - - -class ImageAnnotatorServicer(object): - """Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - def BatchAnnotateImages(self, request, context): - """Run image detection and annotation for a batch of images. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_ImageAnnotatorServicer_to_server(servicer, server): - rpc_method_handlers = { - "BatchAnnotateImages": grpc.unary_unary_rpc_method_handler( - servicer.BatchAnnotateImages, - request_deserializer=google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesResponse.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.vision.v1p1beta1.ImageAnnotator", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class ImageAnnotator(object): - """Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - @staticmethod - def BatchAnnotateImages( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p1beta1.ImageAnnotator/BatchAnnotateImages", - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/vision_v1p1beta1/proto/product_search.proto b/google/cloud/vision_v1p1beta1/proto/product_search.proto deleted file mode 100644 index 85e4e078..00000000 --- a/google/cloud/vision_v1p1beta1/proto/product_search.proto +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2018 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package google.cloud.vision.v1p3beta1; - -import "google/api/annotations.proto"; -import "google/cloud/vision/v1p3beta1/geometry.proto"; -import "google/cloud/vision/v1p3beta1/product_search_service.proto"; -import "google/protobuf/timestamp.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p3beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "ProductSearchProto"; -option java_package = "com.google.cloud.vision.v1p3beta1"; - - -// Parameters for a product search request. -message ProductSearchParams { - // The resource name of the catalog to search. - // - // Format is: `productSearch/catalogs/CATALOG_NAME`. - string catalog_name = 1; - - // The category to search in. - // Optional. It is inferred by the system if it is not specified. - // [Deprecated] Use `product_category`. - ProductSearchCategory category = 2; - - // The product category to search in. - // Optional. It is inferred by the system if it is not specified. - // Supported values are `bag`, `shoe`, `sunglasses`, `dress`, `outerwear`, - // `skirt`, `top`, `shorts`, and `pants`. - string product_category = 5; - - // The bounding polygon around the area of interest in the image. - // Optional. If it is not specified, system discretion will be applied. - // [Deprecated] Use `bounding_poly`. - NormalizedBoundingPoly normalized_bounding_poly = 3; - - // The bounding polygon around the area of interest in the image. - // Optional. If it is not specified, system discretion will be applied. - BoundingPoly bounding_poly = 9; - - // Specifies the verbosity of the product search results. - // Optional. Defaults to `BASIC`. - ProductSearchResultsView view = 4; - - // The resource name of a [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] to be searched for similar images. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`. - string product_set = 6; - - // The list of product categories to search in. Currently, we only consider - // the first category, and either "homegoods" or "apparel" should be - // specified. - repeated string product_categories = 7; - - // The filtering expression. This can be used to restrict search results based - // on Product labels. We currently support an AND of OR of key-value - // expressions, where each expression within an OR must have the same key. - // - // For example, "(color = red OR color = blue) AND brand = Google" is - // acceptable, but not "(color = red OR brand = Google)" or "color: red". - string filter = 8; -} - -// Results for a product search request. -message ProductSearchResults { - // Information about a product. - message ProductInfo { - // Product ID. - string product_id = 1; - - // The URI of the image which matched the query image. - // - // This field is returned only if `view` is set to `FULL` in - // the request. - string image_uri = 2; - - // A confidence level on the match, ranging from 0 (no confidence) to - // 1 (full confidence). - // - // This field is returned only if `view` is set to `FULL` in - // the request. - float score = 3; - } - - // Information about a product. - message Result { - // The Product. - Product product = 1; - - // A confidence level on the match, ranging from 0 (no confidence) to - // 1 (full confidence). - // - // This field is returned only if `view` is set to `FULL` in - // the request. - float score = 2; - - // The resource name of the image from the product that is the closest match - // to the query. - string image = 3; - } - - // Product category. - // [Deprecated] Use `product_category`. - ProductSearchCategory category = 1; - - // Product category. - // Supported values are `bag` and `shoe`. - // [Deprecated] `product_category` is provided in each Product. - string product_category = 4; - - // Timestamp of the index which provided these results. Changes made after - // this time are not reflected in the current results. - google.protobuf.Timestamp index_time = 2; - - // List of detected products. - repeated ProductInfo products = 3; - - // List of results, one for each product match. - repeated Result results = 5; -} - -// Supported product search categories. -enum ProductSearchCategory { - // Default value used when a category is not specified. - PRODUCT_SEARCH_CATEGORY_UNSPECIFIED = 0; - - // Shoes category. - SHOES = 1; - - // Bags category. - BAGS = 2; -} - -// Specifies the fields to include in product search results. -enum ProductSearchResultsView { - // Product search results contain only `product_category` and `product_id`. - // Default value. - BASIC = 0; - - // Product search results contain `product_category`, `product_id`, - // `image_uri`, and `score`. - FULL = 1; -} diff --git a/google/cloud/vision_v1p1beta1/proto/product_search_service.proto b/google/cloud/vision_v1p1beta1/proto/product_search_service.proto deleted file mode 100644 index 90388e36..00000000 --- a/google/cloud/vision_v1p1beta1/proto/product_search_service.proto +++ /dev/null @@ -1,825 +0,0 @@ -// Copyright 2018 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package google.cloud.vision.v1p3beta1; - -import "google/api/annotations.proto"; -import "google/cloud/vision/v1p3beta1/geometry.proto"; -import "google/longrunning/operations.proto"; -import "google/protobuf/empty.proto"; -import "google/protobuf/field_mask.proto"; -import "google/protobuf/timestamp.proto"; -import "google/rpc/status.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p3beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "ProductSearchServiceProto"; -option java_package = "com.google.cloud.vision.v1p3beta1"; - - -// Manages Products and ProductSets of reference images for use in product -// search. It uses the following resource model: -// -// - The API has a collection of [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, named -// `projects/*/locations/*/productSets/*`, which acts as a way to put different -// products into groups to limit identification. -// -// In parallel, -// -// - The API has a collection of [Product][google.cloud.vision.v1p3beta1.Product] resources, named -// `projects/*/locations/*/products/*` -// -// - Each [Product][google.cloud.vision.v1p3beta1.Product] has a collection of [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] resources, named -// `projects/*/locations/*/products/*/referenceImages/*` -service ProductSearch { - // Creates and returns a new ProductSet resource. - // - // Possible errors: - // - // * Returns INVALID_ARGUMENT if display_name is missing, or is longer than - // 4096 characters. - rpc CreateProductSet(CreateProductSetRequest) returns (ProductSet) { - option (google.api.http) = { - post: "/v1p3beta1/{parent=projects/*/locations/*}/productSets" - body: "product_set" - }; - } - - // Lists ProductSets in an unspecified order. - // - // Possible errors: - // - // * Returns INVALID_ARGUMENT if page_size is greater than 100, or less - // than 1. - rpc ListProductSets(ListProductSetsRequest) returns (ListProductSetsResponse) { - option (google.api.http) = { - get: "/v1p3beta1/{parent=projects/*/locations/*}/productSets" - }; - } - - // Gets information associated with a ProductSet. - // - // Possible errors: - // - // * Returns NOT_FOUND if the ProductSet does not exist. - rpc GetProductSet(GetProductSetRequest) returns (ProductSet) { - option (google.api.http) = { - get: "/v1p3beta1/{name=projects/*/locations/*/productSets/*}" - }; - } - - // Makes changes to a ProductSet resource. - // Only display_name can be updated currently. - // - // Possible errors: - // - // * Returns NOT_FOUND if the ProductSet does not exist. - // * Returns INVALID_ARGUMENT if display_name is present in update_mask but - // missing from the request or longer than 4096 characters. - rpc UpdateProductSet(UpdateProductSetRequest) returns (ProductSet) { - option (google.api.http) = { - patch: "/v1p3beta1/{product_set.name=projects/*/locations/*/productSets/*}" - body: "product_set" - }; - } - - // Permanently deletes a ProductSet. All Products and ReferenceImages in the - // ProductSet will be deleted. - // - // The actual image files are not deleted from Google Cloud Storage. - // - // Possible errors: - // - // * Returns NOT_FOUND if the ProductSet does not exist. - rpc DeleteProductSet(DeleteProductSetRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v1p3beta1/{name=projects/*/locations/*/productSets/*}" - }; - } - - // Creates and returns a new product resource. - // - // Possible errors: - // - // * Returns INVALID_ARGUMENT if display_name is missing or longer than 4096 - // characters. - // * Returns INVALID_ARGUMENT if description is longer than 4096 characters. - // * Returns INVALID_ARGUMENT if product_category is missing or invalid. - rpc CreateProduct(CreateProductRequest) returns (Product) { - option (google.api.http) = { - post: "/v1p3beta1/{parent=projects/*/locations/*}/products" - body: "product" - }; - } - - // Lists products in an unspecified order. - // - // Possible errors: - // - // * Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1. - rpc ListProducts(ListProductsRequest) returns (ListProductsResponse) { - option (google.api.http) = { - get: "/v1p3beta1/{parent=projects/*/locations/*}/products" - }; - } - - // Gets information associated with a Product. - // - // Possible errors: - // - // * Returns NOT_FOUND if the Product does not exist. - rpc GetProduct(GetProductRequest) returns (Product) { - option (google.api.http) = { - get: "/v1p3beta1/{name=projects/*/locations/*/products/*}" - }; - } - - // Makes changes to a Product resource. - // Only display_name, description and labels can be updated right now. - // - // If labels are updated, the change will not be reflected in queries until - // the next index time. - // - // Possible errors: - // - // * Returns NOT_FOUND if the Product does not exist. - // * Returns INVALID_ARGUMENT if display_name is present in update_mask but is - // missing from the request or longer than 4096 characters. - // * Returns INVALID_ARGUMENT if description is present in update_mask but is - // longer than 4096 characters. - // * Returns INVALID_ARGUMENT if product_category is present in update_mask. - rpc UpdateProduct(UpdateProductRequest) returns (Product) { - option (google.api.http) = { - patch: "/v1p3beta1/{product.name=projects/*/locations/*/products/*}" - body: "product" - }; - } - - // Permanently deletes a product and its reference images. - // - // Metadata of the product and all its images will be deleted right away, but - // search queries against ProductSets containing the product may still work - // until all related caches are refreshed. - // - // Possible errors: - // - // * Returns NOT_FOUND if the product does not exist. - rpc DeleteProduct(DeleteProductRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v1p3beta1/{name=projects/*/locations/*/products/*}" - }; - } - - // Creates and returns a new ReferenceImage resource. - // - // The `bounding_poly` field is optional. If `bounding_poly` is not specified, - // the system will try to detect regions of interest in the image that are - // compatible with the product_category on the parent product. If it is - // specified, detection is ALWAYS skipped. The system converts polygons into - // non-rotated rectangles. - // - // Note that the pipeline will resize the image if the image resolution is too - // large to process (above 50MP). - // - // Possible errors: - // - // * Returns INVALID_ARGUMENT if the image_uri is missing or longer than 4096 - // characters. - // * Returns INVALID_ARGUMENT if the product does not exist. - // * Returns INVALID_ARGUMENT if bounding_poly is not provided, and nothing - // compatible with the parent product's product_category is detected. - // * Returns INVALID_ARGUMENT if bounding_poly contains more than 10 polygons. - rpc CreateReferenceImage(CreateReferenceImageRequest) returns (ReferenceImage) { - option (google.api.http) = { - post: "/v1p3beta1/{parent=projects/*/locations/*/products/*}/referenceImages" - body: "reference_image" - }; - } - - // Permanently deletes a reference image. - // - // The image metadata will be deleted right away, but search queries - // against ProductSets containing the image may still work until all related - // caches are refreshed. - // - // The actual image files are not deleted from Google Cloud Storage. - // - // Possible errors: - // - // * Returns NOT_FOUND if the reference image does not exist. - rpc DeleteReferenceImage(DeleteReferenceImageRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v1p3beta1/{name=projects/*/locations/*/products/*/referenceImages/*}" - }; - } - - // Lists reference images. - // - // Possible errors: - // - // * Returns NOT_FOUND if the parent product does not exist. - // * Returns INVALID_ARGUMENT if the page_size is greater than 100, or less - // than 1. - rpc ListReferenceImages(ListReferenceImagesRequest) returns (ListReferenceImagesResponse) { - option (google.api.http) = { - get: "/v1p3beta1/{parent=projects/*/locations/*/products/*}/referenceImages" - }; - } - - // Gets information associated with a ReferenceImage. - // - // Possible errors: - // - // * Returns NOT_FOUND if the specified image does not exist. - rpc GetReferenceImage(GetReferenceImageRequest) returns (ReferenceImage) { - option (google.api.http) = { - get: "/v1p3beta1/{name=projects/*/locations/*/products/*/referenceImages/*}" - }; - } - - // Adds a Product to the specified ProductSet. If the Product is already - // present, no change is made. - // - // One Product can be added to at most 100 ProductSets. - // - // Possible errors: - // - // * Returns NOT_FOUND if the Product or the ProductSet doesn't exist. - rpc AddProductToProductSet(AddProductToProductSetRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - post: "/v1p3beta1/{name=projects/*/locations/*/productSets/*}:addProduct" - body: "*" - }; - } - - // Removes a Product from the specified ProductSet. - // - // Possible errors: - // - // * Returns NOT_FOUND If the Product is not found under the ProductSet. - rpc RemoveProductFromProductSet(RemoveProductFromProductSetRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - post: "/v1p3beta1/{name=projects/*/locations/*/productSets/*}:removeProduct" - body: "*" - }; - } - - // Lists the Products in a ProductSet, in an unspecified order. If the - // ProductSet does not exist, the products field of the response will be - // empty. - // - // Possible errors: - // - // * Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1. - rpc ListProductsInProductSet(ListProductsInProductSetRequest) returns (ListProductsInProductSetResponse) { - option (google.api.http) = { - get: "/v1p3beta1/{name=projects/*/locations/*/productSets/*}/products" - }; - } - - // Asynchronous API that imports a list of reference images to specified - // product sets based on a list of image information. - // - // The [google.longrunning.Operation][google.longrunning.Operation] API can be used to keep track of the - // progress and results of the request. - // `Operation.metadata` contains `BatchOperationMetadata`. (progress) - // `Operation.response` contains `ImportProductSetsResponse`. (results) - // - // The input source of this method is a csv file on Google Cloud Storage. - // For the format of the csv file please see - // [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1p3beta1.ImportProductSetsGcsSource.csv_file_uri]. - rpc ImportProductSets(ImportProductSetsRequest) returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v1p3beta1/{parent=projects/*/locations/*}/productSets:import" - body: "*" - }; - } -} - -// A Product contains ReferenceImages. -message Product { - // A product label represented as a key-value pair. - message KeyValue { - // The key of the label attached to the product. Cannot be empty and cannot - // exceed 128 bytes. - string key = 1; - - // The value of the label attached to the product. Cannot be empty and - // cannot exceed 128 bytes. - string value = 2; - } - - // The resource name of the product. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`. - // - // This field is ignored when creating a product. - string name = 1; - - // The user-provided name for this Product. Must not be empty. Must be at most - // 4096 characters long. - string display_name = 2; - - // User-provided metadata to be stored with this product. Must be at most 4096 - // characters long. - string description = 3; - - // The category for the product identified by the reference image. This should - // be either "homegoods" or "apparel". - // - // This field is immutable. - string product_category = 4; - - // Key-value pairs that can be attached to a product. At query time, - // constraints can be specified based on the product_labels. - // - // Note that integer values can be provided as strings, e.g. "1199". Only - // strings with integer values can match a range-based restriction which is - // to be supported soon. - // - // Multiple values can be assigned to the same key. One product may have up to - // 100 product_labels. - repeated KeyValue product_labels = 5; -} - -// A ProductSet contains Products. A ProductSet can contain a maximum of 1 -// million reference images. If the limit is exceeded, periodic indexing will -// fail. -message ProductSet { - // The resource name of the ProductSet. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`. - // - // This field is ignored when creating a ProductSet. - string name = 1; - - // The user-provided name for this ProductSet. Must not be empty. Must be at - // most 4096 characters long. - string display_name = 2; - - // Output only. The time at which this ProductSet was last indexed. Query - // results will reflect all updates before this time. If this ProductSet has - // never been indexed, this field is 0. - // - // This field is ignored when creating a ProductSet. - google.protobuf.Timestamp index_time = 3; - - // Output only. If there was an error with indexing the product set, the field - // is populated. - // - // This field is ignored when creating a ProductSet. - google.rpc.Status index_error = 4; -} - -// A `ReferenceImage` represents a product image and its associated metadata, -// such as bounding boxes. -message ReferenceImage { - // The resource name of the reference image. - // - // Format is: - // - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`. - // - // This field is ignored when creating a reference image. - string name = 1; - - // The Google Cloud Storage URI of the reference image. - // - // The URI must start with `gs://`. - // - // Required. - string uri = 2; - - // Bounding polygons around the areas of interest in the reference image. - // Optional. If this field is empty, the system will try to detect regions of - // interest. At most 10 bounding polygons will be used. - // - // The provided shape is converted into a non-rotated rectangle. Once - // converted, the small edge of the rectangle must be greater than or equal - // to 300 pixels. The aspect ratio must be 1:4 or less (i.e. 1:3 is ok; 1:5 - // is not). - repeated BoundingPoly bounding_polys = 3; -} - -// Request message for the `CreateProduct` method. -message CreateProductRequest { - // The project in which the Product should be created. - // - // Format is - // `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1; - - // The product to create. - Product product = 2; - - // A user-supplied resource id for this Product. If set, the server will - // attempt to use this value as the resource id. If it is already in use, an - // error is returned with code ALREADY_EXISTS. Must be at most 128 characters - // long. It cannot contain the character `/`. - string product_id = 3; -} - -// Request message for the `ListProducts` method. -message ListProductsRequest { - // The project OR ProductSet from which Products should be listed. - // - // Format: - // `projects/PROJECT_ID/locations/LOC_ID` - string parent = 1; - - // The maximum number of items to return. Default 10, maximum 100. - int32 page_size = 2; - - // The next_page_token returned from a previous List request, if any. - string page_token = 3; -} - -// Response message for the `ListProducts` method. -message ListProductsResponse { - // List of products. - repeated Product products = 1; - - // Token to retrieve the next page of results, or empty if there are no more - // results in the list. - string next_page_token = 2; -} - -// Request message for the `GetProduct` method. -message GetProductRequest { - // Resource name of the Product to get. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID` - string name = 1; -} - -// Request message for the `UpdateProduct` method. -message UpdateProductRequest { - // The Product resource which replaces the one on the server. - // product.name is immutable. - Product product = 1; - - // The [FieldMask][google.protobuf.FieldMask] that specifies which fields - // to update. - // If update_mask isn't specified, all mutable fields are to be updated. - // Valid mask paths include `product_labels`, `display_name` and - // `description`. - google.protobuf.FieldMask update_mask = 2; -} - -// Request message for the `DeleteProduct` method. -message DeleteProductRequest { - // Resource name of product to delete. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID` - string name = 1; -} - -// Request message for the `CreateProductSet` method. -message CreateProductSetRequest { - // The project in which the ProductSet should be created. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1; - - // The ProductSet to create. - ProductSet product_set = 2; - - // A user-supplied resource id for this ProductSet. If set, the server will - // attempt to use this value as the resource id. If it is already in use, an - // error is returned with code ALREADY_EXISTS. Must be at most 128 characters - // long. It cannot contain the character `/`. - string product_set_id = 3; -} - -// Request message for the `ListProductSets` method. -message ListProductSetsRequest { - // The project from which ProductSets should be listed. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1; - - // The maximum number of items to return. Default 10, maximum 100. - int32 page_size = 2; - - // The next_page_token returned from a previous List request, if any. - string page_token = 3; -} - -// Response message for the `ListProductSets` method. -message ListProductSetsResponse { - // List of ProductSets. - repeated ProductSet product_sets = 1; - - // Token to retrieve the next page of results, or empty if there are no more - // results in the list. - string next_page_token = 2; -} - -// Request message for the `GetProductSet` method. -message GetProductSetRequest { - // Resource name of the ProductSet to get. - // - // Format is: - // `projects/PROJECT_ID/locations/LOG_ID/productSets/PRODUCT_SET_ID` - string name = 1; -} - -// Request message for the `UpdateProductSet` method. -message UpdateProductSetRequest { - // The ProductSet resource which replaces the one on the server. - ProductSet product_set = 1; - - // The [FieldMask][google.protobuf.FieldMask] that specifies which fields to - // update. - // If update_mask isn't specified, all mutable fields are to be updated. - // Valid mask path is `display_name`. - google.protobuf.FieldMask update_mask = 2; -} - -// Request message for the `DeleteProductSet` method. -message DeleteProductSetRequest { - // Resource name of the ProductSet to delete. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1; -} - -// Request message for the `CreateReferenceImage` method. -message CreateReferenceImageRequest { - // Resource name of the product in which to create the reference image. - // - // Format is - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`. - string parent = 1; - - // The reference image to create. - // If an image ID is specified, it is ignored. - ReferenceImage reference_image = 2; - - // A user-supplied resource id for the ReferenceImage to be added. If set, - // the server will attempt to use this value as the resource id. If it is - // already in use, an error is returned with code ALREADY_EXISTS. Must be at - // most 128 characters long. It cannot contain the character `/`. - string reference_image_id = 3; -} - -// Request message for the `ListReferenceImages` method. -message ListReferenceImagesRequest { - // Resource name of the product containing the reference images. - // - // Format is - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`. - string parent = 1; - - // The maximum number of items to return. Default 10, maximum 100. - int32 page_size = 2; - - // A token identifying a page of results to be returned. This is the value - // of `nextPageToken` returned in a previous reference image list request. - // - // Defaults to the first page if not specified. - string page_token = 3; -} - -// Response message for the `ListReferenceImages` method. -message ListReferenceImagesResponse { - // The list of reference images. - repeated ReferenceImage reference_images = 1; - - // The maximum number of items to return. Default 10, maximum 100. - int32 page_size = 2; - - // The next_page_token returned from a previous List request, if any. - string next_page_token = 3; -} - -// Request message for the `GetReferenceImage` method. -message GetReferenceImageRequest { - // The resource name of the ReferenceImage to get. - // - // Format is: - // - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`. - string name = 1; -} - -// Request message for the `DeleteReferenceImage` method. -message DeleteReferenceImageRequest { - // The resource name of the reference image to delete. - // - // Format is: - // - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID` - string name = 1; -} - -// Request message for the `AddProductToProductSet` method. -message AddProductToProductSetRequest { - // The resource name for the ProductSet to modify. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1; - - // The resource name for the Product to be added to this ProductSet. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID` - string product = 2; -} - -// Request message for the `RemoveProductFromProductSet` method. -message RemoveProductFromProductSetRequest { - // The resource name for the ProductSet to modify. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1; - - // The resource name for the Product to be removed from this ProductSet. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID` - string product = 2; -} - -// Request message for the `ListProductsInProductSet` method. -message ListProductsInProductSetRequest { - // The ProductSet resource for which to retrieve Products. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1; - - // The maximum number of items to return. Default 10, maximum 100. - int32 page_size = 2; - - // The next_page_token returned from a previous List request, if any. - string page_token = 3; -} - -// Response message for the `ListProductsInProductSet` method. -message ListProductsInProductSetResponse { - // The list of Products. - repeated Product products = 1; - - // Token to retrieve the next page of results, or empty if there are no more - // results in the list. - string next_page_token = 2; -} - -// The Google Cloud Storage location for a csv file which preserves a list of -// ImportProductSetRequests in each line. -message ImportProductSetsGcsSource { - // The Google Cloud Storage URI of the input csv file. - // - // The URI must start with gs:// - // - // The format of the input csv file should be one image per line. - // In each line, there are 6 columns. - // 1. image_uri - // 2, image_id - // 3. product_set_id - // 4. product_id - // 5, product_category - // 6, product_display_name - // 7, labels - // 8. bounding_poly - // - // Columns 1, 3, 4, and 5 are required, other columns are optional. A new - // ProductSet/Product with the same id will be created on the fly - // if the ProductSet/Product specified by product_set_id/product_id does not - // exist. - // - // The image_id field is optional but has to be unique if provided. If it is - // empty, we will automatically assign an unique id to the image. - // - // The product_display_name field is optional. If it is empty, a space (" ") - // is used as the place holder for the product display_name, which can - // be updated later through the realtime API. - // - // If the Product with product_id already exists, the fields - // product_display_name, product_category and labels are ignored. - // - // If a Product doesn't exist and needs to be created on the fly, the - // product_display_name field refers to [Product.display_name][google.cloud.vision.v1p3beta1.Product.display_name], the - // product_category field refers to [Product.product_category][google.cloud.vision.v1p3beta1.Product.product_category], and the - // labels field refers to [Product.labels][]. - // - // Labels (optional) should be a line containing a list of comma-separated - // key-value pairs, with the format - // "key_1=value_1,key_2=value_2,...,key_n=value_n". - // - // The bounding_poly (optional) field is used to identify one region of - // interest from the image in the same manner as CreateReferenceImage. If no - // bounding_poly is specified, the system will try to detect regions of - // interest automatically. - // - // Note that the pipeline will resize the image if the image resolution is too - // large to process (above 20MP). - // - // Also note that at most one bounding_poly is allowed per line. If the image - // contains multiple regions of interest, the csv should contain one line per - // region of interest. - // - // The bounding_poly column should contain an even number of comma-separated - // numbers, with the format "p1_x,p1_y,p2_x,p2_y,...,pn_x,pn_y". Nonnegative - // integers should be used for absolute bounding polygons, and float values - // in [0, 1] should be used for normalized bounding polygons. - string csv_file_uri = 1; -} - -// The input content for the `ImportProductSets` method. -message ImportProductSetsInputConfig { - // The source of the input. - oneof source { - // The Google Cloud Storage location for a csv file which preserves a list - // of ImportProductSetRequests in each line. - ImportProductSetsGcsSource gcs_source = 1; - } -} - -// Request message for the `ImportProductSets` method. -message ImportProductSetsRequest { - // The project in which the ProductSets should be imported. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1; - - // The input content for the list of requests. - ImportProductSetsInputConfig input_config = 2; -} - -// Response message for the `ImportProductSets` method. -// -// This message is returned by the -// [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] method in the returned -// [google.longrunning.Operation.response][google.longrunning.Operation.response] field. -message ImportProductSetsResponse { - // The list of reference_images that are imported successfully. - repeated ReferenceImage reference_images = 1; - - // The rpc status for each ImportProductSet request, including both successes - // and errors. - // - // The number of statuses here matches the number of lines in the csv file, - // and statuses[i] stores the success or failure status of processing the i-th - // line of the csv, starting from line 0. - repeated google.rpc.Status statuses = 2; -} - -// Metadata for the batch operations such as the current state. -// -// This is included in the `metadata` field of the `Operation` returned by the -// `GetOperation` call of the `google::longrunning::Operations` service. -message BatchOperationMetadata { - // Enumerates the possible states that the batch request can be in. - enum State { - // Invalid. - STATE_UNSPECIFIED = 0; - - // Request is actively being processed. - PROCESSING = 1; - - // The request is done and at least one item has been successfully - // processed. - SUCCESSFUL = 2; - - // The request is done and no item has been successfully processed. - FAILED = 3; - - // The request is done after the longrunning.Operations.CancelOperation has - // been called by the user. Any records that were processed before the - // cancel command are output as specified in the request. - CANCELLED = 4; - } - - // The current state of the batch operation. - State state = 1; - - // The time when the batch request was submitted to the server. - google.protobuf.Timestamp submit_time = 2; - - // The time when the batch request is finished and - // [google.longrunning.Operation.done][google.longrunning.Operation.done] is set to true. - google.protobuf.Timestamp end_time = 3; -} diff --git a/google/cloud/vision_v1p1beta1/proto/text_annotation_pb2.py b/google/cloud/vision_v1p1beta1/proto/text_annotation_pb2.py deleted file mode 100644 index 53a1d662..00000000 --- a/google/cloud/vision_v1p1beta1/proto/text_annotation_pb2.py +++ /dev/null @@ -1,1221 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p1beta1/proto/text_annotation.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.cloud.vision_v1p1beta1.proto import ( - geometry_pb2 as google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2, -) - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p1beta1/proto/text_annotation.proto", - package="google.cloud.vision.v1p1beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p1beta1B\023TextAnnotationProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p1beta1;vision\370\001\001", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n9google/cloud/vision_v1p1beta1/proto/text_annotation.proto\x12\x1dgoogle.cloud.vision.v1p1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x32google/cloud/vision_v1p1beta1/proto/geometry.proto"\xb2\x04\n\x0eTextAnnotation\x12\x32\n\x05pages\x18\x01 \x03(\x0b\x32#.google.cloud.vision.v1p1beta1.Page\x12\x0c\n\x04text\x18\x02 \x01(\t\x1a=\n\x10\x44\x65tectedLanguage\x12\x15\n\rlanguage_code\x18\x01 \x01(\t\x12\x12\n\nconfidence\x18\x02 \x01(\x02\x1a\xdc\x01\n\rDetectedBreak\x12S\n\x04type\x18\x01 \x01(\x0e\x32\x45.google.cloud.vision.v1p1beta1.TextAnnotation.DetectedBreak.BreakType\x12\x11\n\tis_prefix\x18\x02 \x01(\x08"c\n\tBreakType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\t\n\x05SPACE\x10\x01\x12\x0e\n\nSURE_SPACE\x10\x02\x12\x12\n\x0e\x45OL_SURE_SPACE\x10\x03\x12\n\n\x06HYPHEN\x10\x04\x12\x0e\n\nLINE_BREAK\x10\x05\x1a\xbf\x01\n\x0cTextProperty\x12Z\n\x12\x64\x65tected_languages\x18\x01 \x03(\x0b\x32>.google.cloud.vision.v1p1beta1.TextAnnotation.DetectedLanguage\x12S\n\x0e\x64\x65tected_break\x18\x02 \x01(\x0b\x32;.google.cloud.vision.v1p1beta1.TextAnnotation.DetectedBreak"\xbd\x01\n\x04Page\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p1beta1.TextAnnotation.TextProperty\x12\r\n\x05width\x18\x02 \x01(\x05\x12\x0e\n\x06height\x18\x03 \x01(\x05\x12\x34\n\x06\x62locks\x18\x04 \x03(\x0b\x32$.google.cloud.vision.v1p1beta1.Block\x12\x12\n\nconfidence\x18\x05 \x01(\x02"\x82\x03\n\x05\x42lock\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p1beta1.TextAnnotation.TextProperty\x12\x41\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p1beta1.BoundingPoly\x12<\n\nparagraphs\x18\x03 \x03(\x0b\x32(.google.cloud.vision.v1p1beta1.Paragraph\x12\x42\n\nblock_type\x18\x04 \x01(\x0e\x32..google.cloud.vision.v1p1beta1.Block.BlockType\x12\x12\n\nconfidence\x18\x05 \x01(\x02"R\n\tBlockType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x08\n\x04TEXT\x10\x01\x12\t\n\x05TABLE\x10\x02\x12\x0b\n\x07PICTURE\x10\x03\x12\t\n\x05RULER\x10\x04\x12\x0b\n\x07\x42\x41RCODE\x10\x05"\xe4\x01\n\tParagraph\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p1beta1.TextAnnotation.TextProperty\x12\x41\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p1beta1.BoundingPoly\x12\x32\n\x05words\x18\x03 \x03(\x0b\x32#.google.cloud.vision.v1p1beta1.Word\x12\x12\n\nconfidence\x18\x04 \x01(\x02"\xe3\x01\n\x04Word\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p1beta1.TextAnnotation.TextProperty\x12\x41\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p1beta1.BoundingPoly\x12\x36\n\x07symbols\x18\x03 \x03(\x0b\x32%.google.cloud.vision.v1p1beta1.Symbol\x12\x12\n\nconfidence\x18\x04 \x01(\x02"\xbb\x01\n\x06Symbol\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p1beta1.TextAnnotation.TextProperty\x12\x41\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p1beta1.BoundingPoly\x12\x0c\n\x04text\x18\x03 \x01(\t\x12\x12\n\nconfidence\x18\x04 \x01(\x02\x42\x82\x01\n!com.google.cloud.vision.v1p1beta1B\x13TextAnnotationProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p1beta1;vision\xf8\x01\x01\x62\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2.DESCRIPTOR, - ], -) - - -_TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE = _descriptor.EnumDescriptor( - name="BreakType", - full_name="google.cloud.vision.v1p1beta1.TextAnnotation.DetectedBreak.BreakType", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNKNOWN", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SPACE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SURE_SPACE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="EOL_SURE_SPACE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="HYPHEN", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LINE_BREAK", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=444, - serialized_end=543, -) -_sym_db.RegisterEnumDescriptor(_TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE) - -_BLOCK_BLOCKTYPE = _descriptor.EnumDescriptor( - name="BlockType", - full_name="google.cloud.vision.v1p1beta1.Block.BlockType", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNKNOWN", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="TEXT", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="TABLE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="PICTURE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RULER", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="BARCODE", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=1236, - serialized_end=1318, -) -_sym_db.RegisterEnumDescriptor(_BLOCK_BLOCKTYPE) - - -_TEXTANNOTATION_DETECTEDLANGUAGE = _descriptor.Descriptor( - name="DetectedLanguage", - full_name="google.cloud.vision.v1p1beta1.TextAnnotation.DetectedLanguage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="language_code", - full_name="google.cloud.vision.v1p1beta1.TextAnnotation.DetectedLanguage.language_code", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p1beta1.TextAnnotation.DetectedLanguage.confidence", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=259, - serialized_end=320, -) - -_TEXTANNOTATION_DETECTEDBREAK = _descriptor.Descriptor( - name="DetectedBreak", - full_name="google.cloud.vision.v1p1beta1.TextAnnotation.DetectedBreak", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="type", - full_name="google.cloud.vision.v1p1beta1.TextAnnotation.DetectedBreak.type", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="is_prefix", - full_name="google.cloud.vision.v1p1beta1.TextAnnotation.DetectedBreak.is_prefix", - index=1, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=323, - serialized_end=543, -) - -_TEXTANNOTATION_TEXTPROPERTY = _descriptor.Descriptor( - name="TextProperty", - full_name="google.cloud.vision.v1p1beta1.TextAnnotation.TextProperty", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="detected_languages", - full_name="google.cloud.vision.v1p1beta1.TextAnnotation.TextProperty.detected_languages", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="detected_break", - full_name="google.cloud.vision.v1p1beta1.TextAnnotation.TextProperty.detected_break", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=546, - serialized_end=737, -) - -_TEXTANNOTATION = _descriptor.Descriptor( - name="TextAnnotation", - full_name="google.cloud.vision.v1p1beta1.TextAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="pages", - full_name="google.cloud.vision.v1p1beta1.TextAnnotation.pages", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="text", - full_name="google.cloud.vision.v1p1beta1.TextAnnotation.text", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _TEXTANNOTATION_DETECTEDLANGUAGE, - _TEXTANNOTATION_DETECTEDBREAK, - _TEXTANNOTATION_TEXTPROPERTY, - ], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=175, - serialized_end=737, -) - - -_PAGE = _descriptor.Descriptor( - name="Page", - full_name="google.cloud.vision.v1p1beta1.Page", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p1beta1.Page.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="width", - full_name="google.cloud.vision.v1p1beta1.Page.width", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="height", - full_name="google.cloud.vision.v1p1beta1.Page.height", - index=2, - number=3, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="blocks", - full_name="google.cloud.vision.v1p1beta1.Page.blocks", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p1beta1.Page.confidence", - index=4, - number=5, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=740, - serialized_end=929, -) - - -_BLOCK = _descriptor.Descriptor( - name="Block", - full_name="google.cloud.vision.v1p1beta1.Block", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p1beta1.Block.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_box", - full_name="google.cloud.vision.v1p1beta1.Block.bounding_box", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="paragraphs", - full_name="google.cloud.vision.v1p1beta1.Block.paragraphs", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="block_type", - full_name="google.cloud.vision.v1p1beta1.Block.block_type", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p1beta1.Block.confidence", - index=4, - number=5, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_BLOCK_BLOCKTYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=932, - serialized_end=1318, -) - - -_PARAGRAPH = _descriptor.Descriptor( - name="Paragraph", - full_name="google.cloud.vision.v1p1beta1.Paragraph", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p1beta1.Paragraph.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_box", - full_name="google.cloud.vision.v1p1beta1.Paragraph.bounding_box", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="words", - full_name="google.cloud.vision.v1p1beta1.Paragraph.words", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p1beta1.Paragraph.confidence", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1321, - serialized_end=1549, -) - - -_WORD = _descriptor.Descriptor( - name="Word", - full_name="google.cloud.vision.v1p1beta1.Word", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p1beta1.Word.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_box", - full_name="google.cloud.vision.v1p1beta1.Word.bounding_box", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="symbols", - full_name="google.cloud.vision.v1p1beta1.Word.symbols", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p1beta1.Word.confidence", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1552, - serialized_end=1779, -) - - -_SYMBOL = _descriptor.Descriptor( - name="Symbol", - full_name="google.cloud.vision.v1p1beta1.Symbol", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p1beta1.Symbol.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_box", - full_name="google.cloud.vision.v1p1beta1.Symbol.bounding_box", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="text", - full_name="google.cloud.vision.v1p1beta1.Symbol.text", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p1beta1.Symbol.confidence", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1782, - serialized_end=1969, -) - -_TEXTANNOTATION_DETECTEDLANGUAGE.containing_type = _TEXTANNOTATION -_TEXTANNOTATION_DETECTEDBREAK.fields_by_name[ - "type" -].enum_type = _TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE -_TEXTANNOTATION_DETECTEDBREAK.containing_type = _TEXTANNOTATION -_TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE.containing_type = _TEXTANNOTATION_DETECTEDBREAK -_TEXTANNOTATION_TEXTPROPERTY.fields_by_name[ - "detected_languages" -].message_type = _TEXTANNOTATION_DETECTEDLANGUAGE -_TEXTANNOTATION_TEXTPROPERTY.fields_by_name[ - "detected_break" -].message_type = _TEXTANNOTATION_DETECTEDBREAK -_TEXTANNOTATION_TEXTPROPERTY.containing_type = _TEXTANNOTATION -_TEXTANNOTATION.fields_by_name["pages"].message_type = _PAGE -_PAGE.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_PAGE.fields_by_name["blocks"].message_type = _BLOCK -_BLOCK.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_BLOCK.fields_by_name[ - "bounding_box" -].message_type = ( - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_BLOCK.fields_by_name["paragraphs"].message_type = _PARAGRAPH -_BLOCK.fields_by_name["block_type"].enum_type = _BLOCK_BLOCKTYPE -_BLOCK_BLOCKTYPE.containing_type = _BLOCK -_PARAGRAPH.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_PARAGRAPH.fields_by_name[ - "bounding_box" -].message_type = ( - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_PARAGRAPH.fields_by_name["words"].message_type = _WORD -_WORD.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_WORD.fields_by_name[ - "bounding_box" -].message_type = ( - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_WORD.fields_by_name["symbols"].message_type = _SYMBOL -_SYMBOL.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_SYMBOL.fields_by_name[ - "bounding_box" -].message_type = ( - google_dot_cloud_dot_vision__v1p1beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -DESCRIPTOR.message_types_by_name["TextAnnotation"] = _TEXTANNOTATION -DESCRIPTOR.message_types_by_name["Page"] = _PAGE -DESCRIPTOR.message_types_by_name["Block"] = _BLOCK -DESCRIPTOR.message_types_by_name["Paragraph"] = _PARAGRAPH -DESCRIPTOR.message_types_by_name["Word"] = _WORD -DESCRIPTOR.message_types_by_name["Symbol"] = _SYMBOL -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -TextAnnotation = _reflection.GeneratedProtocolMessageType( - "TextAnnotation", - (_message.Message,), - { - "DetectedLanguage": _reflection.GeneratedProtocolMessageType( - "DetectedLanguage", - (_message.Message,), - { - "DESCRIPTOR": _TEXTANNOTATION_DETECTEDLANGUAGE, - "__module__": "google.cloud.vision_v1p1beta1.proto.text_annotation_pb2", - "__doc__": """Detected language for a structural component. - - Attributes: - language_code: - The BCP-47 language code, such as “en-US” or “sr-Latn”. For - more information, see http://www.unicode.org/reports/tr35/#Uni - code_locale_identifier. - confidence: - Confidence of detected language. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.TextAnnotation.DetectedLanguage) - }, - ), - "DetectedBreak": _reflection.GeneratedProtocolMessageType( - "DetectedBreak", - (_message.Message,), - { - "DESCRIPTOR": _TEXTANNOTATION_DETECTEDBREAK, - "__module__": "google.cloud.vision_v1p1beta1.proto.text_annotation_pb2", - "__doc__": """Detected start or end of a structural component. - - Attributes: - type: - Detected break type. - is_prefix: - True if break prepends the element. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.TextAnnotation.DetectedBreak) - }, - ), - "TextProperty": _reflection.GeneratedProtocolMessageType( - "TextProperty", - (_message.Message,), - { - "DESCRIPTOR": _TEXTANNOTATION_TEXTPROPERTY, - "__module__": "google.cloud.vision_v1p1beta1.proto.text_annotation_pb2", - "__doc__": """Additional information detected on the structural component. - - Attributes: - detected_languages: - A list of detected languages together with confidence. - detected_break: - Detected start or end of a text segment. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.TextAnnotation.TextProperty) - }, - ), - "DESCRIPTOR": _TEXTANNOTATION, - "__module__": "google.cloud.vision_v1p1beta1.proto.text_annotation_pb2", - "__doc__": """TextAnnotation contains a structured representation of OCR extracted - text. The hierarchy of an OCR extracted text structure is like this: - TextAnnotation -> Page -> Block -> Paragraph -> Word -> Symbol Each - structural component, starting from Page, may further have their own - properties. Properties describe detected languages, breaks etc.. - Please refer to the [TextAnnotation.TextProperty][google.cloud.vision. - v1p1beta1.TextAnnotation.TextProperty] message definition below for - more detail. - - Attributes: - pages: - List of pages detected by OCR. - text: - UTF-8 text detected on the pages. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.TextAnnotation) - }, -) -_sym_db.RegisterMessage(TextAnnotation) -_sym_db.RegisterMessage(TextAnnotation.DetectedLanguage) -_sym_db.RegisterMessage(TextAnnotation.DetectedBreak) -_sym_db.RegisterMessage(TextAnnotation.TextProperty) - -Page = _reflection.GeneratedProtocolMessageType( - "Page", - (_message.Message,), - { - "DESCRIPTOR": _PAGE, - "__module__": "google.cloud.vision_v1p1beta1.proto.text_annotation_pb2", - "__doc__": """Detected page from OCR. - - Attributes: - property: - Additional information detected on the page. - width: - Page width in pixels. - height: - Page height in pixels. - blocks: - List of blocks of text, images etc on this page. - confidence: - Confidence of the OCR results on the page. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.Page) - }, -) -_sym_db.RegisterMessage(Page) - -Block = _reflection.GeneratedProtocolMessageType( - "Block", - (_message.Message,), - { - "DESCRIPTOR": _BLOCK, - "__module__": "google.cloud.vision_v1p1beta1.proto.text_annotation_pb2", - "__doc__": """Logical element on the page. - - Attributes: - property: - Additional information detected for the block. - bounding_box: - The bounding box for the block. The vertices are in the order - of top-left, top-right, bottom-right, bottom-left. When a - rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: \* - when the text is horizontal it might look like: 0—-1 \| \| - 3—-2 \* when it’s rotated 180 degrees around the top-left - corner it becomes: 2—-3 \| \| 1—-0 and the vertice order will - still be (0, 1, 2, 3). - paragraphs: - List of paragraphs in this block (if this blocks is of type - text). - block_type: - Detected block type (text, image etc) for this block. - confidence: - Confidence of the OCR results on the block. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.Block) - }, -) -_sym_db.RegisterMessage(Block) - -Paragraph = _reflection.GeneratedProtocolMessageType( - "Paragraph", - (_message.Message,), - { - "DESCRIPTOR": _PARAGRAPH, - "__module__": "google.cloud.vision_v1p1beta1.proto.text_annotation_pb2", - "__doc__": """Structural unit of text representing a number of words in certain - order. - - Attributes: - property: - Additional information detected for the paragraph. - bounding_box: - The bounding box for the paragraph. The vertices are in the - order of top-left, top-right, bottom-right, bottom-left. When - a rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: \* - when the text is horizontal it might look like: 0—-1 \| \| - 3—-2 \* when it’s rotated 180 degrees around the top-left - corner it becomes: 2—-3 \| \| 1—-0 and the vertice order will - still be (0, 1, 2, 3). - words: - List of words in this paragraph. - confidence: - Confidence of the OCR results for the paragraph. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.Paragraph) - }, -) -_sym_db.RegisterMessage(Paragraph) - -Word = _reflection.GeneratedProtocolMessageType( - "Word", - (_message.Message,), - { - "DESCRIPTOR": _WORD, - "__module__": "google.cloud.vision_v1p1beta1.proto.text_annotation_pb2", - "__doc__": """A word representation. - - Attributes: - property: - Additional information detected for the word. - bounding_box: - The bounding box for the word. The vertices are in the order - of top-left, top-right, bottom-right, bottom-left. When a - rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: \* - when the text is horizontal it might look like: 0—-1 \| \| - 3—-2 \* when it’s rotated 180 degrees around the top-left - corner it becomes: 2—-3 \| \| 1—-0 and the vertice order will - still be (0, 1, 2, 3). - symbols: - List of symbols in the word. The order of the symbols follows - the natural reading order. - confidence: - Confidence of the OCR results for the word. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.Word) - }, -) -_sym_db.RegisterMessage(Word) - -Symbol = _reflection.GeneratedProtocolMessageType( - "Symbol", - (_message.Message,), - { - "DESCRIPTOR": _SYMBOL, - "__module__": "google.cloud.vision_v1p1beta1.proto.text_annotation_pb2", - "__doc__": """A single symbol representation. - - Attributes: - property: - Additional information detected for the symbol. - bounding_box: - The bounding box for the symbol. The vertices are in the order - of top-left, top-right, bottom-right, bottom-left. When a - rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: \* - when the text is horizontal it might look like: 0—-1 \| \| - 3—-2 \* when it’s rotated 180 degrees around the top-left - corner it becomes: 2—-3 \| \| 1—-0 and the vertice order will - still be (0, 1, 2, 3). - text: - The actual UTF-8 representation of the symbol. - confidence: - Confidence of the OCR results for the symbol. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.Symbol) - }, -) -_sym_db.RegisterMessage(Symbol) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p1beta1/proto/text_annotation_pb2_grpc.py b/google/cloud/vision_v1p1beta1/proto/text_annotation_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/vision_v1p1beta1/proto/text_annotation_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/vision_v1p1beta1/proto/web_detection_pb2.py b/google/cloud/vision_v1p1beta1/proto/web_detection_pb2.py deleted file mode 100644 index 20f18fe0..00000000 --- a/google/cloud/vision_v1p1beta1/proto/web_detection_pb2.py +++ /dev/null @@ -1,628 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p1beta1/proto/web_detection.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p1beta1/proto/web_detection.proto", - package="google.cloud.vision.v1p1beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p1beta1B\021WebDetectionProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p1beta1;vision\370\001\001", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n7google/cloud/vision_v1p1beta1/proto/web_detection.proto\x12\x1dgoogle.cloud.vision.v1p1beta1\x1a\x1cgoogle/api/annotations.proto"\x8c\x07\n\x0cWebDetection\x12K\n\x0cweb_entities\x18\x01 \x03(\x0b\x32\x35.google.cloud.vision.v1p1beta1.WebDetection.WebEntity\x12R\n\x14\x66ull_matching_images\x18\x02 \x03(\x0b\x32\x34.google.cloud.vision.v1p1beta1.WebDetection.WebImage\x12U\n\x17partial_matching_images\x18\x03 \x03(\x0b\x32\x34.google.cloud.vision.v1p1beta1.WebDetection.WebImage\x12W\n\x1apages_with_matching_images\x18\x04 \x03(\x0b\x32\x33.google.cloud.vision.v1p1beta1.WebDetection.WebPage\x12U\n\x17visually_similar_images\x18\x06 \x03(\x0b\x32\x34.google.cloud.vision.v1p1beta1.WebDetection.WebImage\x12O\n\x11\x62\x65st_guess_labels\x18\x08 \x03(\x0b\x32\x34.google.cloud.vision.v1p1beta1.WebDetection.WebLabel\x1a\x42\n\tWebEntity\x12\x11\n\tentity_id\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\x1a&\n\x08WebImage\x12\x0b\n\x03url\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x1a\xe4\x01\n\x07WebPage\x12\x0b\n\x03url\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x12\n\npage_title\x18\x03 \x01(\t\x12R\n\x14\x66ull_matching_images\x18\x04 \x03(\x0b\x32\x34.google.cloud.vision.v1p1beta1.WebDetection.WebImage\x12U\n\x17partial_matching_images\x18\x05 \x03(\x0b\x32\x34.google.cloud.vision.v1p1beta1.WebDetection.WebImage\x1a\x30\n\x08WebLabel\x12\r\n\x05label\x18\x01 \x01(\t\x12\x15\n\rlanguage_code\x18\x02 \x01(\tB\x80\x01\n!com.google.cloud.vision.v1p1beta1B\x11WebDetectionProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p1beta1;vision\xf8\x01\x01\x62\x06proto3', - dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,], -) - - -_WEBDETECTION_WEBENTITY = _descriptor.Descriptor( - name="WebEntity", - full_name="google.cloud.vision.v1p1beta1.WebDetection.WebEntity", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="entity_id", - full_name="google.cloud.vision.v1p1beta1.WebDetection.WebEntity.entity_id", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p1beta1.WebDetection.WebEntity.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.vision.v1p1beta1.WebDetection.WebEntity.description", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=642, - serialized_end=708, -) - -_WEBDETECTION_WEBIMAGE = _descriptor.Descriptor( - name="WebImage", - full_name="google.cloud.vision.v1p1beta1.WebDetection.WebImage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="url", - full_name="google.cloud.vision.v1p1beta1.WebDetection.WebImage.url", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p1beta1.WebDetection.WebImage.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=710, - serialized_end=748, -) - -_WEBDETECTION_WEBPAGE = _descriptor.Descriptor( - name="WebPage", - full_name="google.cloud.vision.v1p1beta1.WebDetection.WebPage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="url", - full_name="google.cloud.vision.v1p1beta1.WebDetection.WebPage.url", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p1beta1.WebDetection.WebPage.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_title", - full_name="google.cloud.vision.v1p1beta1.WebDetection.WebPage.page_title", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="full_matching_images", - full_name="google.cloud.vision.v1p1beta1.WebDetection.WebPage.full_matching_images", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="partial_matching_images", - full_name="google.cloud.vision.v1p1beta1.WebDetection.WebPage.partial_matching_images", - index=4, - number=5, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=751, - serialized_end=979, -) - -_WEBDETECTION_WEBLABEL = _descriptor.Descriptor( - name="WebLabel", - full_name="google.cloud.vision.v1p1beta1.WebDetection.WebLabel", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="label", - full_name="google.cloud.vision.v1p1beta1.WebDetection.WebLabel.label", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="language_code", - full_name="google.cloud.vision.v1p1beta1.WebDetection.WebLabel.language_code", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=981, - serialized_end=1029, -) - -_WEBDETECTION = _descriptor.Descriptor( - name="WebDetection", - full_name="google.cloud.vision.v1p1beta1.WebDetection", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="web_entities", - full_name="google.cloud.vision.v1p1beta1.WebDetection.web_entities", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="full_matching_images", - full_name="google.cloud.vision.v1p1beta1.WebDetection.full_matching_images", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="partial_matching_images", - full_name="google.cloud.vision.v1p1beta1.WebDetection.partial_matching_images", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="pages_with_matching_images", - full_name="google.cloud.vision.v1p1beta1.WebDetection.pages_with_matching_images", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="visually_similar_images", - full_name="google.cloud.vision.v1p1beta1.WebDetection.visually_similar_images", - index=4, - number=6, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="best_guess_labels", - full_name="google.cloud.vision.v1p1beta1.WebDetection.best_guess_labels", - index=5, - number=8, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _WEBDETECTION_WEBENTITY, - _WEBDETECTION_WEBIMAGE, - _WEBDETECTION_WEBPAGE, - _WEBDETECTION_WEBLABEL, - ], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=121, - serialized_end=1029, -) - -_WEBDETECTION_WEBENTITY.containing_type = _WEBDETECTION -_WEBDETECTION_WEBIMAGE.containing_type = _WEBDETECTION -_WEBDETECTION_WEBPAGE.fields_by_name[ - "full_matching_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION_WEBPAGE.fields_by_name[ - "partial_matching_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION_WEBPAGE.containing_type = _WEBDETECTION -_WEBDETECTION_WEBLABEL.containing_type = _WEBDETECTION -_WEBDETECTION.fields_by_name["web_entities"].message_type = _WEBDETECTION_WEBENTITY -_WEBDETECTION.fields_by_name[ - "full_matching_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION.fields_by_name[ - "partial_matching_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION.fields_by_name[ - "pages_with_matching_images" -].message_type = _WEBDETECTION_WEBPAGE -_WEBDETECTION.fields_by_name[ - "visually_similar_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION.fields_by_name["best_guess_labels"].message_type = _WEBDETECTION_WEBLABEL -DESCRIPTOR.message_types_by_name["WebDetection"] = _WEBDETECTION -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -WebDetection = _reflection.GeneratedProtocolMessageType( - "WebDetection", - (_message.Message,), - { - "WebEntity": _reflection.GeneratedProtocolMessageType( - "WebEntity", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTION_WEBENTITY, - "__module__": "google.cloud.vision_v1p1beta1.proto.web_detection_pb2", - "__doc__": """Entity deduced from similar images on the Internet. - - Attributes: - entity_id: - Opaque entity ID. - score: - Overall relevancy score for the entity. Not normalized and not - comparable across different image queries. - description: - Canonical description of the entity, in English. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.WebDetection.WebEntity) - }, - ), - "WebImage": _reflection.GeneratedProtocolMessageType( - "WebImage", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTION_WEBIMAGE, - "__module__": "google.cloud.vision_v1p1beta1.proto.web_detection_pb2", - "__doc__": """Metadata for online images. - - Attributes: - url: - The result image URL. - score: - (Deprecated) Overall relevancy score for the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.WebDetection.WebImage) - }, - ), - "WebPage": _reflection.GeneratedProtocolMessageType( - "WebPage", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTION_WEBPAGE, - "__module__": "google.cloud.vision_v1p1beta1.proto.web_detection_pb2", - "__doc__": """Metadata for web pages. - - Attributes: - url: - The result web page URL. - score: - (Deprecated) Overall relevancy score for the web page. - page_title: - Title for the web page, may contain HTML markups. - full_matching_images: - Fully matching images on the page. Can include resized copies - of the query image. - partial_matching_images: - Partial matching images on the page. Those images are similar - enough to share some key-point features. For example an - original image will likely have partial matching for its - crops. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.WebDetection.WebPage) - }, - ), - "WebLabel": _reflection.GeneratedProtocolMessageType( - "WebLabel", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTION_WEBLABEL, - "__module__": "google.cloud.vision_v1p1beta1.proto.web_detection_pb2", - "__doc__": """Label to provide extra metadata for the web detection. - - Attributes: - label: - Label for extra metadata. - language_code: - The BCP-47 language code for ``label``, such as “en-US” or - “sr-Latn”. For more information, see http://www.unicode.org/re - ports/tr35/#Unicode_locale_identifier. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.WebDetection.WebLabel) - }, - ), - "DESCRIPTOR": _WEBDETECTION, - "__module__": "google.cloud.vision_v1p1beta1.proto.web_detection_pb2", - "__doc__": """Relevant information for the image from the Internet. - - Attributes: - web_entities: - Deduced entities from similar images on the Internet. - full_matching_images: - Fully matching images from the Internet. Can include resized - copies of the query image. - partial_matching_images: - Partial matching images from the Internet. Those images are - similar enough to share some key-point features. For example - an original image will likely have partial matching for its - crops. - pages_with_matching_images: - Web pages containing the matching images from the Internet. - visually_similar_images: - The visually similar image results. - best_guess_labels: - Best guess text labels for the request image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p1beta1.WebDetection) - }, -) -_sym_db.RegisterMessage(WebDetection) -_sym_db.RegisterMessage(WebDetection.WebEntity) -_sym_db.RegisterMessage(WebDetection.WebImage) -_sym_db.RegisterMessage(WebDetection.WebPage) -_sym_db.RegisterMessage(WebDetection.WebLabel) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p1beta1/proto/web_detection_pb2_grpc.py b/google/cloud/vision_v1p1beta1/proto/web_detection_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/vision_v1p1beta1/proto/web_detection_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/vision_v1p1beta1/py.typed b/google/cloud/vision_v1p1beta1/py.typed new file mode 100644 index 00000000..8cb07491 --- /dev/null +++ b/google/cloud/vision_v1p1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-vision package uses inline types. diff --git a/google/__init__.py b/google/cloud/vision_v1p1beta1/services/__init__.py similarity index 66% rename from google/__init__.py rename to google/cloud/vision_v1p1beta1/services/__init__.py index dd3a9f48..42ffdf2b 100644 --- a/google/__init__.py +++ b/google/cloud/vision_v1p1beta1/services/__init__.py @@ -1,22 +1,16 @@ -# Copyright 2018 Google LLC +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -try: - import pkg_resources - - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil - - __path__ = pkgutil.extend_path(__path__, __name__) +# diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/__init__.py b/google/cloud/vision_v1p1beta1/services/image_annotator/__init__.py new file mode 100644 index 00000000..2b601881 --- /dev/null +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import ImageAnnotatorClient +from .async_client import ImageAnnotatorAsyncClient + +__all__ = ( + "ImageAnnotatorClient", + "ImageAnnotatorAsyncClient", +) diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/async_client.py b/google/cloud/vision_v1p1beta1/services/image_annotator/async_client.py new file mode 100644 index 00000000..0ee7c093 --- /dev/null +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/async_client.py @@ -0,0 +1,188 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.vision_v1p1beta1.types import image_annotator + +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport +from .client import ImageAnnotatorClient + + +class ImageAnnotatorAsyncClient: + """Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + """ + + _client: ImageAnnotatorClient + + DEFAULT_ENDPOINT = ImageAnnotatorClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + + from_service_account_file = ImageAnnotatorClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(ImageAnnotatorClient).get_transport_class, type(ImageAnnotatorClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, ImageAnnotatorTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the image annotator client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ImageAnnotatorTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = ImageAnnotatorClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def batch_annotate_images( + self, + request: image_annotator.BatchAnnotateImagesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateImageRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: + r"""Run image detection and annotation for a batch of + images. + + Args: + request (:class:`~.image_annotator.BatchAnnotateImagesRequest`): + The request object. Multiple image annotation requests + are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AnnotateImageRequest]`): + Required. Individual image annotation + requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.image_annotator.BatchAnnotateImagesResponse: + Response to a batch image annotation + request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([requests]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = image_annotator.BatchAnnotateImagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_annotate_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ImageAnnotatorAsyncClient",) diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/client.py b/google/cloud/vision_v1p1beta1/services/image_annotator/client.py new file mode 100644 index 00000000..c4b2547c --- /dev/null +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/client.py @@ -0,0 +1,333 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.vision_v1p1beta1.types import image_annotator + +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ImageAnnotatorGrpcTransport +from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport + + +class ImageAnnotatorClientMeta(type): + """Metaclass for the ImageAnnotator client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[ImageAnnotatorTransport]] + _transport_registry["grpc"] = ImageAnnotatorGrpcTransport + _transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[ImageAnnotatorTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ImageAnnotatorClient(metaclass=ImageAnnotatorClientMeta): + """Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "vision.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + def __init__( + self, + *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, ImageAnnotatorTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the image annotator client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ImageAnnotatorTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ImageAnnotatorTransport): + # transport is a ImageAnnotatorTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def batch_annotate_images( + self, + request: image_annotator.BatchAnnotateImagesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateImageRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: + r"""Run image detection and annotation for a batch of + images. + + Args: + request (:class:`~.image_annotator.BatchAnnotateImagesRequest`): + The request object. Multiple image annotation requests + are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AnnotateImageRequest]`): + Required. Individual image annotation + requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.image_annotator.BatchAnnotateImagesResponse: + Response to a batch image annotation + request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([requests]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a image_annotator.BatchAnnotateImagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, image_annotator.BatchAnnotateImagesRequest): + request = image_annotator.BatchAnnotateImagesRequest(request) + if requests is not None: + for i in range(len(requests)): + requests[i] = image_annotator.AnnotateImageRequest(requests[i]) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_annotate_images] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ImageAnnotatorClient",) diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/__init__.py b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/__init__.py new file mode 100644 index 00000000..f2315e0d --- /dev/null +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import ImageAnnotatorTransport +from .grpc import ImageAnnotatorGrpcTransport +from .grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ImageAnnotatorTransport]] +_transport_registry["grpc"] = ImageAnnotatorGrpcTransport +_transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport + + +__all__ = ( + "ImageAnnotatorTransport", + "ImageAnnotatorGrpcTransport", + "ImageAnnotatorGrpcAsyncIOTransport", +) diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py new file mode 100644 index 00000000..9132791e --- /dev/null +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py @@ -0,0 +1,138 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.vision_v1p1beta1.types import image_annotator + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ImageAnnotatorTransport(abc.ABC): + """Abstract transport class for ImageAnnotator.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ) + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.batch_annotate_images: gapic_v1.method.wrap_method( + self.batch_annotate_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + @property + def batch_annotate_images( + self, + ) -> typing.Callable[ + [image_annotator.BatchAnnotateImagesRequest], + typing.Union[ + image_annotator.BatchAnnotateImagesResponse, + typing.Awaitable[image_annotator.BatchAnnotateImagesResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ("ImageAnnotatorTransport",) diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py new file mode 100644 index 00000000..f5047961 --- /dev/null +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py @@ -0,0 +1,266 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.vision_v1p1beta1.types import image_annotator + +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO + + +class ImageAnnotatorGrpcTransport(ImageAnnotatorTransport): + """gRPC backend transport for ImageAnnotator. + + Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def batch_annotate_images( + self, + ) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + image_annotator.BatchAnnotateImagesResponse, + ]: + r"""Return a callable for the batch annotate images method over gRPC. + + Run image detection and annotation for a batch of + images. + + Returns: + Callable[[~.BatchAnnotateImagesRequest], + ~.BatchAnnotateImagesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_annotate_images" not in self._stubs: + self._stubs["batch_annotate_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p1beta1.ImageAnnotator/BatchAnnotateImages", + request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, + response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, + ) + return self._stubs["batch_annotate_images"] + + +__all__ = ("ImageAnnotatorGrpcTransport",) diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc_asyncio.py b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc_asyncio.py new file mode 100644 index 00000000..a01b6b71 --- /dev/null +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc_asyncio.py @@ -0,0 +1,266 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.vision_v1p1beta1.types import image_annotator + +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .grpc import ImageAnnotatorGrpcTransport + + +class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): + """gRPC AsyncIO backend transport for ImageAnnotator. + + Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def batch_annotate_images( + self, + ) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + Awaitable[image_annotator.BatchAnnotateImagesResponse], + ]: + r"""Return a callable for the batch annotate images method over gRPC. + + Run image detection and annotation for a batch of + images. + + Returns: + Callable[[~.BatchAnnotateImagesRequest], + Awaitable[~.BatchAnnotateImagesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_annotate_images" not in self._stubs: + self._stubs["batch_annotate_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p1beta1.ImageAnnotator/BatchAnnotateImages", + request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, + response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, + ) + return self._stubs["batch_annotate_images"] + + +__all__ = ("ImageAnnotatorGrpcAsyncIOTransport",) diff --git a/google/cloud/vision_v1p1beta1/types.py b/google/cloud/vision_v1p1beta1/types.py deleted file mode 100644 index 0a9d2895..00000000 --- a/google/cloud/vision_v1p1beta1/types.py +++ /dev/null @@ -1,62 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.vision_v1p1beta1.proto import geometry_pb2 -from google.cloud.vision_v1p1beta1.proto import image_annotator_pb2 -from google.cloud.vision_v1p1beta1.proto import text_annotation_pb2 -from google.cloud.vision_v1p1beta1.proto import web_detection_pb2 -from google.protobuf import any_pb2 -from google.protobuf import wrappers_pb2 -from google.rpc import status_pb2 -from google.type import color_pb2 -from google.type import latlng_pb2 - - -_shared_modules = [ - any_pb2, - wrappers_pb2, - status_pb2, - color_pb2, - latlng_pb2, -] - -_local_modules = [ - geometry_pb2, - image_annotator_pb2, - text_annotation_pb2, - web_detection_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.vision_v1p1beta1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/vision_v1p1beta1/types/__init__.py b/google/cloud/vision_v1p1beta1/types/__init__.py new file mode 100644 index 00000000..3247d09c --- /dev/null +++ b/google/cloud/vision_v1p1beta1/types/__init__.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .geometry import ( + Vertex, + BoundingPoly, + Position, +) +from .text_annotation import ( + TextAnnotation, + Page, + Block, + Paragraph, + Word, + Symbol, +) +from .web_detection import WebDetection +from .image_annotator import ( + Feature, + ImageSource, + Image, + FaceAnnotation, + LocationInfo, + Property, + EntityAnnotation, + SafeSearchAnnotation, + LatLongRect, + ColorInfo, + DominantColorsAnnotation, + ImageProperties, + CropHint, + CropHintsAnnotation, + CropHintsParams, + WebDetectionParams, + ImageContext, + AnnotateImageRequest, + AnnotateImageResponse, + BatchAnnotateImagesRequest, + BatchAnnotateImagesResponse, +) + + +__all__ = ( + "Vertex", + "BoundingPoly", + "Position", + "TextAnnotation", + "Page", + "Block", + "Paragraph", + "Word", + "Symbol", + "WebDetection", + "Feature", + "ImageSource", + "Image", + "FaceAnnotation", + "LocationInfo", + "Property", + "EntityAnnotation", + "SafeSearchAnnotation", + "LatLongRect", + "ColorInfo", + "DominantColorsAnnotation", + "ImageProperties", + "CropHint", + "CropHintsAnnotation", + "CropHintsParams", + "WebDetectionParams", + "ImageContext", + "AnnotateImageRequest", + "AnnotateImageResponse", + "BatchAnnotateImagesRequest", + "BatchAnnotateImagesResponse", +) diff --git a/google/cloud/vision_v1p1beta1/types/geometry.py b/google/cloud/vision_v1p1beta1/types/geometry.py new file mode 100644 index 00000000..6dd62de3 --- /dev/null +++ b/google/cloud/vision_v1p1beta1/types/geometry.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p1beta1", + manifest={"Vertex", "BoundingPoly", "Position",}, +) + + +class Vertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the vertex coordinates are in the same scale as the + original image. + + Attributes: + x (int): + X coordinate. + y (int): + Y coordinate. + """ + + x = proto.Field(proto.INT32, number=1) + + y = proto.Field(proto.INT32, number=2) + + +class BoundingPoly(proto.Message): + r"""A bounding polygon for the detected image annotation. + + Attributes: + vertices (Sequence[~.geometry.Vertex]): + The bounding polygon vertices. + """ + + vertices = proto.RepeatedField(proto.MESSAGE, number=1, message=Vertex,) + + +class Position(proto.Message): + r"""A 3D position in the image, used primarily for Face detection + landmarks. A valid Position must have both x and y coordinates. + The position coordinates are in the same scale as the original + image. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate. + z (float): + Z coordinate (or depth). + """ + + x = proto.Field(proto.FLOAT, number=1) + + y = proto.Field(proto.FLOAT, number=2) + + z = proto.Field(proto.FLOAT, number=3) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p1beta1/types/image_annotator.py b/google/cloud/vision_v1p1beta1/types/image_annotator.py new file mode 100644 index 00000000..9ad8a626 --- /dev/null +++ b/google/cloud/vision_v1p1beta1/types/image_annotator.py @@ -0,0 +1,735 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.vision_v1p1beta1.types import geometry +from google.cloud.vision_v1p1beta1.types import text_annotation +from google.cloud.vision_v1p1beta1.types import web_detection as gcv_web_detection +from google.rpc import status_pb2 as status # type: ignore +from google.type import color_pb2 as gt_color # type: ignore +from google.type import latlng_pb2 as latlng # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p1beta1", + manifest={ + "Likelihood", + "Feature", + "ImageSource", + "Image", + "FaceAnnotation", + "LocationInfo", + "Property", + "EntityAnnotation", + "SafeSearchAnnotation", + "LatLongRect", + "ColorInfo", + "DominantColorsAnnotation", + "ImageProperties", + "CropHint", + "CropHintsAnnotation", + "CropHintsParams", + "WebDetectionParams", + "ImageContext", + "AnnotateImageRequest", + "AnnotateImageResponse", + "BatchAnnotateImagesRequest", + "BatchAnnotateImagesResponse", + }, +) + + +class Likelihood(proto.Enum): + r"""A bucketized representation of likelihood, which is intended + to give clients highly stable results across model upgrades. + """ + UNKNOWN = 0 + VERY_UNLIKELY = 1 + UNLIKELY = 2 + POSSIBLE = 3 + LIKELY = 4 + VERY_LIKELY = 5 + + +class Feature(proto.Message): + r"""Users describe the type of Google Cloud Vision API tasks to perform + over images by using *Feature*\ s. Each Feature indicates a type of + image detection task to perform. Features encode the Cloud Vision + API vertical to operate on and the number of top-scoring results to + return. + + Attributes: + type_ (~.image_annotator.Feature.Type): + The feature type. + max_results (int): + Maximum number of results of this type. + model (str): + Model to use for the feature. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + class Type(proto.Enum): + r"""Type of image feature.""" + TYPE_UNSPECIFIED = 0 + FACE_DETECTION = 1 + LANDMARK_DETECTION = 2 + LOGO_DETECTION = 3 + LABEL_DETECTION = 4 + TEXT_DETECTION = 5 + DOCUMENT_TEXT_DETECTION = 11 + SAFE_SEARCH_DETECTION = 6 + IMAGE_PROPERTIES = 7 + CROP_HINTS = 9 + WEB_DETECTION = 10 + + type_ = proto.Field(proto.ENUM, number=1, enum=Type,) + + max_results = proto.Field(proto.INT32, number=2) + + model = proto.Field(proto.STRING, number=3) + + +class ImageSource(proto.Message): + r"""External image source (Google Cloud Storage image location). + + Attributes: + gcs_image_uri (str): + NOTE: For new code ``image_uri`` below is preferred. Google + Cloud Storage image URI, which must be in the following + form: ``gs://bucket_name/object_name`` (for details, see + `Google Cloud Storage Request + URIs `__). + NOTE: Cloud Storage object versioning is not supported. + image_uri (str): + Image URI which supports: + + 1) Google Cloud Storage image URI, which must be in the + following form: ``gs://bucket_name/object_name`` (for + details, see `Google Cloud Storage Request + URIs `__). + NOTE: Cloud Storage object versioning is not supported. + 2) Publicly accessible image HTTP/HTTPS URL. This is + preferred over the legacy ``gcs_image_uri`` above. When + both ``gcs_image_uri`` and ``image_uri`` are specified, + ``image_uri`` takes precedence. + """ + + gcs_image_uri = proto.Field(proto.STRING, number=1) + + image_uri = proto.Field(proto.STRING, number=2) + + +class Image(proto.Message): + r"""Client image to perform Google Cloud Vision API tasks over. + + Attributes: + content (bytes): + Image content, represented as a stream of bytes. Note: as + with all ``bytes`` fields, protobuffers use a pure binary + representation, whereas JSON representations use base64. + source (~.image_annotator.ImageSource): + Google Cloud Storage image location. If both ``content`` and + ``source`` are provided for an image, ``content`` takes + precedence and is used to perform the image annotation + request. + """ + + content = proto.Field(proto.BYTES, number=1) + + source = proto.Field(proto.MESSAGE, number=2, message=ImageSource,) + + +class FaceAnnotation(proto.Message): + r"""A face annotation object contains the results of face + detection. + + Attributes: + bounding_poly (~.geometry.BoundingPoly): + The bounding polygon around the face. The coordinates of the + bounding box are in the original image's scale, as returned + in ``ImageParams``. The bounding box is computed to "frame" + the face in accordance with human expectations. It is based + on the landmarker results. Note that one or more x and/or y + coordinates may not be generated in the ``BoundingPoly`` + (the polygon will be unbounded) if only a partial face + appears in the image to be annotated. + fd_bounding_poly (~.geometry.BoundingPoly): + The ``fd_bounding_poly`` bounding polygon is tighter than + the ``boundingPoly``, and encloses only the skin part of the + face. Typically, it is used to eliminate the face from any + image analysis that detects the "amount of skin" visible in + an image. It is not based on the landmarker results, only on + the initial face detection, hence the fd (face detection) + prefix. + landmarks (Sequence[~.image_annotator.FaceAnnotation.Landmark]): + Detected face landmarks. + roll_angle (float): + Roll angle, which indicates the amount of + clockwise/anti-clockwise rotation of the face relative to + the image vertical about the axis perpendicular to the face. + Range [-180,180]. + pan_angle (float): + Yaw angle, which indicates the leftward/rightward angle that + the face is pointing relative to the vertical plane + perpendicular to the image. Range [-180,180]. + tilt_angle (float): + Pitch angle, which indicates the upwards/downwards angle + that the face is pointing relative to the image's horizontal + plane. Range [-180,180]. + detection_confidence (float): + Detection confidence. Range [0, 1]. + landmarking_confidence (float): + Face landmarking confidence. Range [0, 1]. + joy_likelihood (~.image_annotator.Likelihood): + Joy likelihood. + sorrow_likelihood (~.image_annotator.Likelihood): + Sorrow likelihood. + anger_likelihood (~.image_annotator.Likelihood): + Anger likelihood. + surprise_likelihood (~.image_annotator.Likelihood): + Surprise likelihood. + under_exposed_likelihood (~.image_annotator.Likelihood): + Under-exposed likelihood. + blurred_likelihood (~.image_annotator.Likelihood): + Blurred likelihood. + headwear_likelihood (~.image_annotator.Likelihood): + Headwear likelihood. + """ + + class Landmark(proto.Message): + r"""A face-specific landmark (for example, a face feature). + + Attributes: + type_ (~.image_annotator.FaceAnnotation.Landmark.Type): + Face landmark type. + position (~.geometry.Position): + Face landmark position. + """ + + class Type(proto.Enum): + r"""Face landmark (feature) type. Left and right are defined from the + vantage of the viewer of the image without considering mirror + projections typical of photos. So, ``LEFT_EYE``, typically, is the + person's right eye. + """ + UNKNOWN_LANDMARK = 0 + LEFT_EYE = 1 + RIGHT_EYE = 2 + LEFT_OF_LEFT_EYEBROW = 3 + RIGHT_OF_LEFT_EYEBROW = 4 + LEFT_OF_RIGHT_EYEBROW = 5 + RIGHT_OF_RIGHT_EYEBROW = 6 + MIDPOINT_BETWEEN_EYES = 7 + NOSE_TIP = 8 + UPPER_LIP = 9 + LOWER_LIP = 10 + MOUTH_LEFT = 11 + MOUTH_RIGHT = 12 + MOUTH_CENTER = 13 + NOSE_BOTTOM_RIGHT = 14 + NOSE_BOTTOM_LEFT = 15 + NOSE_BOTTOM_CENTER = 16 + LEFT_EYE_TOP_BOUNDARY = 17 + LEFT_EYE_RIGHT_CORNER = 18 + LEFT_EYE_BOTTOM_BOUNDARY = 19 + LEFT_EYE_LEFT_CORNER = 20 + RIGHT_EYE_TOP_BOUNDARY = 21 + RIGHT_EYE_RIGHT_CORNER = 22 + RIGHT_EYE_BOTTOM_BOUNDARY = 23 + RIGHT_EYE_LEFT_CORNER = 24 + LEFT_EYEBROW_UPPER_MIDPOINT = 25 + RIGHT_EYEBROW_UPPER_MIDPOINT = 26 + LEFT_EAR_TRAGION = 27 + RIGHT_EAR_TRAGION = 28 + LEFT_EYE_PUPIL = 29 + RIGHT_EYE_PUPIL = 30 + FOREHEAD_GLABELLA = 31 + CHIN_GNATHION = 32 + CHIN_LEFT_GONION = 33 + CHIN_RIGHT_GONION = 34 + + type_ = proto.Field(proto.ENUM, number=3, enum="FaceAnnotation.Landmark.Type",) + + position = proto.Field(proto.MESSAGE, number=4, message=geometry.Position,) + + bounding_poly = proto.Field(proto.MESSAGE, number=1, message=geometry.BoundingPoly,) + + fd_bounding_poly = proto.Field( + proto.MESSAGE, number=2, message=geometry.BoundingPoly, + ) + + landmarks = proto.RepeatedField(proto.MESSAGE, number=3, message=Landmark,) + + roll_angle = proto.Field(proto.FLOAT, number=4) + + pan_angle = proto.Field(proto.FLOAT, number=5) + + tilt_angle = proto.Field(proto.FLOAT, number=6) + + detection_confidence = proto.Field(proto.FLOAT, number=7) + + landmarking_confidence = proto.Field(proto.FLOAT, number=8) + + joy_likelihood = proto.Field(proto.ENUM, number=9, enum="Likelihood",) + + sorrow_likelihood = proto.Field(proto.ENUM, number=10, enum="Likelihood",) + + anger_likelihood = proto.Field(proto.ENUM, number=11, enum="Likelihood",) + + surprise_likelihood = proto.Field(proto.ENUM, number=12, enum="Likelihood",) + + under_exposed_likelihood = proto.Field(proto.ENUM, number=13, enum="Likelihood",) + + blurred_likelihood = proto.Field(proto.ENUM, number=14, enum="Likelihood",) + + headwear_likelihood = proto.Field(proto.ENUM, number=15, enum="Likelihood",) + + +class LocationInfo(proto.Message): + r"""Detected entity location information. + + Attributes: + lat_lng (~.latlng.LatLng): + lat/long location coordinates. + """ + + lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng.LatLng,) + + +class Property(proto.Message): + r"""A ``Property`` consists of a user-supplied name/value pair. + + Attributes: + name (str): + Name of the property. + value (str): + Value of the property. + uint64_value (int): + Value of numeric properties. + """ + + name = proto.Field(proto.STRING, number=1) + + value = proto.Field(proto.STRING, number=2) + + uint64_value = proto.Field(proto.UINT64, number=3) + + +class EntityAnnotation(proto.Message): + r"""Set of detected entity features. + + Attributes: + mid (str): + Opaque entity ID. Some IDs may be available in `Google + Knowledge Graph Search + API `__. + locale (str): + The language code for the locale in which the entity textual + ``description`` is expressed. + description (str): + Entity textual description, expressed in its ``locale`` + language. + score (float): + Overall score of the result. Range [0, 1]. + confidence (float): + The accuracy of the entity detection in an image. For + example, for an image in which the "Eiffel Tower" entity is + detected, this field represents the confidence that there is + a tower in the query image. Range [0, 1]. + topicality (float): + The relevancy of the ICA (Image Content Annotation) label to + the image. For example, the relevancy of "tower" is likely + higher to an image containing the detected "Eiffel Tower" + than to an image containing a detected distant towering + building, even though the confidence that there is a tower + in each image may be the same. Range [0, 1]. + bounding_poly (~.geometry.BoundingPoly): + Image region to which this entity belongs. Not produced for + ``LABEL_DETECTION`` features. + locations (Sequence[~.image_annotator.LocationInfo]): + The location information for the detected entity. Multiple + ``LocationInfo`` elements can be present because one + location may indicate the location of the scene in the + image, and another location may indicate the location of the + place where the image was taken. Location information is + usually present for landmarks. + properties (Sequence[~.image_annotator.Property]): + Some entities may have optional user-supplied ``Property`` + (name/value) fields, such a score or string that qualifies + the entity. + """ + + mid = proto.Field(proto.STRING, number=1) + + locale = proto.Field(proto.STRING, number=2) + + description = proto.Field(proto.STRING, number=3) + + score = proto.Field(proto.FLOAT, number=4) + + confidence = proto.Field(proto.FLOAT, number=5) + + topicality = proto.Field(proto.FLOAT, number=6) + + bounding_poly = proto.Field(proto.MESSAGE, number=7, message=geometry.BoundingPoly,) + + locations = proto.RepeatedField(proto.MESSAGE, number=8, message=LocationInfo,) + + properties = proto.RepeatedField(proto.MESSAGE, number=9, message=Property,) + + +class SafeSearchAnnotation(proto.Message): + r"""Set of features pertaining to the image, computed by computer + vision methods over safe-search verticals (for example, adult, + spoof, medical, violence). + + Attributes: + adult (~.image_annotator.Likelihood): + Represents the adult content likelihood for + the image. Adult content may contain elements + such as nudity, pornographic images or cartoons, + or sexual activities. + spoof (~.image_annotator.Likelihood): + Spoof likelihood. The likelihood that an + modification was made to the image's canonical + version to make it appear funny or offensive. + medical (~.image_annotator.Likelihood): + Likelihood that this is a medical image. + violence (~.image_annotator.Likelihood): + Likelihood that this image contains violent + content. + racy (~.image_annotator.Likelihood): + Likelihood that the request image contains + racy content. Racy content may include (but is + not limited to) skimpy or sheer clothing, + strategically covered nudity, lewd or + provocative poses, or close-ups of sensitive + body areas. + """ + + adult = proto.Field(proto.ENUM, number=1, enum="Likelihood",) + + spoof = proto.Field(proto.ENUM, number=2, enum="Likelihood",) + + medical = proto.Field(proto.ENUM, number=3, enum="Likelihood",) + + violence = proto.Field(proto.ENUM, number=4, enum="Likelihood",) + + racy = proto.Field(proto.ENUM, number=9, enum="Likelihood",) + + +class LatLongRect(proto.Message): + r"""Rectangle determined by min and max ``LatLng`` pairs. + + Attributes: + min_lat_lng (~.latlng.LatLng): + Min lat/long pair. + max_lat_lng (~.latlng.LatLng): + Max lat/long pair. + """ + + min_lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng.LatLng,) + + max_lat_lng = proto.Field(proto.MESSAGE, number=2, message=latlng.LatLng,) + + +class ColorInfo(proto.Message): + r"""Color information consists of RGB channels, score, and the + fraction of the image that the color occupies in the image. + + Attributes: + color (~.gt_color.Color): + RGB components of the color. + score (float): + Image-specific score for this color. Value in range [0, 1]. + pixel_fraction (float): + The fraction of pixels the color occupies in the image. + Value in range [0, 1]. + """ + + color = proto.Field(proto.MESSAGE, number=1, message=gt_color.Color,) + + score = proto.Field(proto.FLOAT, number=2) + + pixel_fraction = proto.Field(proto.FLOAT, number=3) + + +class DominantColorsAnnotation(proto.Message): + r"""Set of dominant colors and their corresponding scores. + + Attributes: + colors (Sequence[~.image_annotator.ColorInfo]): + RGB color values with their score and pixel + fraction. + """ + + colors = proto.RepeatedField(proto.MESSAGE, number=1, message=ColorInfo,) + + +class ImageProperties(proto.Message): + r"""Stores image properties, such as dominant colors. + + Attributes: + dominant_colors (~.image_annotator.DominantColorsAnnotation): + If present, dominant colors completed + successfully. + """ + + dominant_colors = proto.Field( + proto.MESSAGE, number=1, message=DominantColorsAnnotation, + ) + + +class CropHint(proto.Message): + r"""Single crop hint that is used to generate a new crop when + serving an image. + + Attributes: + bounding_poly (~.geometry.BoundingPoly): + The bounding polygon for the crop region. The coordinates of + the bounding box are in the original image's scale, as + returned in ``ImageParams``. + confidence (float): + Confidence of this being a salient region. Range [0, 1]. + importance_fraction (float): + Fraction of importance of this salient region + with respect to the original image. + """ + + bounding_poly = proto.Field(proto.MESSAGE, number=1, message=geometry.BoundingPoly,) + + confidence = proto.Field(proto.FLOAT, number=2) + + importance_fraction = proto.Field(proto.FLOAT, number=3) + + +class CropHintsAnnotation(proto.Message): + r"""Set of crop hints that are used to generate new crops when + serving images. + + Attributes: + crop_hints (Sequence[~.image_annotator.CropHint]): + Crop hint results. + """ + + crop_hints = proto.RepeatedField(proto.MESSAGE, number=1, message=CropHint,) + + +class CropHintsParams(proto.Message): + r"""Parameters for crop hints annotation request. + + Attributes: + aspect_ratios (Sequence[float]): + Aspect ratios in floats, representing the + ratio of the width to the height of the image. + For example, if the desired aspect ratio is 4/3, + the corresponding float value should be 1.33333. + If not specified, the best possible crop is + returned. The number of provided aspect ratios + is limited to a maximum of 16; any aspect ratios + provided after the 16th are ignored. + """ + + aspect_ratios = proto.RepeatedField(proto.FLOAT, number=1) + + +class WebDetectionParams(proto.Message): + r"""Parameters for web detection request. + + Attributes: + include_geo_results (bool): + Whether to include results derived from the + geo information in the image. + """ + + include_geo_results = proto.Field(proto.BOOL, number=2) + + +class ImageContext(proto.Message): + r"""Image context and/or feature-specific parameters. + + Attributes: + lat_long_rect (~.image_annotator.LatLongRect): + lat/long rectangle that specifies the + location of the image. + language_hints (Sequence[str]): + List of languages to use for TEXT_DETECTION. In most cases, + an empty value yields the best results since it enables + automatic language detection. For languages based on the + Latin alphabet, setting ``language_hints`` is not needed. In + rare cases, when the language of the text in the image is + known, setting a hint will help get better results (although + it will be a significant hindrance if the hint is wrong). + Text detection returns an error if one or more of the + specified languages is not one of the `supported + languages `__. + crop_hints_params (~.image_annotator.CropHintsParams): + Parameters for crop hints annotation request. + web_detection_params (~.image_annotator.WebDetectionParams): + Parameters for web detection. + """ + + lat_long_rect = proto.Field(proto.MESSAGE, number=1, message=LatLongRect,) + + language_hints = proto.RepeatedField(proto.STRING, number=2) + + crop_hints_params = proto.Field(proto.MESSAGE, number=4, message=CropHintsParams,) + + web_detection_params = proto.Field( + proto.MESSAGE, number=6, message=WebDetectionParams, + ) + + +class AnnotateImageRequest(proto.Message): + r"""Request for performing Google Cloud Vision API tasks over a + user-provided image, with user-requested features. + + Attributes: + image (~.image_annotator.Image): + The image to be processed. + features (Sequence[~.image_annotator.Feature]): + Requested features. + image_context (~.image_annotator.ImageContext): + Additional context that may accompany the + image. + """ + + image = proto.Field(proto.MESSAGE, number=1, message=Image,) + + features = proto.RepeatedField(proto.MESSAGE, number=2, message=Feature,) + + image_context = proto.Field(proto.MESSAGE, number=3, message=ImageContext,) + + +class AnnotateImageResponse(proto.Message): + r"""Response to an image annotation request. + + Attributes: + face_annotations (Sequence[~.image_annotator.FaceAnnotation]): + If present, face detection has completed + successfully. + landmark_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, landmark detection has completed + successfully. + logo_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, logo detection has completed + successfully. + label_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, label detection has completed + successfully. + text_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, text (OCR) detection has + completed successfully. + full_text_annotation (~.text_annotation.TextAnnotation): + If present, text (OCR) detection or document + (OCR) text detection has completed successfully. + This annotation provides the structural + hierarchy for the OCR detected text. + safe_search_annotation (~.image_annotator.SafeSearchAnnotation): + If present, safe-search annotation has + completed successfully. + image_properties_annotation (~.image_annotator.ImageProperties): + If present, image properties were extracted + successfully. + crop_hints_annotation (~.image_annotator.CropHintsAnnotation): + If present, crop hints have completed + successfully. + web_detection (~.gcv_web_detection.WebDetection): + If present, web detection has completed + successfully. + error (~.status.Status): + If set, represents the error message for the operation. Note + that filled-in image annotations are guaranteed to be + correct, even when ``error`` is set. + """ + + face_annotations = proto.RepeatedField( + proto.MESSAGE, number=1, message=FaceAnnotation, + ) + + landmark_annotations = proto.RepeatedField( + proto.MESSAGE, number=2, message=EntityAnnotation, + ) + + logo_annotations = proto.RepeatedField( + proto.MESSAGE, number=3, message=EntityAnnotation, + ) + + label_annotations = proto.RepeatedField( + proto.MESSAGE, number=4, message=EntityAnnotation, + ) + + text_annotations = proto.RepeatedField( + proto.MESSAGE, number=5, message=EntityAnnotation, + ) + + full_text_annotation = proto.Field( + proto.MESSAGE, number=12, message=text_annotation.TextAnnotation, + ) + + safe_search_annotation = proto.Field( + proto.MESSAGE, number=6, message=SafeSearchAnnotation, + ) + + image_properties_annotation = proto.Field( + proto.MESSAGE, number=8, message=ImageProperties, + ) + + crop_hints_annotation = proto.Field( + proto.MESSAGE, number=11, message=CropHintsAnnotation, + ) + + web_detection = proto.Field( + proto.MESSAGE, number=13, message=gcv_web_detection.WebDetection, + ) + + error = proto.Field(proto.MESSAGE, number=9, message=status.Status,) + + +class BatchAnnotateImagesRequest(proto.Message): + r"""Multiple image annotation requests are batched into a single + service call. + + Attributes: + requests (Sequence[~.image_annotator.AnnotateImageRequest]): + Required. Individual image annotation + requests for this batch. + """ + + requests = proto.RepeatedField( + proto.MESSAGE, number=1, message=AnnotateImageRequest, + ) + + +class BatchAnnotateImagesResponse(proto.Message): + r"""Response to a batch image annotation request. + + Attributes: + responses (Sequence[~.image_annotator.AnnotateImageResponse]): + Individual responses to image annotation + requests within the batch. + """ + + responses = proto.RepeatedField( + proto.MESSAGE, number=1, message=AnnotateImageResponse, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p1beta1/types/text_annotation.py b/google/cloud/vision_v1p1beta1/types/text_annotation.py new file mode 100644 index 00000000..36c7b955 --- /dev/null +++ b/google/cloud/vision_v1p1beta1/types/text_annotation.py @@ -0,0 +1,305 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.vision_v1p1beta1.types import geometry + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p1beta1", + manifest={"TextAnnotation", "Page", "Block", "Paragraph", "Word", "Symbol",}, +) + + +class TextAnnotation(proto.Message): + r"""TextAnnotation contains a structured representation of OCR extracted + text. The hierarchy of an OCR extracted text structure is like this: + TextAnnotation -> Page -> Block -> Paragraph -> Word -> Symbol Each + structural component, starting from Page, may further have their own + properties. Properties describe detected languages, breaks etc.. + Please refer to the + [TextAnnotation.TextProperty][google.cloud.vision.v1p1beta1.TextAnnotation.TextProperty] + message definition below for more detail. + + Attributes: + pages (Sequence[~.text_annotation.Page]): + List of pages detected by OCR. + text (str): + UTF-8 text detected on the pages. + """ + + class DetectedLanguage(proto.Message): + r"""Detected language for a structural component. + + Attributes: + language_code (str): + The BCP-47 language code, such as "en-US" or "sr-Latn". For + more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + confidence (float): + Confidence of detected language. Range [0, 1]. + """ + + language_code = proto.Field(proto.STRING, number=1) + + confidence = proto.Field(proto.FLOAT, number=2) + + class DetectedBreak(proto.Message): + r"""Detected start or end of a structural component. + + Attributes: + type_ (~.text_annotation.TextAnnotation.DetectedBreak.BreakType): + Detected break type. + is_prefix (bool): + True if break prepends the element. + """ + + class BreakType(proto.Enum): + r"""Enum to denote the type of break found. New line, space etc.""" + UNKNOWN = 0 + SPACE = 1 + SURE_SPACE = 2 + EOL_SURE_SPACE = 3 + HYPHEN = 4 + LINE_BREAK = 5 + + type_ = proto.Field( + proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", + ) + + is_prefix = proto.Field(proto.BOOL, number=2) + + class TextProperty(proto.Message): + r"""Additional information detected on the structural component. + + Attributes: + detected_languages (Sequence[~.text_annotation.TextAnnotation.DetectedLanguage]): + A list of detected languages together with + confidence. + detected_break (~.text_annotation.TextAnnotation.DetectedBreak): + Detected start or end of a text segment. + """ + + detected_languages = proto.RepeatedField( + proto.MESSAGE, number=1, message="TextAnnotation.DetectedLanguage", + ) + + detected_break = proto.Field( + proto.MESSAGE, number=2, message="TextAnnotation.DetectedBreak", + ) + + pages = proto.RepeatedField(proto.MESSAGE, number=1, message="Page",) + + text = proto.Field(proto.STRING, number=2) + + +class Page(proto.Message): + r"""Detected page from OCR. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected on the page. + width (int): + Page width in pixels. + height (int): + Page height in pixels. + blocks (Sequence[~.text_annotation.Block]): + List of blocks of text, images etc on this + page. + confidence (float): + Confidence of the OCR results on the page. Range [0, 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + width = proto.Field(proto.INT32, number=2) + + height = proto.Field(proto.INT32, number=3) + + blocks = proto.RepeatedField(proto.MESSAGE, number=4, message="Block",) + + confidence = proto.Field(proto.FLOAT, number=5) + + +class Block(proto.Message): + r"""Logical element on the page. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the + block. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the block. The vertices are in the + order of top-left, top-right, bottom-right, bottom-left. + When a rotation of the bounding box is detected the rotation + is represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). + paragraphs (Sequence[~.text_annotation.Paragraph]): + List of paragraphs in this block (if this + blocks is of type text). + block_type (~.text_annotation.Block.BlockType): + Detected block type (text, image etc) for + this block. + confidence (float): + Confidence of the OCR results on the block. Range [0, 1]. + """ + + class BlockType(proto.Enum): + r"""Type of a block (text, image etc) as identified by OCR.""" + UNKNOWN = 0 + TEXT = 1 + TABLE = 2 + PICTURE = 3 + RULER = 4 + BARCODE = 5 + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + paragraphs = proto.RepeatedField(proto.MESSAGE, number=3, message="Paragraph",) + + block_type = proto.Field(proto.ENUM, number=4, enum=BlockType,) + + confidence = proto.Field(proto.FLOAT, number=5) + + +class Paragraph(proto.Message): + r"""Structural unit of text representing a number of words in + certain order. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the + paragraph. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the paragraph. The vertices are in the + order of top-left, top-right, bottom-right, bottom-left. + When a rotation of the bounding box is detected the rotation + is represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). + words (Sequence[~.text_annotation.Word]): + List of words in this paragraph. + confidence (float): + Confidence of the OCR results for the paragraph. Range [0, + 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + words = proto.RepeatedField(proto.MESSAGE, number=3, message="Word",) + + confidence = proto.Field(proto.FLOAT, number=4) + + +class Word(proto.Message): + r"""A word representation. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the word. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the word. The vertices are in the order + of top-left, top-right, bottom-right, bottom-left. When a + rotation of the bounding box is detected the rotation is + represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). + symbols (Sequence[~.text_annotation.Symbol]): + List of symbols in the word. + The order of the symbols follows the natural + reading order. + confidence (float): + Confidence of the OCR results for the word. Range [0, 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + symbols = proto.RepeatedField(proto.MESSAGE, number=3, message="Symbol",) + + confidence = proto.Field(proto.FLOAT, number=4) + + +class Symbol(proto.Message): + r"""A single symbol representation. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the + symbol. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the symbol. The vertices are in the + order of top-left, top-right, bottom-right, bottom-left. + When a rotation of the bounding box is detected the rotation + is represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). + text (str): + The actual UTF-8 representation of the + symbol. + confidence (float): + Confidence of the OCR results for the symbol. Range [0, 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + text = proto.Field(proto.STRING, number=3) + + confidence = proto.Field(proto.FLOAT, number=4) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p1beta1/types/web_detection.py b/google/cloud/vision_v1p1beta1/types/web_detection.py new file mode 100644 index 00000000..6bd91777 --- /dev/null +++ b/google/cloud/vision_v1p1beta1/types/web_detection.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p1beta1", manifest={"WebDetection",}, +) + + +class WebDetection(proto.Message): + r"""Relevant information for the image from the Internet. + + Attributes: + web_entities (Sequence[~.web_detection.WebDetection.WebEntity]): + Deduced entities from similar images on the + Internet. + full_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Fully matching images from the Internet. + Can include resized copies of the query image. + partial_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Partial matching images from the Internet. + Those images are similar enough to share some + key-point features. For example an original + image will likely have partial matching for its + crops. + pages_with_matching_images (Sequence[~.web_detection.WebDetection.WebPage]): + Web pages containing the matching images from + the Internet. + visually_similar_images (Sequence[~.web_detection.WebDetection.WebImage]): + The visually similar image results. + best_guess_labels (Sequence[~.web_detection.WebDetection.WebLabel]): + Best guess text labels for the request image. + """ + + class WebEntity(proto.Message): + r"""Entity deduced from similar images on the Internet. + + Attributes: + entity_id (str): + Opaque entity ID. + score (float): + Overall relevancy score for the entity. + Not normalized and not comparable across + different image queries. + description (str): + Canonical description of the entity, in + English. + """ + + entity_id = proto.Field(proto.STRING, number=1) + + score = proto.Field(proto.FLOAT, number=2) + + description = proto.Field(proto.STRING, number=3) + + class WebImage(proto.Message): + r"""Metadata for online images. + + Attributes: + url (str): + The result image URL. + score (float): + (Deprecated) Overall relevancy score for the + image. + """ + + url = proto.Field(proto.STRING, number=1) + + score = proto.Field(proto.FLOAT, number=2) + + class WebPage(proto.Message): + r"""Metadata for web pages. + + Attributes: + url (str): + The result web page URL. + score (float): + (Deprecated) Overall relevancy score for the + web page. + page_title (str): + Title for the web page, may contain HTML + markups. + full_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Fully matching images on the page. + Can include resized copies of the query image. + partial_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Partial matching images on the page. + Those images are similar enough to share some + key-point features. For example an original + image will likely have partial matching for its + crops. + """ + + url = proto.Field(proto.STRING, number=1) + + score = proto.Field(proto.FLOAT, number=2) + + page_title = proto.Field(proto.STRING, number=3) + + full_matching_images = proto.RepeatedField( + proto.MESSAGE, number=4, message="WebDetection.WebImage", + ) + + partial_matching_images = proto.RepeatedField( + proto.MESSAGE, number=5, message="WebDetection.WebImage", + ) + + class WebLabel(proto.Message): + r"""Label to provide extra metadata for the web detection. + + Attributes: + label (str): + Label for extra metadata. + language_code (str): + The BCP-47 language code for ``label``, such as "en-US" or + "sr-Latn". For more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + """ + + label = proto.Field(proto.STRING, number=1) + + language_code = proto.Field(proto.STRING, number=2) + + web_entities = proto.RepeatedField(proto.MESSAGE, number=1, message=WebEntity,) + + full_matching_images = proto.RepeatedField( + proto.MESSAGE, number=2, message=WebImage, + ) + + partial_matching_images = proto.RepeatedField( + proto.MESSAGE, number=3, message=WebImage, + ) + + pages_with_matching_images = proto.RepeatedField( + proto.MESSAGE, number=4, message=WebPage, + ) + + visually_similar_images = proto.RepeatedField( + proto.MESSAGE, number=6, message=WebImage, + ) + + best_guess_labels = proto.RepeatedField(proto.MESSAGE, number=8, message=WebLabel,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p2beta1/__init__.py b/google/cloud/vision_v1p2beta1/__init__.py index 43e50de1..594f7e7a 100644 --- a/google/cloud/vision_v1p2beta1/__init__.py +++ b/google/cloud/vision_v1p2beta1/__init__.py @@ -1,49 +1,120 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - - -from __future__ import absolute_import +# from google.cloud.vision_helpers.decorators import add_single_feature_methods from google.cloud.vision_helpers import VisionHelpers -import sys -import warnings - -from google.cloud.vision_v1p2beta1 import types -from google.cloud.vision_v1p2beta1.gapic import enums -from google.cloud.vision_v1p2beta1.gapic import image_annotator_client as iac - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) +from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient +from .types.geometry import BoundingPoly +from .types.geometry import NormalizedVertex +from .types.geometry import Position +from .types.geometry import Vertex +from .types.image_annotator import AnnotateFileResponse +from .types.image_annotator import AnnotateImageRequest +from .types.image_annotator import AnnotateImageResponse +from .types.image_annotator import AsyncAnnotateFileRequest +from .types.image_annotator import AsyncAnnotateFileResponse +from .types.image_annotator import AsyncBatchAnnotateFilesRequest +from .types.image_annotator import AsyncBatchAnnotateFilesResponse +from .types.image_annotator import BatchAnnotateImagesRequest +from .types.image_annotator import BatchAnnotateImagesResponse +from .types.image_annotator import ColorInfo +from .types.image_annotator import CropHint +from .types.image_annotator import CropHintsAnnotation +from .types.image_annotator import CropHintsParams +from .types.image_annotator import DominantColorsAnnotation +from .types.image_annotator import EntityAnnotation +from .types.image_annotator import FaceAnnotation +from .types.image_annotator import Feature +from .types.image_annotator import GcsDestination +from .types.image_annotator import GcsSource +from .types.image_annotator import Image +from .types.image_annotator import ImageAnnotationContext +from .types.image_annotator import ImageContext +from .types.image_annotator import ImageProperties +from .types.image_annotator import ImageSource +from .types.image_annotator import InputConfig +from .types.image_annotator import LatLongRect +from .types.image_annotator import Likelihood +from .types.image_annotator import LocationInfo +from .types.image_annotator import OperationMetadata +from .types.image_annotator import OutputConfig +from .types.image_annotator import Property +from .types.image_annotator import SafeSearchAnnotation +from .types.image_annotator import WebDetectionParams +from .types.text_annotation import Block +from .types.text_annotation import Page +from .types.text_annotation import Paragraph +from .types.text_annotation import Symbol +from .types.text_annotation import TextAnnotation +from .types.text_annotation import Word +from .types.web_detection import WebDetection @add_single_feature_methods -class ImageAnnotatorClient(VisionHelpers, iac.ImageAnnotatorClient): - __doc__ = iac.ImageAnnotatorClient.__doc__ - enums = enums +class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): + __doc__ = IacImageAnnotatorClient.__doc__ + Feature = Feature __all__ = ( - "enums", - "types", + "AnnotateFileResponse", + "AnnotateImageRequest", + "AnnotateImageResponse", + "AsyncAnnotateFileRequest", + "AsyncAnnotateFileResponse", + "AsyncBatchAnnotateFilesRequest", + "AsyncBatchAnnotateFilesResponse", + "BatchAnnotateImagesRequest", + "BatchAnnotateImagesResponse", + "Block", + "BoundingPoly", + "ColorInfo", + "CropHint", + "CropHintsAnnotation", + "CropHintsParams", + "DominantColorsAnnotation", + "EntityAnnotation", + "FaceAnnotation", + "Feature", + "GcsDestination", + "GcsSource", + "Image", + "ImageAnnotationContext", + "ImageContext", + "ImageProperties", + "ImageSource", + "InputConfig", + "LatLongRect", + "Likelihood", + "LocationInfo", + "NormalizedVertex", + "OperationMetadata", + "OutputConfig", + "Page", + "Paragraph", + "Position", + "Property", + "SafeSearchAnnotation", + "Symbol", + "TextAnnotation", + "Vertex", + "WebDetection", + "WebDetectionParams", + "Word", "ImageAnnotatorClient", ) diff --git a/google/cloud/vision_v1p2beta1/gapic/__init__.py b/google/cloud/vision_v1p2beta1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/vision_v1p2beta1/gapic/enums.py b/google/cloud/vision_v1p2beta1/gapic/enums.py deleted file mode 100644 index 2bc57b08..00000000 --- a/google/cloud/vision_v1p2beta1/gapic/enums.py +++ /dev/null @@ -1,228 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class Likelihood(enum.IntEnum): - """ - A bucketized representation of likelihood, which is intended to give clients - highly stable results across model upgrades. - - Attributes: - UNKNOWN (int): Unknown likelihood. - VERY_UNLIKELY (int): It is very unlikely that the image belongs to the specified vertical. - UNLIKELY (int): It is unlikely that the image belongs to the specified vertical. - POSSIBLE (int): It is possible that the image belongs to the specified vertical. - LIKELY (int): It is likely that the image belongs to the specified vertical. - VERY_LIKELY (int): It is very likely that the image belongs to the specified vertical. - """ - - UNKNOWN = 0 - VERY_UNLIKELY = 1 - UNLIKELY = 2 - POSSIBLE = 3 - LIKELY = 4 - VERY_LIKELY = 5 - - -class Block(object): - class BlockType(enum.IntEnum): - """ - Type of a block (text, image etc) as identified by OCR. - - Attributes: - UNKNOWN (int): Unknown block type. - TEXT (int): Regular text block. - TABLE (int): Table block. - PICTURE (int): Image block. - RULER (int): Horizontal/vertical line box. - BARCODE (int): Barcode block. - """ - - UNKNOWN = 0 - TEXT = 1 - TABLE = 2 - PICTURE = 3 - RULER = 4 - BARCODE = 5 - - -class FaceAnnotation(object): - class Landmark(object): - class Type(enum.IntEnum): - """ - Face landmark (feature) type. Left and right are defined from the - vantage of the viewer of the image without considering mirror - projections typical of photos. So, ``LEFT_EYE``, typically, is the - person's right eye. - - Attributes: - UNKNOWN_LANDMARK (int): Unknown face landmark detected. Should not be filled. - LEFT_EYE (int): Left eye. - RIGHT_EYE (int): Right eye. - LEFT_OF_LEFT_EYEBROW (int): Left of left eyebrow. - RIGHT_OF_LEFT_EYEBROW (int): Right of left eyebrow. - LEFT_OF_RIGHT_EYEBROW (int): Left of right eyebrow. - RIGHT_OF_RIGHT_EYEBROW (int): Right of right eyebrow. - MIDPOINT_BETWEEN_EYES (int): Midpoint between eyes. - NOSE_TIP (int): Nose tip. - UPPER_LIP (int): Upper lip. - LOWER_LIP (int): Lower lip. - MOUTH_LEFT (int): Mouth left. - MOUTH_RIGHT (int): Mouth right. - MOUTH_CENTER (int): Mouth center. - NOSE_BOTTOM_RIGHT (int): Nose, bottom right. - NOSE_BOTTOM_LEFT (int): Nose, bottom left. - NOSE_BOTTOM_CENTER (int): Nose, bottom center. - LEFT_EYE_TOP_BOUNDARY (int): Left eye, top boundary. - LEFT_EYE_RIGHT_CORNER (int): Left eye, right corner. - LEFT_EYE_BOTTOM_BOUNDARY (int): Left eye, bottom boundary. - LEFT_EYE_LEFT_CORNER (int): Left eye, left corner. - RIGHT_EYE_TOP_BOUNDARY (int): Right eye, top boundary. - RIGHT_EYE_RIGHT_CORNER (int): Right eye, right corner. - RIGHT_EYE_BOTTOM_BOUNDARY (int): Right eye, bottom boundary. - RIGHT_EYE_LEFT_CORNER (int): Right eye, left corner. - LEFT_EYEBROW_UPPER_MIDPOINT (int): Left eyebrow, upper midpoint. - RIGHT_EYEBROW_UPPER_MIDPOINT (int): Right eyebrow, upper midpoint. - LEFT_EAR_TRAGION (int): Left ear tragion. - RIGHT_EAR_TRAGION (int): Right ear tragion. - LEFT_EYE_PUPIL (int): Left eye pupil. - RIGHT_EYE_PUPIL (int): Right eye pupil. - FOREHEAD_GLABELLA (int): Forehead glabella. - CHIN_GNATHION (int): Chin gnathion. - CHIN_LEFT_GONION (int): Chin left gonion. - CHIN_RIGHT_GONION (int): Chin right gonion. - """ - - UNKNOWN_LANDMARK = 0 - LEFT_EYE = 1 - RIGHT_EYE = 2 - LEFT_OF_LEFT_EYEBROW = 3 - RIGHT_OF_LEFT_EYEBROW = 4 - LEFT_OF_RIGHT_EYEBROW = 5 - RIGHT_OF_RIGHT_EYEBROW = 6 - MIDPOINT_BETWEEN_EYES = 7 - NOSE_TIP = 8 - UPPER_LIP = 9 - LOWER_LIP = 10 - MOUTH_LEFT = 11 - MOUTH_RIGHT = 12 - MOUTH_CENTER = 13 - NOSE_BOTTOM_RIGHT = 14 - NOSE_BOTTOM_LEFT = 15 - NOSE_BOTTOM_CENTER = 16 - LEFT_EYE_TOP_BOUNDARY = 17 - LEFT_EYE_RIGHT_CORNER = 18 - LEFT_EYE_BOTTOM_BOUNDARY = 19 - LEFT_EYE_LEFT_CORNER = 20 - RIGHT_EYE_TOP_BOUNDARY = 21 - RIGHT_EYE_RIGHT_CORNER = 22 - RIGHT_EYE_BOTTOM_BOUNDARY = 23 - RIGHT_EYE_LEFT_CORNER = 24 - LEFT_EYEBROW_UPPER_MIDPOINT = 25 - RIGHT_EYEBROW_UPPER_MIDPOINT = 26 - LEFT_EAR_TRAGION = 27 - RIGHT_EAR_TRAGION = 28 - LEFT_EYE_PUPIL = 29 - RIGHT_EYE_PUPIL = 30 - FOREHEAD_GLABELLA = 31 - CHIN_GNATHION = 32 - CHIN_LEFT_GONION = 33 - CHIN_RIGHT_GONION = 34 - - -class Feature(object): - class Type(enum.IntEnum): - """ - Type of Google Cloud Vision API feature to be extracted. - - Attributes: - TYPE_UNSPECIFIED (int): Unspecified feature type. - FACE_DETECTION (int): Run face detection. - LANDMARK_DETECTION (int): Run landmark detection. - LOGO_DETECTION (int): Run logo detection. - LABEL_DETECTION (int): Run label detection. - TEXT_DETECTION (int): Run text detection / optical character recognition (OCR). Text - detection is optimized for areas of text within a larger image; if the - image is a document, use ``DOCUMENT_TEXT_DETECTION`` instead. - DOCUMENT_TEXT_DETECTION (int): Run dense text document OCR. Takes precedence when both - ``DOCUMENT_TEXT_DETECTION`` and ``TEXT_DETECTION`` are present. - SAFE_SEARCH_DETECTION (int): Run Safe Search to detect potentially unsafe - or undesirable content. - IMAGE_PROPERTIES (int): Compute a set of image properties, such as the - image's dominant colors. - CROP_HINTS (int): Run crop hints. - WEB_DETECTION (int): Run web detection. - """ - - TYPE_UNSPECIFIED = 0 - FACE_DETECTION = 1 - LANDMARK_DETECTION = 2 - LOGO_DETECTION = 3 - LABEL_DETECTION = 4 - TEXT_DETECTION = 5 - DOCUMENT_TEXT_DETECTION = 11 - SAFE_SEARCH_DETECTION = 6 - IMAGE_PROPERTIES = 7 - CROP_HINTS = 9 - WEB_DETECTION = 10 - - -class OperationMetadata(object): - class State(enum.IntEnum): - """ - Batch operation states. - - Attributes: - STATE_UNSPECIFIED (int): Invalid. - CREATED (int): Request is received. - RUNNING (int): Request is actively being processed. - DONE (int): The batch processing is done. - CANCELLED (int): The batch processing was cancelled. - """ - - STATE_UNSPECIFIED = 0 - CREATED = 1 - RUNNING = 2 - DONE = 3 - CANCELLED = 4 - - -class TextAnnotation(object): - class DetectedBreak(object): - class BreakType(enum.IntEnum): - """ - Enum to denote the type of break found. New line, space etc. - - Attributes: - UNKNOWN (int): Unknown break label type. - SPACE (int): Regular space. - SURE_SPACE (int): Sure space (very wide). - EOL_SURE_SPACE (int): Line-wrapping break. - HYPHEN (int): End-line hyphen that is not present in text; does not co-occur with - ``SPACE``, ``LEADER_SPACE``, or ``LINE_BREAK``. - LINE_BREAK (int): Line break that ends a paragraph. - """ - - UNKNOWN = 0 - SPACE = 1 - SURE_SPACE = 2 - EOL_SURE_SPACE = 3 - HYPHEN = 4 - LINE_BREAK = 5 diff --git a/google/cloud/vision_v1p2beta1/gapic/image_annotator_client.py b/google/cloud/vision_v1p2beta1/gapic/image_annotator_client.py deleted file mode 100644 index 8a7b02a9..00000000 --- a/google/cloud/vision_v1p2beta1/gapic/image_annotator_client.py +++ /dev/null @@ -1,330 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.vision.v1p2beta1 ImageAnnotator API.""" - -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.grpc_helpers -import google.api_core.operation -from google.api_core import operations_v1 -import grpc - -from google.cloud.vision_v1p2beta1.gapic import enums -from google.cloud.vision_v1p2beta1.gapic import image_annotator_client_config -from google.cloud.vision_v1p2beta1.gapic.transports import ( - image_annotator_grpc_transport, -) -from google.cloud.vision_v1p2beta1.proto import image_annotator_pb2 -from google.cloud.vision_v1p2beta1.proto import image_annotator_pb2_grpc -from google.longrunning import operations_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-vision",).version - - -class ImageAnnotatorClient(object): - """ - Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - SERVICE_ADDRESS = "vision.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.vision.v1p2beta1.ImageAnnotator" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ImageAnnotatorClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.ImageAnnotatorGrpcTransport, - Callable[[~.Credentials, type], ~.ImageAnnotatorGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = image_annotator_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=image_annotator_grpc_transport.ImageAnnotatorGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = image_annotator_grpc_transport.ImageAnnotatorGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def async_batch_annotate_files( - self, - requests, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Run async image detection and annotation for a list of generic files - (e.g. PDF) which may contain multiple pages and multiple images per - page. Progress and results can be retrieved through the - ``google.longrunning.Operations`` interface. ``Operation.metadata`` - contains ``OperationMetadata`` (metadata). ``Operation.response`` - contains ``AsyncBatchAnnotateFilesResponse`` (results). - - Example: - >>> from google.cloud import vision_v1p2beta1 - >>> - >>> client = vision_v1p2beta1.ImageAnnotatorClient() - >>> - >>> # TODO: Initialize `requests`: - >>> requests = [] - >>> - >>> response = client.async_batch_annotate_files(requests) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - requests (list[Union[dict, ~google.cloud.vision_v1p2beta1.types.AsyncAnnotateFileRequest]]): Required. Individual async file annotation requests for this batch. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p2beta1.types.AsyncAnnotateFileRequest` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p2beta1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "async_batch_annotate_files" not in self._inner_api_calls: - self._inner_api_calls[ - "async_batch_annotate_files" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.async_batch_annotate_files, - default_retry=self._method_configs["AsyncBatchAnnotateFiles"].retry, - default_timeout=self._method_configs["AsyncBatchAnnotateFiles"].timeout, - client_info=self._client_info, - ) - - request = image_annotator_pb2.AsyncBatchAnnotateFilesRequest(requests=requests,) - operation = self._inner_api_calls["async_batch_annotate_files"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - image_annotator_pb2.AsyncBatchAnnotateFilesResponse, - metadata_type=image_annotator_pb2.OperationMetadata, - ) - - def batch_annotate_images( - self, - requests, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Run image detection and annotation for a batch of images. - - Example: - >>> from google.cloud import vision_v1p2beta1 - >>> - >>> client = vision_v1p2beta1.ImageAnnotatorClient() - >>> - >>> # TODO: Initialize `requests`: - >>> requests = [] - >>> - >>> response = client.batch_annotate_images(requests) - - Args: - requests (list[Union[dict, ~google.cloud.vision_v1p2beta1.types.AnnotateImageRequest]]): Required. Individual image annotation requests for this batch. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p2beta1.types.AnnotateImageRequest` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p2beta1.types.BatchAnnotateImagesResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "batch_annotate_images" not in self._inner_api_calls: - self._inner_api_calls[ - "batch_annotate_images" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.batch_annotate_images, - default_retry=self._method_configs["BatchAnnotateImages"].retry, - default_timeout=self._method_configs["BatchAnnotateImages"].timeout, - client_info=self._client_info, - ) - - request = image_annotator_pb2.BatchAnnotateImagesRequest(requests=requests,) - return self._inner_api_calls["batch_annotate_images"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/vision_v1p2beta1/gapic/image_annotator_client_config.py b/google/cloud/vision_v1p2beta1/gapic/image_annotator_client_config.py deleted file mode 100644 index f28a817c..00000000 --- a/google/cloud/vision_v1p2beta1/gapic/image_annotator_client_config.py +++ /dev/null @@ -1,42 +0,0 @@ -config = { - "interfaces": { - "google.cloud.vision.v1p2beta1.ImageAnnotator": { - "retry_codes": { - "retry_policy_1_codes": ["UNAVAILABLE", "DEADLINE_EXCEEDED"], - "no_retry_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 600000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 600000, - "total_timeout_millis": 600000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - }, - "methods": { - "AsyncBatchAnnotateFiles": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "BatchAnnotateImages": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - }, - } - } -} diff --git a/google/cloud/vision_v1p2beta1/gapic/transports/__init__.py b/google/cloud/vision_v1p2beta1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/vision_v1p2beta1/gapic/transports/image_annotator_grpc_transport.py b/google/cloud/vision_v1p2beta1/gapic/transports/image_annotator_grpc_transport.py deleted file mode 100644 index d3ac5544..00000000 --- a/google/cloud/vision_v1p2beta1/gapic/transports/image_annotator_grpc_transport.py +++ /dev/null @@ -1,152 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers -from google.api_core import operations_v1 - -from google.cloud.vision_v1p2beta1.proto import image_annotator_pb2_grpc - - -class ImageAnnotatorGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.vision.v1p2beta1 ImageAnnotator API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ) - - def __init__( - self, channel=None, credentials=None, address="vision.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "image_annotator_stub": image_annotator_pb2_grpc.ImageAnnotatorStub( - channel - ), - } - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="vision.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def async_batch_annotate_files(self): - """Return the gRPC stub for :meth:`ImageAnnotatorClient.async_batch_annotate_files`. - - Run async image detection and annotation for a list of generic files - (e.g. PDF) which may contain multiple pages and multiple images per - page. Progress and results can be retrieved through the - ``google.longrunning.Operations`` interface. ``Operation.metadata`` - contains ``OperationMetadata`` (metadata). ``Operation.response`` - contains ``AsyncBatchAnnotateFilesResponse`` (results). - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["image_annotator_stub"].AsyncBatchAnnotateFiles - - @property - def batch_annotate_images(self): - """Return the gRPC stub for :meth:`ImageAnnotatorClient.batch_annotate_images`. - - Run image detection and annotation for a batch of images. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["image_annotator_stub"].BatchAnnotateImages diff --git a/google/cloud/vision_v1p2beta1/proto/__init__.py b/google/cloud/vision_v1p2beta1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/vision_v1p2beta1/proto/geometry_pb2.py b/google/cloud/vision_v1p2beta1/proto/geometry_pb2.py deleted file mode 100644 index 9444883b..00000000 --- a/google/cloud/vision_v1p2beta1/proto/geometry_pb2.py +++ /dev/null @@ -1,369 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p2beta1/proto/geometry.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p2beta1/proto/geometry.proto", - package="google.cloud.vision.v1p2beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p2beta1B\rGeometryProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p2beta1;vision\370\001\001", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n2google/cloud/vision_v1p2beta1/proto/geometry.proto\x12\x1dgoogle.cloud.vision.v1p2beta1"\x1e\n\x06Vertex\x12\t\n\x01x\x18\x01 \x01(\x05\x12\t\n\x01y\x18\x02 \x01(\x05"(\n\x10NormalizedVertex\x12\t\n\x01x\x18\x01 \x01(\x02\x12\t\n\x01y\x18\x02 \x01(\x02"\x95\x01\n\x0c\x42oundingPoly\x12\x37\n\x08vertices\x18\x01 \x03(\x0b\x32%.google.cloud.vision.v1p2beta1.Vertex\x12L\n\x13normalized_vertices\x18\x02 \x03(\x0b\x32/.google.cloud.vision.v1p2beta1.NormalizedVertex"+\n\x08Position\x12\t\n\x01x\x18\x01 \x01(\x02\x12\t\n\x01y\x18\x02 \x01(\x02\x12\t\n\x01z\x18\x03 \x01(\x02\x42|\n!com.google.cloud.vision.v1p2beta1B\rGeometryProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p2beta1;vision\xf8\x01\x01\x62\x06proto3', -) - - -_VERTEX = _descriptor.Descriptor( - name="Vertex", - full_name="google.cloud.vision.v1p2beta1.Vertex", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="x", - full_name="google.cloud.vision.v1p2beta1.Vertex.x", - index=0, - number=1, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="y", - full_name="google.cloud.vision.v1p2beta1.Vertex.y", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=85, - serialized_end=115, -) - - -_NORMALIZEDVERTEX = _descriptor.Descriptor( - name="NormalizedVertex", - full_name="google.cloud.vision.v1p2beta1.NormalizedVertex", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="x", - full_name="google.cloud.vision.v1p2beta1.NormalizedVertex.x", - index=0, - number=1, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="y", - full_name="google.cloud.vision.v1p2beta1.NormalizedVertex.y", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=117, - serialized_end=157, -) - - -_BOUNDINGPOLY = _descriptor.Descriptor( - name="BoundingPoly", - full_name="google.cloud.vision.v1p2beta1.BoundingPoly", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="vertices", - full_name="google.cloud.vision.v1p2beta1.BoundingPoly.vertices", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="normalized_vertices", - full_name="google.cloud.vision.v1p2beta1.BoundingPoly.normalized_vertices", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=160, - serialized_end=309, -) - - -_POSITION = _descriptor.Descriptor( - name="Position", - full_name="google.cloud.vision.v1p2beta1.Position", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="x", - full_name="google.cloud.vision.v1p2beta1.Position.x", - index=0, - number=1, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="y", - full_name="google.cloud.vision.v1p2beta1.Position.y", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="z", - full_name="google.cloud.vision.v1p2beta1.Position.z", - index=2, - number=3, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=311, - serialized_end=354, -) - -_BOUNDINGPOLY.fields_by_name["vertices"].message_type = _VERTEX -_BOUNDINGPOLY.fields_by_name["normalized_vertices"].message_type = _NORMALIZEDVERTEX -DESCRIPTOR.message_types_by_name["Vertex"] = _VERTEX -DESCRIPTOR.message_types_by_name["NormalizedVertex"] = _NORMALIZEDVERTEX -DESCRIPTOR.message_types_by_name["BoundingPoly"] = _BOUNDINGPOLY -DESCRIPTOR.message_types_by_name["Position"] = _POSITION -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Vertex = _reflection.GeneratedProtocolMessageType( - "Vertex", - (_message.Message,), - { - "DESCRIPTOR": _VERTEX, - "__module__": "google.cloud.vision_v1p2beta1.proto.geometry_pb2", - "__doc__": """X coordinate. - - Attributes: - y: - Y coordinate. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.Vertex) - }, -) -_sym_db.RegisterMessage(Vertex) - -NormalizedVertex = _reflection.GeneratedProtocolMessageType( - "NormalizedVertex", - (_message.Message,), - { - "DESCRIPTOR": _NORMALIZEDVERTEX, - "__module__": "google.cloud.vision_v1p2beta1.proto.geometry_pb2", - "__doc__": """X coordinate. - - Attributes: - y: - Y coordinate. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.NormalizedVertex) - }, -) -_sym_db.RegisterMessage(NormalizedVertex) - -BoundingPoly = _reflection.GeneratedProtocolMessageType( - "BoundingPoly", - (_message.Message,), - { - "DESCRIPTOR": _BOUNDINGPOLY, - "__module__": "google.cloud.vision_v1p2beta1.proto.geometry_pb2", - "__doc__": """A bounding polygon for the detected image annotation. - - Attributes: - vertices: - The bounding polygon vertices. - normalized_vertices: - The bounding polygon normalized vertices. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.BoundingPoly) - }, -) -_sym_db.RegisterMessage(BoundingPoly) - -Position = _reflection.GeneratedProtocolMessageType( - "Position", - (_message.Message,), - { - "DESCRIPTOR": _POSITION, - "__module__": "google.cloud.vision_v1p2beta1.proto.geometry_pb2", - "__doc__": """A 3D position in the image, used primarily for Face detection - landmarks. A valid Position must have both x and y coordinates. The - position coordinates are in the same scale as the original image. - - Attributes: - x: - X coordinate. - y: - Y coordinate. - z: - Z coordinate (or depth). - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.Position) - }, -) -_sym_db.RegisterMessage(Position) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p2beta1/proto/geometry_pb2_grpc.py b/google/cloud/vision_v1p2beta1/proto/geometry_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/vision_v1p2beta1/proto/geometry_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/vision_v1p2beta1/proto/image_annotator_pb2.py b/google/cloud/vision_v1p2beta1/proto/image_annotator_pb2.py deleted file mode 100644 index 9e9c6380..00000000 --- a/google/cloud/vision_v1p2beta1/proto/image_annotator_pb2.py +++ /dev/null @@ -1,4175 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p2beta1/proto/image_annotator.proto -"""Generated protocol buffer code.""" -from google.protobuf.internal import enum_type_wrapper -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.cloud.vision_v1p2beta1.proto import ( - geometry_pb2 as google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_geometry__pb2, -) -from google.cloud.vision_v1p2beta1.proto import ( - text_annotation_pb2 as google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_text__annotation__pb2, -) -from google.cloud.vision_v1p2beta1.proto import ( - web_detection_pb2 as google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_web__detection__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2 -from google.type import color_pb2 as google_dot_type_dot_color__pb2 -from google.type import latlng_pb2 as google_dot_type_dot_latlng__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p2beta1/proto/image_annotator.proto", - package="google.cloud.vision.v1p2beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p2beta1B\023ImageAnnotatorProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p2beta1;vision\370\001\001", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n9google/cloud/vision_v1p2beta1/proto/image_annotator.proto\x12\x1dgoogle.cloud.vision.v1p2beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x32google/cloud/vision_v1p2beta1/proto/geometry.proto\x1a\x39google/cloud/vision_v1p2beta1/proto/text_annotation.proto\x1a\x37google/cloud/vision_v1p2beta1/proto/web_detection.proto\x1a#google/longrunning/operations.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x17google/rpc/status.proto\x1a\x17google/type/color.proto\x1a\x18google/type/latlng.proto"\xe1\x02\n\x07\x46\x65\x61ture\x12\x39\n\x04type\x18\x01 \x01(\x0e\x32+.google.cloud.vision.v1p2beta1.Feature.Type\x12\x13\n\x0bmax_results\x18\x02 \x01(\x05\x12\r\n\x05model\x18\x03 \x01(\t"\xf6\x01\n\x04Type\x12\x14\n\x10TYPE_UNSPECIFIED\x10\x00\x12\x12\n\x0e\x46\x41\x43\x45_DETECTION\x10\x01\x12\x16\n\x12LANDMARK_DETECTION\x10\x02\x12\x12\n\x0eLOGO_DETECTION\x10\x03\x12\x13\n\x0fLABEL_DETECTION\x10\x04\x12\x12\n\x0eTEXT_DETECTION\x10\x05\x12\x1b\n\x17\x44OCUMENT_TEXT_DETECTION\x10\x0b\x12\x19\n\x15SAFE_SEARCH_DETECTION\x10\x06\x12\x14\n\x10IMAGE_PROPERTIES\x10\x07\x12\x0e\n\nCROP_HINTS\x10\t\x12\x11\n\rWEB_DETECTION\x10\n"7\n\x0bImageSource\x12\x15\n\rgcs_image_uri\x18\x01 \x01(\t\x12\x11\n\timage_uri\x18\x02 \x01(\t"T\n\x05Image\x12\x0f\n\x07\x63ontent\x18\x01 \x01(\x0c\x12:\n\x06source\x18\x02 \x01(\x0b\x32*.google.cloud.vision.v1p2beta1.ImageSource"\x9b\x0e\n\x0e\x46\x61\x63\x65\x41nnotation\x12\x42\n\rbounding_poly\x18\x01 \x01(\x0b\x32+.google.cloud.vision.v1p2beta1.BoundingPoly\x12\x45\n\x10\x66\x64_bounding_poly\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p2beta1.BoundingPoly\x12I\n\tlandmarks\x18\x03 \x03(\x0b\x32\x36.google.cloud.vision.v1p2beta1.FaceAnnotation.Landmark\x12\x12\n\nroll_angle\x18\x04 \x01(\x02\x12\x11\n\tpan_angle\x18\x05 \x01(\x02\x12\x12\n\ntilt_angle\x18\x06 \x01(\x02\x12\x1c\n\x14\x64\x65tection_confidence\x18\x07 \x01(\x02\x12\x1e\n\x16landmarking_confidence\x18\x08 \x01(\x02\x12\x41\n\x0ejoy_likelihood\x18\t \x01(\x0e\x32).google.cloud.vision.v1p2beta1.Likelihood\x12\x44\n\x11sorrow_likelihood\x18\n \x01(\x0e\x32).google.cloud.vision.v1p2beta1.Likelihood\x12\x43\n\x10\x61nger_likelihood\x18\x0b \x01(\x0e\x32).google.cloud.vision.v1p2beta1.Likelihood\x12\x46\n\x13surprise_likelihood\x18\x0c \x01(\x0e\x32).google.cloud.vision.v1p2beta1.Likelihood\x12K\n\x18under_exposed_likelihood\x18\r \x01(\x0e\x32).google.cloud.vision.v1p2beta1.Likelihood\x12\x45\n\x12\x62lurred_likelihood\x18\x0e \x01(\x0e\x32).google.cloud.vision.v1p2beta1.Likelihood\x12\x46\n\x13headwear_likelihood\x18\x0f \x01(\x0e\x32).google.cloud.vision.v1p2beta1.Likelihood\x1a\xc7\x07\n\x08Landmark\x12I\n\x04type\x18\x03 \x01(\x0e\x32;.google.cloud.vision.v1p2beta1.FaceAnnotation.Landmark.Type\x12\x39\n\x08position\x18\x04 \x01(\x0b\x32\'.google.cloud.vision.v1p2beta1.Position"\xb4\x06\n\x04Type\x12\x14\n\x10UNKNOWN_LANDMARK\x10\x00\x12\x0c\n\x08LEFT_EYE\x10\x01\x12\r\n\tRIGHT_EYE\x10\x02\x12\x18\n\x14LEFT_OF_LEFT_EYEBROW\x10\x03\x12\x19\n\x15RIGHT_OF_LEFT_EYEBROW\x10\x04\x12\x19\n\x15LEFT_OF_RIGHT_EYEBROW\x10\x05\x12\x1a\n\x16RIGHT_OF_RIGHT_EYEBROW\x10\x06\x12\x19\n\x15MIDPOINT_BETWEEN_EYES\x10\x07\x12\x0c\n\x08NOSE_TIP\x10\x08\x12\r\n\tUPPER_LIP\x10\t\x12\r\n\tLOWER_LIP\x10\n\x12\x0e\n\nMOUTH_LEFT\x10\x0b\x12\x0f\n\x0bMOUTH_RIGHT\x10\x0c\x12\x10\n\x0cMOUTH_CENTER\x10\r\x12\x15\n\x11NOSE_BOTTOM_RIGHT\x10\x0e\x12\x14\n\x10NOSE_BOTTOM_LEFT\x10\x0f\x12\x16\n\x12NOSE_BOTTOM_CENTER\x10\x10\x12\x19\n\x15LEFT_EYE_TOP_BOUNDARY\x10\x11\x12\x19\n\x15LEFT_EYE_RIGHT_CORNER\x10\x12\x12\x1c\n\x18LEFT_EYE_BOTTOM_BOUNDARY\x10\x13\x12\x18\n\x14LEFT_EYE_LEFT_CORNER\x10\x14\x12\x1a\n\x16RIGHT_EYE_TOP_BOUNDARY\x10\x15\x12\x1a\n\x16RIGHT_EYE_RIGHT_CORNER\x10\x16\x12\x1d\n\x19RIGHT_EYE_BOTTOM_BOUNDARY\x10\x17\x12\x19\n\x15RIGHT_EYE_LEFT_CORNER\x10\x18\x12\x1f\n\x1bLEFT_EYEBROW_UPPER_MIDPOINT\x10\x19\x12 \n\x1cRIGHT_EYEBROW_UPPER_MIDPOINT\x10\x1a\x12\x14\n\x10LEFT_EAR_TRAGION\x10\x1b\x12\x15\n\x11RIGHT_EAR_TRAGION\x10\x1c\x12\x12\n\x0eLEFT_EYE_PUPIL\x10\x1d\x12\x13\n\x0fRIGHT_EYE_PUPIL\x10\x1e\x12\x15\n\x11\x46OREHEAD_GLABELLA\x10\x1f\x12\x11\n\rCHIN_GNATHION\x10 \x12\x14\n\x10\x43HIN_LEFT_GONION\x10!\x12\x15\n\x11\x43HIN_RIGHT_GONION\x10""4\n\x0cLocationInfo\x12$\n\x07lat_lng\x18\x01 \x01(\x0b\x32\x13.google.type.LatLng"=\n\x08Property\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t\x12\x14\n\x0cuint64_value\x18\x03 \x01(\x04"\xbc\x02\n\x10\x45ntityAnnotation\x12\x0b\n\x03mid\x18\x01 \x01(\t\x12\x0e\n\x06locale\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\x12\r\n\x05score\x18\x04 \x01(\x02\x12\x12\n\nconfidence\x18\x05 \x01(\x02\x12\x12\n\ntopicality\x18\x06 \x01(\x02\x12\x42\n\rbounding_poly\x18\x07 \x01(\x0b\x32+.google.cloud.vision.v1p2beta1.BoundingPoly\x12>\n\tlocations\x18\x08 \x03(\x0b\x32+.google.cloud.vision.v1p2beta1.LocationInfo\x12;\n\nproperties\x18\t \x03(\x0b\x32\'.google.cloud.vision.v1p2beta1.Property"\xbc\x02\n\x14SafeSearchAnnotation\x12\x38\n\x05\x61\x64ult\x18\x01 \x01(\x0e\x32).google.cloud.vision.v1p2beta1.Likelihood\x12\x38\n\x05spoof\x18\x02 \x01(\x0e\x32).google.cloud.vision.v1p2beta1.Likelihood\x12:\n\x07medical\x18\x03 \x01(\x0e\x32).google.cloud.vision.v1p2beta1.Likelihood\x12;\n\x08violence\x18\x04 \x01(\x0e\x32).google.cloud.vision.v1p2beta1.Likelihood\x12\x37\n\x04racy\x18\t \x01(\x0e\x32).google.cloud.vision.v1p2beta1.Likelihood"a\n\x0bLatLongRect\x12(\n\x0bmin_lat_lng\x18\x01 \x01(\x0b\x32\x13.google.type.LatLng\x12(\n\x0bmax_lat_lng\x18\x02 \x01(\x0b\x32\x13.google.type.LatLng"U\n\tColorInfo\x12!\n\x05\x63olor\x18\x01 \x01(\x0b\x32\x12.google.type.Color\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x16\n\x0epixel_fraction\x18\x03 \x01(\x02"T\n\x18\x44ominantColorsAnnotation\x12\x38\n\x06\x63olors\x18\x01 \x03(\x0b\x32(.google.cloud.vision.v1p2beta1.ColorInfo"c\n\x0fImageProperties\x12P\n\x0f\x64ominant_colors\x18\x01 \x01(\x0b\x32\x37.google.cloud.vision.v1p2beta1.DominantColorsAnnotation"\x7f\n\x08\x43ropHint\x12\x42\n\rbounding_poly\x18\x01 \x01(\x0b\x32+.google.cloud.vision.v1p2beta1.BoundingPoly\x12\x12\n\nconfidence\x18\x02 \x01(\x02\x12\x1b\n\x13importance_fraction\x18\x03 \x01(\x02"R\n\x13\x43ropHintsAnnotation\x12;\n\ncrop_hints\x18\x01 \x03(\x0b\x32\'.google.cloud.vision.v1p2beta1.CropHint"(\n\x0f\x43ropHintsParams\x12\x15\n\raspect_ratios\x18\x01 \x03(\x02"1\n\x12WebDetectionParams\x12\x1b\n\x13include_geo_results\x18\x02 \x01(\x08"\x85\x02\n\x0cImageContext\x12\x41\n\rlat_long_rect\x18\x01 \x01(\x0b\x32*.google.cloud.vision.v1p2beta1.LatLongRect\x12\x16\n\x0elanguage_hints\x18\x02 \x03(\t\x12I\n\x11\x63rop_hints_params\x18\x04 \x01(\x0b\x32..google.cloud.vision.v1p2beta1.CropHintsParams\x12O\n\x14web_detection_params\x18\x06 \x01(\x0b\x32\x31.google.cloud.vision.v1p2beta1.WebDetectionParams"\xc9\x01\n\x14\x41nnotateImageRequest\x12\x33\n\x05image\x18\x01 \x01(\x0b\x32$.google.cloud.vision.v1p2beta1.Image\x12\x38\n\x08\x66\x65\x61tures\x18\x02 \x03(\x0b\x32&.google.cloud.vision.v1p2beta1.Feature\x12\x42\n\rimage_context\x18\x03 \x01(\x0b\x32+.google.cloud.vision.v1p2beta1.ImageContext":\n\x16ImageAnnotationContext\x12\x0b\n\x03uri\x18\x01 \x01(\t\x12\x13\n\x0bpage_number\x18\x02 \x01(\x05"\x8a\x07\n\x15\x41nnotateImageResponse\x12G\n\x10\x66\x61\x63\x65_annotations\x18\x01 \x03(\x0b\x32-.google.cloud.vision.v1p2beta1.FaceAnnotation\x12M\n\x14landmark_annotations\x18\x02 \x03(\x0b\x32/.google.cloud.vision.v1p2beta1.EntityAnnotation\x12I\n\x10logo_annotations\x18\x03 \x03(\x0b\x32/.google.cloud.vision.v1p2beta1.EntityAnnotation\x12J\n\x11label_annotations\x18\x04 \x03(\x0b\x32/.google.cloud.vision.v1p2beta1.EntityAnnotation\x12I\n\x10text_annotations\x18\x05 \x03(\x0b\x32/.google.cloud.vision.v1p2beta1.EntityAnnotation\x12K\n\x14\x66ull_text_annotation\x18\x0c \x01(\x0b\x32-.google.cloud.vision.v1p2beta1.TextAnnotation\x12S\n\x16safe_search_annotation\x18\x06 \x01(\x0b\x32\x33.google.cloud.vision.v1p2beta1.SafeSearchAnnotation\x12S\n\x1bimage_properties_annotation\x18\x08 \x01(\x0b\x32..google.cloud.vision.v1p2beta1.ImageProperties\x12Q\n\x15\x63rop_hints_annotation\x18\x0b \x01(\x0b\x32\x32.google.cloud.vision.v1p2beta1.CropHintsAnnotation\x12\x42\n\rweb_detection\x18\r \x01(\x0b\x32+.google.cloud.vision.v1p2beta1.WebDetection\x12!\n\x05\x65rror\x18\t \x01(\x0b\x32\x12.google.rpc.Status\x12\x46\n\x07\x63ontext\x18\x15 \x01(\x0b\x32\x35.google.cloud.vision.v1p2beta1.ImageAnnotationContext"\xa1\x01\n\x14\x41nnotateFileResponse\x12@\n\x0cinput_config\x18\x01 \x01(\x0b\x32*.google.cloud.vision.v1p2beta1.InputConfig\x12G\n\tresponses\x18\x02 \x03(\x0b\x32\x34.google.cloud.vision.v1p2beta1.AnnotateImageResponse"h\n\x1a\x42\x61tchAnnotateImagesRequest\x12J\n\x08requests\x18\x01 \x03(\x0b\x32\x33.google.cloud.vision.v1p2beta1.AnnotateImageRequestB\x03\xe0\x41\x02"f\n\x1b\x42\x61tchAnnotateImagesResponse\x12G\n\tresponses\x18\x01 \x03(\x0b\x32\x34.google.cloud.vision.v1p2beta1.AnnotateImageResponse"\x9e\x02\n\x18\x41syncAnnotateFileRequest\x12@\n\x0cinput_config\x18\x01 \x01(\x0b\x32*.google.cloud.vision.v1p2beta1.InputConfig\x12\x38\n\x08\x66\x65\x61tures\x18\x02 \x03(\x0b\x32&.google.cloud.vision.v1p2beta1.Feature\x12\x42\n\rimage_context\x18\x03 \x01(\x0b\x32+.google.cloud.vision.v1p2beta1.ImageContext\x12\x42\n\routput_config\x18\x04 \x01(\x0b\x32+.google.cloud.vision.v1p2beta1.OutputConfig"_\n\x19\x41syncAnnotateFileResponse\x12\x42\n\routput_config\x18\x01 \x01(\x0b\x32+.google.cloud.vision.v1p2beta1.OutputConfig"p\n\x1e\x41syncBatchAnnotateFilesRequest\x12N\n\x08requests\x18\x01 \x03(\x0b\x32\x37.google.cloud.vision.v1p2beta1.AsyncAnnotateFileRequestB\x03\xe0\x41\x02"n\n\x1f\x41syncBatchAnnotateFilesResponse\x12K\n\tresponses\x18\x01 \x03(\x0b\x32\x38.google.cloud.vision.v1p2beta1.AsyncAnnotateFileResponse"^\n\x0bInputConfig\x12<\n\ngcs_source\x18\x01 \x01(\x0b\x32(.google.cloud.vision.v1p2beta1.GcsSource\x12\x11\n\tmime_type\x18\x02 \x01(\t"j\n\x0cOutputConfig\x12\x46\n\x0fgcs_destination\x18\x01 \x01(\x0b\x32-.google.cloud.vision.v1p2beta1.GcsDestination\x12\x12\n\nbatch_size\x18\x02 \x01(\x05"\x18\n\tGcsSource\x12\x0b\n\x03uri\x18\x01 \x01(\t"\x1d\n\x0eGcsDestination\x12\x0b\n\x03uri\x18\x01 \x01(\t"\x8f\x02\n\x11OperationMetadata\x12\x45\n\x05state\x18\x01 \x01(\x0e\x32\x36.google.cloud.vision.v1p2beta1.OperationMetadata.State\x12/\n\x0b\x63reate_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"Q\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0b\n\x07\x43REATED\x10\x01\x12\x0b\n\x07RUNNING\x10\x02\x12\x08\n\x04\x44ONE\x10\x03\x12\r\n\tCANCELLED\x10\x04*e\n\nLikelihood\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x11\n\rVERY_UNLIKELY\x10\x01\x12\x0c\n\x08UNLIKELY\x10\x02\x12\x0c\n\x08POSSIBLE\x10\x03\x12\n\n\x06LIKELY\x10\x04\x12\x0f\n\x0bVERY_LIKELY\x10\x05\x32\xb5\x04\n\x0eImageAnnotator\x12\xbe\x01\n\x13\x42\x61tchAnnotateImages\x12\x39.google.cloud.vision.v1p2beta1.BatchAnnotateImagesRequest\x1a:.google.cloud.vision.v1p2beta1.BatchAnnotateImagesResponse"0\x82\xd3\xe4\x93\x02\x1f"\x1a/v1p2beta1/images:annotate:\x01*\xda\x41\x08requests\x12\xe9\x01\n\x17\x41syncBatchAnnotateFiles\x12=.google.cloud.vision.v1p2beta1.AsyncBatchAnnotateFilesRequest\x1a\x1d.google.longrunning.Operation"p\x82\xd3\xe4\x93\x02("#/v1p2beta1/files:asyncBatchAnnotate:\x01*\xda\x41\x08requests\xca\x41\x34\n\x1f\x41syncBatchAnnotateFilesResponse\x12\x11OperationMetadata\x1av\xca\x41\x15vision.googleapis.com\xd2\x41[https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-visionB\x82\x01\n!com.google.cloud.vision.v1p2beta1B\x13ImageAnnotatorProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p2beta1;vision\xf8\x01\x01\x62\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_geometry__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_text__annotation__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_web__detection__pb2.DESCRIPTOR, - google_dot_longrunning_dot_operations__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_rpc_dot_status__pb2.DESCRIPTOR, - google_dot_type_dot_color__pb2.DESCRIPTOR, - google_dot_type_dot_latlng__pb2.DESCRIPTOR, - ], -) - -_LIKELIHOOD = _descriptor.EnumDescriptor( - name="Likelihood", - full_name="google.cloud.vision.v1p2beta1.Likelihood", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNKNOWN", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="VERY_UNLIKELY", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="UNLIKELY", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="POSSIBLE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LIKELY", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="VERY_LIKELY", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=7207, - serialized_end=7308, -) -_sym_db.RegisterEnumDescriptor(_LIKELIHOOD) - -Likelihood = enum_type_wrapper.EnumTypeWrapper(_LIKELIHOOD) -UNKNOWN = 0 -VERY_UNLIKELY = 1 -UNLIKELY = 2 -POSSIBLE = 3 -LIKELY = 4 -VERY_LIKELY = 5 - - -_FEATURE_TYPE = _descriptor.EnumDescriptor( - name="Type", - full_name="google.cloud.vision.v1p2beta1.Feature.Type", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="TYPE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FACE_DETECTION", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LANDMARK_DETECTION", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LOGO_DETECTION", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LABEL_DETECTION", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="TEXT_DETECTION", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DOCUMENT_TEXT_DETECTION", - index=6, - number=11, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SAFE_SEARCH_DETECTION", - index=7, - number=6, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="IMAGE_PROPERTIES", - index=8, - number=7, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CROP_HINTS", - index=9, - number=9, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="WEB_DETECTION", - index=10, - number=10, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=602, - serialized_end=848, -) -_sym_db.RegisterEnumDescriptor(_FEATURE_TYPE) - -_FACEANNOTATION_LANDMARK_TYPE = _descriptor.EnumDescriptor( - name="Type", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.Landmark.Type", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNKNOWN_LANDMARK", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_OF_LEFT_EYEBROW", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_OF_LEFT_EYEBROW", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_OF_RIGHT_EYEBROW", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_OF_RIGHT_EYEBROW", - index=6, - number=6, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MIDPOINT_BETWEEN_EYES", - index=7, - number=7, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NOSE_TIP", - index=8, - number=8, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="UPPER_LIP", - index=9, - number=9, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LOWER_LIP", - index=10, - number=10, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MOUTH_LEFT", - index=11, - number=11, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MOUTH_RIGHT", - index=12, - number=12, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MOUTH_CENTER", - index=13, - number=13, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NOSE_BOTTOM_RIGHT", - index=14, - number=14, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NOSE_BOTTOM_LEFT", - index=15, - number=15, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NOSE_BOTTOM_CENTER", - index=16, - number=16, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_TOP_BOUNDARY", - index=17, - number=17, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_RIGHT_CORNER", - index=18, - number=18, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_BOTTOM_BOUNDARY", - index=19, - number=19, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_LEFT_CORNER", - index=20, - number=20, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_TOP_BOUNDARY", - index=21, - number=21, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_RIGHT_CORNER", - index=22, - number=22, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_BOTTOM_BOUNDARY", - index=23, - number=23, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_LEFT_CORNER", - index=24, - number=24, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYEBROW_UPPER_MIDPOINT", - index=25, - number=25, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYEBROW_UPPER_MIDPOINT", - index=26, - number=26, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EAR_TRAGION", - index=27, - number=27, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EAR_TRAGION", - index=28, - number=28, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_PUPIL", - index=29, - number=29, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_PUPIL", - index=30, - number=30, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FOREHEAD_GLABELLA", - index=31, - number=31, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CHIN_GNATHION", - index=32, - number=32, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CHIN_LEFT_GONION", - index=33, - number=33, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CHIN_RIGHT_GONION", - index=34, - number=34, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=1993, - serialized_end=2813, -) -_sym_db.RegisterEnumDescriptor(_FACEANNOTATION_LANDMARK_TYPE) - -_OPERATIONMETADATA_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.vision.v1p2beta1.OperationMetadata.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CREATED", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RUNNING", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DONE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLED", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=7124, - serialized_end=7205, -) -_sym_db.RegisterEnumDescriptor(_OPERATIONMETADATA_STATE) - - -_FEATURE = _descriptor.Descriptor( - name="Feature", - full_name="google.cloud.vision.v1p2beta1.Feature", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="type", - full_name="google.cloud.vision.v1p2beta1.Feature.type", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="max_results", - full_name="google.cloud.vision.v1p2beta1.Feature.max_results", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="model", - full_name="google.cloud.vision.v1p2beta1.Feature.model", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_FEATURE_TYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=495, - serialized_end=848, -) - - -_IMAGESOURCE = _descriptor.Descriptor( - name="ImageSource", - full_name="google.cloud.vision.v1p2beta1.ImageSource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_image_uri", - full_name="google.cloud.vision.v1p2beta1.ImageSource.gcs_image_uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_uri", - full_name="google.cloud.vision.v1p2beta1.ImageSource.image_uri", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=850, - serialized_end=905, -) - - -_IMAGE = _descriptor.Descriptor( - name="Image", - full_name="google.cloud.vision.v1p2beta1.Image", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="content", - full_name="google.cloud.vision.v1p2beta1.Image.content", - index=0, - number=1, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"", - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source", - full_name="google.cloud.vision.v1p2beta1.Image.source", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=907, - serialized_end=991, -) - - -_FACEANNOTATION_LANDMARK = _descriptor.Descriptor( - name="Landmark", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.Landmark", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="type", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.Landmark.type", - index=0, - number=3, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="position", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.Landmark.position", - index=1, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_FACEANNOTATION_LANDMARK_TYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1846, - serialized_end=2813, -) - -_FACEANNOTATION = _descriptor.Descriptor( - name="FaceAnnotation", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.bounding_poly", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="fd_bounding_poly", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.fd_bounding_poly", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="landmarks", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.landmarks", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="roll_angle", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.roll_angle", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="pan_angle", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.pan_angle", - index=4, - number=5, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="tilt_angle", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.tilt_angle", - index=5, - number=6, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="detection_confidence", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.detection_confidence", - index=6, - number=7, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="landmarking_confidence", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.landmarking_confidence", - index=7, - number=8, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="joy_likelihood", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.joy_likelihood", - index=8, - number=9, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="sorrow_likelihood", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.sorrow_likelihood", - index=9, - number=10, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="anger_likelihood", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.anger_likelihood", - index=10, - number=11, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="surprise_likelihood", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.surprise_likelihood", - index=11, - number=12, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="under_exposed_likelihood", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.under_exposed_likelihood", - index=12, - number=13, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="blurred_likelihood", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.blurred_likelihood", - index=13, - number=14, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="headwear_likelihood", - full_name="google.cloud.vision.v1p2beta1.FaceAnnotation.headwear_likelihood", - index=14, - number=15, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_FACEANNOTATION_LANDMARK,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=994, - serialized_end=2813, -) - - -_LOCATIONINFO = _descriptor.Descriptor( - name="LocationInfo", - full_name="google.cloud.vision.v1p2beta1.LocationInfo", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="lat_lng", - full_name="google.cloud.vision.v1p2beta1.LocationInfo.lat_lng", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2815, - serialized_end=2867, -) - - -_PROPERTY = _descriptor.Descriptor( - name="Property", - full_name="google.cloud.vision.v1p2beta1.Property", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p2beta1.Property.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.vision.v1p2beta1.Property.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="uint64_value", - full_name="google.cloud.vision.v1p2beta1.Property.uint64_value", - index=2, - number=3, - type=4, - cpp_type=4, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2869, - serialized_end=2930, -) - - -_ENTITYANNOTATION = _descriptor.Descriptor( - name="EntityAnnotation", - full_name="google.cloud.vision.v1p2beta1.EntityAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="mid", - full_name="google.cloud.vision.v1p2beta1.EntityAnnotation.mid", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="locale", - full_name="google.cloud.vision.v1p2beta1.EntityAnnotation.locale", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.vision.v1p2beta1.EntityAnnotation.description", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p2beta1.EntityAnnotation.score", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p2beta1.EntityAnnotation.confidence", - index=4, - number=5, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="topicality", - full_name="google.cloud.vision.v1p2beta1.EntityAnnotation.topicality", - index=5, - number=6, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p2beta1.EntityAnnotation.bounding_poly", - index=6, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="locations", - full_name="google.cloud.vision.v1p2beta1.EntityAnnotation.locations", - index=7, - number=8, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="properties", - full_name="google.cloud.vision.v1p2beta1.EntityAnnotation.properties", - index=8, - number=9, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2933, - serialized_end=3249, -) - - -_SAFESEARCHANNOTATION = _descriptor.Descriptor( - name="SafeSearchAnnotation", - full_name="google.cloud.vision.v1p2beta1.SafeSearchAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="adult", - full_name="google.cloud.vision.v1p2beta1.SafeSearchAnnotation.adult", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="spoof", - full_name="google.cloud.vision.v1p2beta1.SafeSearchAnnotation.spoof", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="medical", - full_name="google.cloud.vision.v1p2beta1.SafeSearchAnnotation.medical", - index=2, - number=3, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="violence", - full_name="google.cloud.vision.v1p2beta1.SafeSearchAnnotation.violence", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="racy", - full_name="google.cloud.vision.v1p2beta1.SafeSearchAnnotation.racy", - index=4, - number=9, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3252, - serialized_end=3568, -) - - -_LATLONGRECT = _descriptor.Descriptor( - name="LatLongRect", - full_name="google.cloud.vision.v1p2beta1.LatLongRect", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="min_lat_lng", - full_name="google.cloud.vision.v1p2beta1.LatLongRect.min_lat_lng", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="max_lat_lng", - full_name="google.cloud.vision.v1p2beta1.LatLongRect.max_lat_lng", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3570, - serialized_end=3667, -) - - -_COLORINFO = _descriptor.Descriptor( - name="ColorInfo", - full_name="google.cloud.vision.v1p2beta1.ColorInfo", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="color", - full_name="google.cloud.vision.v1p2beta1.ColorInfo.color", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p2beta1.ColorInfo.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="pixel_fraction", - full_name="google.cloud.vision.v1p2beta1.ColorInfo.pixel_fraction", - index=2, - number=3, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3669, - serialized_end=3754, -) - - -_DOMINANTCOLORSANNOTATION = _descriptor.Descriptor( - name="DominantColorsAnnotation", - full_name="google.cloud.vision.v1p2beta1.DominantColorsAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="colors", - full_name="google.cloud.vision.v1p2beta1.DominantColorsAnnotation.colors", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3756, - serialized_end=3840, -) - - -_IMAGEPROPERTIES = _descriptor.Descriptor( - name="ImageProperties", - full_name="google.cloud.vision.v1p2beta1.ImageProperties", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="dominant_colors", - full_name="google.cloud.vision.v1p2beta1.ImageProperties.dominant_colors", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3842, - serialized_end=3941, -) - - -_CROPHINT = _descriptor.Descriptor( - name="CropHint", - full_name="google.cloud.vision.v1p2beta1.CropHint", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p2beta1.CropHint.bounding_poly", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p2beta1.CropHint.confidence", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="importance_fraction", - full_name="google.cloud.vision.v1p2beta1.CropHint.importance_fraction", - index=2, - number=3, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3943, - serialized_end=4070, -) - - -_CROPHINTSANNOTATION = _descriptor.Descriptor( - name="CropHintsAnnotation", - full_name="google.cloud.vision.v1p2beta1.CropHintsAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="crop_hints", - full_name="google.cloud.vision.v1p2beta1.CropHintsAnnotation.crop_hints", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4072, - serialized_end=4154, -) - - -_CROPHINTSPARAMS = _descriptor.Descriptor( - name="CropHintsParams", - full_name="google.cloud.vision.v1p2beta1.CropHintsParams", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="aspect_ratios", - full_name="google.cloud.vision.v1p2beta1.CropHintsParams.aspect_ratios", - index=0, - number=1, - type=2, - cpp_type=6, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4156, - serialized_end=4196, -) - - -_WEBDETECTIONPARAMS = _descriptor.Descriptor( - name="WebDetectionParams", - full_name="google.cloud.vision.v1p2beta1.WebDetectionParams", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="include_geo_results", - full_name="google.cloud.vision.v1p2beta1.WebDetectionParams.include_geo_results", - index=0, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4198, - serialized_end=4247, -) - - -_IMAGECONTEXT = _descriptor.Descriptor( - name="ImageContext", - full_name="google.cloud.vision.v1p2beta1.ImageContext", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="lat_long_rect", - full_name="google.cloud.vision.v1p2beta1.ImageContext.lat_long_rect", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="language_hints", - full_name="google.cloud.vision.v1p2beta1.ImageContext.language_hints", - index=1, - number=2, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="crop_hints_params", - full_name="google.cloud.vision.v1p2beta1.ImageContext.crop_hints_params", - index=2, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="web_detection_params", - full_name="google.cloud.vision.v1p2beta1.ImageContext.web_detection_params", - index=3, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4250, - serialized_end=4511, -) - - -_ANNOTATEIMAGEREQUEST = _descriptor.Descriptor( - name="AnnotateImageRequest", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="image", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageRequest.image", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="features", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageRequest.features", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_context", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageRequest.image_context", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4514, - serialized_end=4715, -) - - -_IMAGEANNOTATIONCONTEXT = _descriptor.Descriptor( - name="ImageAnnotationContext", - full_name="google.cloud.vision.v1p2beta1.ImageAnnotationContext", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="uri", - full_name="google.cloud.vision.v1p2beta1.ImageAnnotationContext.uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_number", - full_name="google.cloud.vision.v1p2beta1.ImageAnnotationContext.page_number", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4717, - serialized_end=4775, -) - - -_ANNOTATEIMAGERESPONSE = _descriptor.Descriptor( - name="AnnotateImageResponse", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="face_annotations", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageResponse.face_annotations", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="landmark_annotations", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageResponse.landmark_annotations", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="logo_annotations", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageResponse.logo_annotations", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="label_annotations", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageResponse.label_annotations", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="text_annotations", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageResponse.text_annotations", - index=4, - number=5, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="full_text_annotation", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageResponse.full_text_annotation", - index=5, - number=12, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="safe_search_annotation", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageResponse.safe_search_annotation", - index=6, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_properties_annotation", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageResponse.image_properties_annotation", - index=7, - number=8, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="crop_hints_annotation", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageResponse.crop_hints_annotation", - index=8, - number=11, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="web_detection", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageResponse.web_detection", - index=9, - number=13, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="error", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageResponse.error", - index=10, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="context", - full_name="google.cloud.vision.v1p2beta1.AnnotateImageResponse.context", - index=11, - number=21, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4778, - serialized_end=5684, -) - - -_ANNOTATEFILERESPONSE = _descriptor.Descriptor( - name="AnnotateFileResponse", - full_name="google.cloud.vision.v1p2beta1.AnnotateFileResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="input_config", - full_name="google.cloud.vision.v1p2beta1.AnnotateFileResponse.input_config", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="responses", - full_name="google.cloud.vision.v1p2beta1.AnnotateFileResponse.responses", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5687, - serialized_end=5848, -) - - -_BATCHANNOTATEIMAGESREQUEST = _descriptor.Descriptor( - name="BatchAnnotateImagesRequest", - full_name="google.cloud.vision.v1p2beta1.BatchAnnotateImagesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="requests", - full_name="google.cloud.vision.v1p2beta1.BatchAnnotateImagesRequest.requests", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5850, - serialized_end=5954, -) - - -_BATCHANNOTATEIMAGESRESPONSE = _descriptor.Descriptor( - name="BatchAnnotateImagesResponse", - full_name="google.cloud.vision.v1p2beta1.BatchAnnotateImagesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="responses", - full_name="google.cloud.vision.v1p2beta1.BatchAnnotateImagesResponse.responses", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5956, - serialized_end=6058, -) - - -_ASYNCANNOTATEFILEREQUEST = _descriptor.Descriptor( - name="AsyncAnnotateFileRequest", - full_name="google.cloud.vision.v1p2beta1.AsyncAnnotateFileRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="input_config", - full_name="google.cloud.vision.v1p2beta1.AsyncAnnotateFileRequest.input_config", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="features", - full_name="google.cloud.vision.v1p2beta1.AsyncAnnotateFileRequest.features", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_context", - full_name="google.cloud.vision.v1p2beta1.AsyncAnnotateFileRequest.image_context", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="output_config", - full_name="google.cloud.vision.v1p2beta1.AsyncAnnotateFileRequest.output_config", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6061, - serialized_end=6347, -) - - -_ASYNCANNOTATEFILERESPONSE = _descriptor.Descriptor( - name="AsyncAnnotateFileResponse", - full_name="google.cloud.vision.v1p2beta1.AsyncAnnotateFileResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="output_config", - full_name="google.cloud.vision.v1p2beta1.AsyncAnnotateFileResponse.output_config", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6349, - serialized_end=6444, -) - - -_ASYNCBATCHANNOTATEFILESREQUEST = _descriptor.Descriptor( - name="AsyncBatchAnnotateFilesRequest", - full_name="google.cloud.vision.v1p2beta1.AsyncBatchAnnotateFilesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="requests", - full_name="google.cloud.vision.v1p2beta1.AsyncBatchAnnotateFilesRequest.requests", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6446, - serialized_end=6558, -) - - -_ASYNCBATCHANNOTATEFILESRESPONSE = _descriptor.Descriptor( - name="AsyncBatchAnnotateFilesResponse", - full_name="google.cloud.vision.v1p2beta1.AsyncBatchAnnotateFilesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="responses", - full_name="google.cloud.vision.v1p2beta1.AsyncBatchAnnotateFilesResponse.responses", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6560, - serialized_end=6670, -) - - -_INPUTCONFIG = _descriptor.Descriptor( - name="InputConfig", - full_name="google.cloud.vision.v1p2beta1.InputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_source", - full_name="google.cloud.vision.v1p2beta1.InputConfig.gcs_source", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="mime_type", - full_name="google.cloud.vision.v1p2beta1.InputConfig.mime_type", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6672, - serialized_end=6766, -) - - -_OUTPUTCONFIG = _descriptor.Descriptor( - name="OutputConfig", - full_name="google.cloud.vision.v1p2beta1.OutputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_destination", - full_name="google.cloud.vision.v1p2beta1.OutputConfig.gcs_destination", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="batch_size", - full_name="google.cloud.vision.v1p2beta1.OutputConfig.batch_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6768, - serialized_end=6874, -) - - -_GCSSOURCE = _descriptor.Descriptor( - name="GcsSource", - full_name="google.cloud.vision.v1p2beta1.GcsSource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="uri", - full_name="google.cloud.vision.v1p2beta1.GcsSource.uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6876, - serialized_end=6900, -) - - -_GCSDESTINATION = _descriptor.Descriptor( - name="GcsDestination", - full_name="google.cloud.vision.v1p2beta1.GcsDestination", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="uri", - full_name="google.cloud.vision.v1p2beta1.GcsDestination.uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6902, - serialized_end=6931, -) - - -_OPERATIONMETADATA = _descriptor.Descriptor( - name="OperationMetadata", - full_name="google.cloud.vision.v1p2beta1.OperationMetadata", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.vision.v1p2beta1.OperationMetadata.state", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="create_time", - full_name="google.cloud.vision.v1p2beta1.OperationMetadata.create_time", - index=1, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_time", - full_name="google.cloud.vision.v1p2beta1.OperationMetadata.update_time", - index=2, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_OPERATIONMETADATA_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6934, - serialized_end=7205, -) - -_FEATURE.fields_by_name["type"].enum_type = _FEATURE_TYPE -_FEATURE_TYPE.containing_type = _FEATURE -_IMAGE.fields_by_name["source"].message_type = _IMAGESOURCE -_FACEANNOTATION_LANDMARK.fields_by_name[ - "type" -].enum_type = _FACEANNOTATION_LANDMARK_TYPE -_FACEANNOTATION_LANDMARK.fields_by_name[ - "position" -].message_type = ( - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_geometry__pb2._POSITION -) -_FACEANNOTATION_LANDMARK.containing_type = _FACEANNOTATION -_FACEANNOTATION_LANDMARK_TYPE.containing_type = _FACEANNOTATION_LANDMARK -_FACEANNOTATION.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_FACEANNOTATION.fields_by_name[ - "fd_bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_FACEANNOTATION.fields_by_name["landmarks"].message_type = _FACEANNOTATION_LANDMARK -_FACEANNOTATION.fields_by_name["joy_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["sorrow_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["anger_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["surprise_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["under_exposed_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["blurred_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["headwear_likelihood"].enum_type = _LIKELIHOOD -_LOCATIONINFO.fields_by_name[ - "lat_lng" -].message_type = google_dot_type_dot_latlng__pb2._LATLNG -_ENTITYANNOTATION.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_ENTITYANNOTATION.fields_by_name["locations"].message_type = _LOCATIONINFO -_ENTITYANNOTATION.fields_by_name["properties"].message_type = _PROPERTY -_SAFESEARCHANNOTATION.fields_by_name["adult"].enum_type = _LIKELIHOOD -_SAFESEARCHANNOTATION.fields_by_name["spoof"].enum_type = _LIKELIHOOD -_SAFESEARCHANNOTATION.fields_by_name["medical"].enum_type = _LIKELIHOOD -_SAFESEARCHANNOTATION.fields_by_name["violence"].enum_type = _LIKELIHOOD -_SAFESEARCHANNOTATION.fields_by_name["racy"].enum_type = _LIKELIHOOD -_LATLONGRECT.fields_by_name[ - "min_lat_lng" -].message_type = google_dot_type_dot_latlng__pb2._LATLNG -_LATLONGRECT.fields_by_name[ - "max_lat_lng" -].message_type = google_dot_type_dot_latlng__pb2._LATLNG -_COLORINFO.fields_by_name["color"].message_type = google_dot_type_dot_color__pb2._COLOR -_DOMINANTCOLORSANNOTATION.fields_by_name["colors"].message_type = _COLORINFO -_IMAGEPROPERTIES.fields_by_name[ - "dominant_colors" -].message_type = _DOMINANTCOLORSANNOTATION -_CROPHINT.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_CROPHINTSANNOTATION.fields_by_name["crop_hints"].message_type = _CROPHINT -_IMAGECONTEXT.fields_by_name["lat_long_rect"].message_type = _LATLONGRECT -_IMAGECONTEXT.fields_by_name["crop_hints_params"].message_type = _CROPHINTSPARAMS -_IMAGECONTEXT.fields_by_name["web_detection_params"].message_type = _WEBDETECTIONPARAMS -_ANNOTATEIMAGEREQUEST.fields_by_name["image"].message_type = _IMAGE -_ANNOTATEIMAGEREQUEST.fields_by_name["features"].message_type = _FEATURE -_ANNOTATEIMAGEREQUEST.fields_by_name["image_context"].message_type = _IMAGECONTEXT -_ANNOTATEIMAGERESPONSE.fields_by_name["face_annotations"].message_type = _FACEANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "landmark_annotations" -].message_type = _ENTITYANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "logo_annotations" -].message_type = _ENTITYANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "label_annotations" -].message_type = _ENTITYANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "text_annotations" -].message_type = _ENTITYANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "full_text_annotation" -].message_type = ( - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_text__annotation__pb2._TEXTANNOTATION -) -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "safe_search_annotation" -].message_type = _SAFESEARCHANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "image_properties_annotation" -].message_type = _IMAGEPROPERTIES -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "crop_hints_annotation" -].message_type = _CROPHINTSANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "web_detection" -].message_type = ( - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_web__detection__pb2._WEBDETECTION -) -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "error" -].message_type = google_dot_rpc_dot_status__pb2._STATUS -_ANNOTATEIMAGERESPONSE.fields_by_name["context"].message_type = _IMAGEANNOTATIONCONTEXT -_ANNOTATEFILERESPONSE.fields_by_name["input_config"].message_type = _INPUTCONFIG -_ANNOTATEFILERESPONSE.fields_by_name["responses"].message_type = _ANNOTATEIMAGERESPONSE -_BATCHANNOTATEIMAGESREQUEST.fields_by_name[ - "requests" -].message_type = _ANNOTATEIMAGEREQUEST -_BATCHANNOTATEIMAGESRESPONSE.fields_by_name[ - "responses" -].message_type = _ANNOTATEIMAGERESPONSE -_ASYNCANNOTATEFILEREQUEST.fields_by_name["input_config"].message_type = _INPUTCONFIG -_ASYNCANNOTATEFILEREQUEST.fields_by_name["features"].message_type = _FEATURE -_ASYNCANNOTATEFILEREQUEST.fields_by_name["image_context"].message_type = _IMAGECONTEXT -_ASYNCANNOTATEFILEREQUEST.fields_by_name["output_config"].message_type = _OUTPUTCONFIG -_ASYNCANNOTATEFILERESPONSE.fields_by_name["output_config"].message_type = _OUTPUTCONFIG -_ASYNCBATCHANNOTATEFILESREQUEST.fields_by_name[ - "requests" -].message_type = _ASYNCANNOTATEFILEREQUEST -_ASYNCBATCHANNOTATEFILESRESPONSE.fields_by_name[ - "responses" -].message_type = _ASYNCANNOTATEFILERESPONSE -_INPUTCONFIG.fields_by_name["gcs_source"].message_type = _GCSSOURCE -_OUTPUTCONFIG.fields_by_name["gcs_destination"].message_type = _GCSDESTINATION -_OPERATIONMETADATA.fields_by_name["state"].enum_type = _OPERATIONMETADATA_STATE -_OPERATIONMETADATA.fields_by_name[ - "create_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_OPERATIONMETADATA.fields_by_name[ - "update_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_OPERATIONMETADATA_STATE.containing_type = _OPERATIONMETADATA -DESCRIPTOR.message_types_by_name["Feature"] = _FEATURE -DESCRIPTOR.message_types_by_name["ImageSource"] = _IMAGESOURCE -DESCRIPTOR.message_types_by_name["Image"] = _IMAGE -DESCRIPTOR.message_types_by_name["FaceAnnotation"] = _FACEANNOTATION -DESCRIPTOR.message_types_by_name["LocationInfo"] = _LOCATIONINFO -DESCRIPTOR.message_types_by_name["Property"] = _PROPERTY -DESCRIPTOR.message_types_by_name["EntityAnnotation"] = _ENTITYANNOTATION -DESCRIPTOR.message_types_by_name["SafeSearchAnnotation"] = _SAFESEARCHANNOTATION -DESCRIPTOR.message_types_by_name["LatLongRect"] = _LATLONGRECT -DESCRIPTOR.message_types_by_name["ColorInfo"] = _COLORINFO -DESCRIPTOR.message_types_by_name["DominantColorsAnnotation"] = _DOMINANTCOLORSANNOTATION -DESCRIPTOR.message_types_by_name["ImageProperties"] = _IMAGEPROPERTIES -DESCRIPTOR.message_types_by_name["CropHint"] = _CROPHINT -DESCRIPTOR.message_types_by_name["CropHintsAnnotation"] = _CROPHINTSANNOTATION -DESCRIPTOR.message_types_by_name["CropHintsParams"] = _CROPHINTSPARAMS -DESCRIPTOR.message_types_by_name["WebDetectionParams"] = _WEBDETECTIONPARAMS -DESCRIPTOR.message_types_by_name["ImageContext"] = _IMAGECONTEXT -DESCRIPTOR.message_types_by_name["AnnotateImageRequest"] = _ANNOTATEIMAGEREQUEST -DESCRIPTOR.message_types_by_name["ImageAnnotationContext"] = _IMAGEANNOTATIONCONTEXT -DESCRIPTOR.message_types_by_name["AnnotateImageResponse"] = _ANNOTATEIMAGERESPONSE -DESCRIPTOR.message_types_by_name["AnnotateFileResponse"] = _ANNOTATEFILERESPONSE -DESCRIPTOR.message_types_by_name[ - "BatchAnnotateImagesRequest" -] = _BATCHANNOTATEIMAGESREQUEST -DESCRIPTOR.message_types_by_name[ - "BatchAnnotateImagesResponse" -] = _BATCHANNOTATEIMAGESRESPONSE -DESCRIPTOR.message_types_by_name["AsyncAnnotateFileRequest"] = _ASYNCANNOTATEFILEREQUEST -DESCRIPTOR.message_types_by_name[ - "AsyncAnnotateFileResponse" -] = _ASYNCANNOTATEFILERESPONSE -DESCRIPTOR.message_types_by_name[ - "AsyncBatchAnnotateFilesRequest" -] = _ASYNCBATCHANNOTATEFILESREQUEST -DESCRIPTOR.message_types_by_name[ - "AsyncBatchAnnotateFilesResponse" -] = _ASYNCBATCHANNOTATEFILESRESPONSE -DESCRIPTOR.message_types_by_name["InputConfig"] = _INPUTCONFIG -DESCRIPTOR.message_types_by_name["OutputConfig"] = _OUTPUTCONFIG -DESCRIPTOR.message_types_by_name["GcsSource"] = _GCSSOURCE -DESCRIPTOR.message_types_by_name["GcsDestination"] = _GCSDESTINATION -DESCRIPTOR.message_types_by_name["OperationMetadata"] = _OPERATIONMETADATA -DESCRIPTOR.enum_types_by_name["Likelihood"] = _LIKELIHOOD -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Feature = _reflection.GeneratedProtocolMessageType( - "Feature", - (_message.Message,), - { - "DESCRIPTOR": _FEATURE, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """The type of Google Cloud Vision API detection to perform, and the - maximum number of results to return for that type. Multiple - ``Feature`` objects can be specified in the ``features`` list. - - Attributes: - type: - The feature type. - max_results: - Maximum number of results of this type. Does not apply to - ``TEXT_DETECTION``, ``DOCUMENT_TEXT_DETECTION``, or - ``CROP_HINTS``. - model: - Model to use for the feature. Supported values: - “builtin/stable” (the default if unset) and “builtin/latest”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.Feature) - }, -) -_sym_db.RegisterMessage(Feature) - -ImageSource = _reflection.GeneratedProtocolMessageType( - "ImageSource", - (_message.Message,), - { - "DESCRIPTOR": _IMAGESOURCE, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """External image source (Google Cloud Storage or web URL image - location). - - Attributes: - gcs_image_uri: - \ **Use ``image_uri`` instead.** The Google Cloud Storage URI - of the form ``gs://bucket_name/object_name``. Object - versioning is not supported. See `Google Cloud Storage Request - URIs `__ - for more info. - image_uri: - The URI of the source image. Can be either: 1. A Google Cloud - Storage URI of the form ``gs://bucket_name/object_name``. - Object versioning is not supported. See `Google Cloud - Storage Request URIs - `__ for - more info. 2. A publicly-accessible image HTTP/HTTPS URL. - When fetching images from HTTP/HTTPS URLs, Google cannot - guarantee that the request will be completed. Your request - may fail if the specified host denies the request (e.g. due - to request throttling or DOS prevention), or if Google - throttles requests to the site for abuse prevention. You - should not depend on externally-hosted images for production - applications. When both ``gcs_image_uri`` and ``image_uri`` - are specified, ``image_uri`` takes precedence. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.ImageSource) - }, -) -_sym_db.RegisterMessage(ImageSource) - -Image = _reflection.GeneratedProtocolMessageType( - "Image", - (_message.Message,), - { - "DESCRIPTOR": _IMAGE, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Client image to perform Google Cloud Vision API tasks over. - - Attributes: - content: - Image content, represented as a stream of bytes. Note: As with - all ``bytes`` fields, protobuffers use a pure binary - representation, whereas JSON representations use base64. - source: - Google Cloud Storage image location, or publicly-accessible - image URL. If both ``content`` and ``source`` are provided for - an image, ``content`` takes precedence and is used to perform - the image annotation request. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.Image) - }, -) -_sym_db.RegisterMessage(Image) - -FaceAnnotation = _reflection.GeneratedProtocolMessageType( - "FaceAnnotation", - (_message.Message,), - { - "Landmark": _reflection.GeneratedProtocolMessageType( - "Landmark", - (_message.Message,), - { - "DESCRIPTOR": _FACEANNOTATION_LANDMARK, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """A face-specific landmark (for example, a face feature). - - Attributes: - type: - Face landmark type. - position: - Face landmark position. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.FaceAnnotation.Landmark) - }, - ), - "DESCRIPTOR": _FACEANNOTATION, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """A face annotation object contains the results of face detection. - - Attributes: - bounding_poly: - The bounding polygon around the face. The coordinates of the - bounding box are in the original image’s scale, as returned in - ``ImageParams``. The bounding box is computed to “frame” the - face in accordance with human expectations. It is based on the - landmarker results. Note that one or more x and/or y - coordinates may not be generated in the ``BoundingPoly`` (the - polygon will be unbounded) if only a partial face appears in - the image to be annotated. - fd_bounding_poly: - The ``fd_bounding_poly`` bounding polygon is tighter than the - ``boundingPoly``, and encloses only the skin part of the face. - Typically, it is used to eliminate the face from any image - analysis that detects the “amount of skin” visible in an - image. It is not based on the landmarker results, only on the - initial face detection, hence the fd (face detection) prefix. - landmarks: - Detected face landmarks. - roll_angle: - Roll angle, which indicates the amount of clockwise/anti- - clockwise rotation of the face relative to the image vertical - about the axis perpendicular to the face. Range [-180,180]. - pan_angle: - Yaw angle, which indicates the leftward/rightward angle that - the face is pointing relative to the vertical plane - perpendicular to the image. Range [-180,180]. - tilt_angle: - Pitch angle, which indicates the upwards/downwards angle that - the face is pointing relative to the image’s horizontal plane. - Range [-180,180]. - detection_confidence: - Detection confidence. Range [0, 1]. - landmarking_confidence: - Face landmarking confidence. Range [0, 1]. - joy_likelihood: - Joy likelihood. - sorrow_likelihood: - Sorrow likelihood. - anger_likelihood: - Anger likelihood. - surprise_likelihood: - Surprise likelihood. - under_exposed_likelihood: - Under-exposed likelihood. - blurred_likelihood: - Blurred likelihood. - headwear_likelihood: - Headwear likelihood. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.FaceAnnotation) - }, -) -_sym_db.RegisterMessage(FaceAnnotation) -_sym_db.RegisterMessage(FaceAnnotation.Landmark) - -LocationInfo = _reflection.GeneratedProtocolMessageType( - "LocationInfo", - (_message.Message,), - { - "DESCRIPTOR": _LOCATIONINFO, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Detected entity location information. - - Attributes: - lat_lng: - lat/long location coordinates. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.LocationInfo) - }, -) -_sym_db.RegisterMessage(LocationInfo) - -Property = _reflection.GeneratedProtocolMessageType( - "Property", - (_message.Message,), - { - "DESCRIPTOR": _PROPERTY, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """A ``Property`` consists of a user-supplied name/value pair. - - Attributes: - name: - Name of the property. - value: - Value of the property. - uint64_value: - Value of numeric properties. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.Property) - }, -) -_sym_db.RegisterMessage(Property) - -EntityAnnotation = _reflection.GeneratedProtocolMessageType( - "EntityAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _ENTITYANNOTATION, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Set of detected entity features. - - Attributes: - mid: - Opaque entity ID. Some IDs may be available in `Google - Knowledge Graph Search API - `__. - locale: - The language code for the locale in which the entity textual - ``description`` is expressed. - description: - Entity textual description, expressed in its ``locale`` - language. - score: - Overall score of the result. Range [0, 1]. - confidence: - \ **Deprecated. Use ``score`` instead.** The accuracy of the - entity detection in an image. For example, for an image in - which the “Eiffel Tower” entity is detected, this field - represents the confidence that there is a tower in the query - image. Range [0, 1]. - topicality: - The relevancy of the ICA (Image Content Annotation) label to - the image. For example, the relevancy of “tower” is likely - higher to an image containing the detected “Eiffel Tower” than - to an image containing a detected distant towering building, - even though the confidence that there is a tower in each image - may be the same. Range [0, 1]. - bounding_poly: - Image region to which this entity belongs. Not produced for - ``LABEL_DETECTION`` features. - locations: - The location information for the detected entity. Multiple - ``LocationInfo`` elements can be present because one location - may indicate the location of the scene in the image, and - another location may indicate the location of the place where - the image was taken. Location information is usually present - for landmarks. - properties: - Some entities may have optional user-supplied ``Property`` - (name/value) fields, such a score or string that qualifies the - entity. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.EntityAnnotation) - }, -) -_sym_db.RegisterMessage(EntityAnnotation) - -SafeSearchAnnotation = _reflection.GeneratedProtocolMessageType( - "SafeSearchAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _SAFESEARCHANNOTATION, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Set of features pertaining to the image, computed by computer vision - methods over safe-search verticals (for example, adult, spoof, - medical, violence). - - Attributes: - adult: - Represents the adult content likelihood for the image. Adult - content may contain elements such as nudity, pornographic - images or cartoons, or sexual activities. - spoof: - Spoof likelihood. The likelihood that an modification was made - to the image’s canonical version to make it appear funny or - offensive. - medical: - Likelihood that this is a medical image. - violence: - Likelihood that this image contains violent content. - racy: - Likelihood that the request image contains racy content. Racy - content may include (but is not limited to) skimpy or sheer - clothing, strategically covered nudity, lewd or provocative - poses, or close-ups of sensitive body areas. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.SafeSearchAnnotation) - }, -) -_sym_db.RegisterMessage(SafeSearchAnnotation) - -LatLongRect = _reflection.GeneratedProtocolMessageType( - "LatLongRect", - (_message.Message,), - { - "DESCRIPTOR": _LATLONGRECT, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Rectangle determined by min and max ``LatLng`` pairs. - - Attributes: - min_lat_lng: - Min lat/long pair. - max_lat_lng: - Max lat/long pair. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.LatLongRect) - }, -) -_sym_db.RegisterMessage(LatLongRect) - -ColorInfo = _reflection.GeneratedProtocolMessageType( - "ColorInfo", - (_message.Message,), - { - "DESCRIPTOR": _COLORINFO, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Color information consists of RGB channels, score, and the fraction of - the image that the color occupies in the image. - - Attributes: - color: - RGB components of the color. - score: - Image-specific score for this color. Value in range [0, 1]. - pixel_fraction: - The fraction of pixels the color occupies in the image. Value - in range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.ColorInfo) - }, -) -_sym_db.RegisterMessage(ColorInfo) - -DominantColorsAnnotation = _reflection.GeneratedProtocolMessageType( - "DominantColorsAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _DOMINANTCOLORSANNOTATION, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Set of dominant colors and their corresponding scores. - - Attributes: - colors: - RGB color values with their score and pixel fraction. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.DominantColorsAnnotation) - }, -) -_sym_db.RegisterMessage(DominantColorsAnnotation) - -ImageProperties = _reflection.GeneratedProtocolMessageType( - "ImageProperties", - (_message.Message,), - { - "DESCRIPTOR": _IMAGEPROPERTIES, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Stores image properties, such as dominant colors. - - Attributes: - dominant_colors: - If present, dominant colors completed successfully. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.ImageProperties) - }, -) -_sym_db.RegisterMessage(ImageProperties) - -CropHint = _reflection.GeneratedProtocolMessageType( - "CropHint", - (_message.Message,), - { - "DESCRIPTOR": _CROPHINT, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Single crop hint that is used to generate a new crop when serving an - image. - - Attributes: - bounding_poly: - The bounding polygon for the crop region. The coordinates of - the bounding box are in the original image’s scale, as - returned in ``ImageParams``. - confidence: - Confidence of this being a salient region. Range [0, 1]. - importance_fraction: - Fraction of importance of this salient region with respect to - the original image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.CropHint) - }, -) -_sym_db.RegisterMessage(CropHint) - -CropHintsAnnotation = _reflection.GeneratedProtocolMessageType( - "CropHintsAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _CROPHINTSANNOTATION, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Set of crop hints that are used to generate new crops when serving - images. - - Attributes: - crop_hints: - Crop hint results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.CropHintsAnnotation) - }, -) -_sym_db.RegisterMessage(CropHintsAnnotation) - -CropHintsParams = _reflection.GeneratedProtocolMessageType( - "CropHintsParams", - (_message.Message,), - { - "DESCRIPTOR": _CROPHINTSPARAMS, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Parameters for crop hints annotation request. - - Attributes: - aspect_ratios: - Aspect ratios in floats, representing the ratio of the width - to the height of the image. For example, if the desired aspect - ratio is 4/3, the corresponding float value should be 1.33333. - If not specified, the best possible crop is returned. The - number of provided aspect ratios is limited to a maximum of - 16; any aspect ratios provided after the 16th are ignored. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.CropHintsParams) - }, -) -_sym_db.RegisterMessage(CropHintsParams) - -WebDetectionParams = _reflection.GeneratedProtocolMessageType( - "WebDetectionParams", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTIONPARAMS, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Parameters for web detection request. - - Attributes: - include_geo_results: - Whether to include results derived from the geo information in - the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.WebDetectionParams) - }, -) -_sym_db.RegisterMessage(WebDetectionParams) - -ImageContext = _reflection.GeneratedProtocolMessageType( - "ImageContext", - (_message.Message,), - { - "DESCRIPTOR": _IMAGECONTEXT, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Image context and/or feature-specific parameters. - - Attributes: - lat_long_rect: - Not used. - language_hints: - List of languages to use for TEXT_DETECTION. In most cases, an - empty value yields the best results since it enables automatic - language detection. For languages based on the Latin alphabet, - setting ``language_hints`` is not needed. In rare cases, when - the language of the text in the image is known, setting a hint - will help get better results (although it will be a - significant hindrance if the hint is wrong). Text detection - returns an error if one or more of the specified languages is - not one of the `supported languages - `__. - crop_hints_params: - Parameters for crop hints annotation request. - web_detection_params: - Parameters for web detection. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.ImageContext) - }, -) -_sym_db.RegisterMessage(ImageContext) - -AnnotateImageRequest = _reflection.GeneratedProtocolMessageType( - "AnnotateImageRequest", - (_message.Message,), - { - "DESCRIPTOR": _ANNOTATEIMAGEREQUEST, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Request for performing Google Cloud Vision API tasks over a user- - provided image, with user-requested features. - - Attributes: - image: - The image to be processed. - features: - Requested features. - image_context: - Additional context that may accompany the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.AnnotateImageRequest) - }, -) -_sym_db.RegisterMessage(AnnotateImageRequest) - -ImageAnnotationContext = _reflection.GeneratedProtocolMessageType( - "ImageAnnotationContext", - (_message.Message,), - { - "DESCRIPTOR": _IMAGEANNOTATIONCONTEXT, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """If an image was produced from a file (e.g. a PDF), this message gives - information about the source of that image. - - Attributes: - uri: - The URI of the file used to produce the image. - page_number: - If the file was a PDF or TIFF, this field gives the page - number within the file used to produce the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.ImageAnnotationContext) - }, -) -_sym_db.RegisterMessage(ImageAnnotationContext) - -AnnotateImageResponse = _reflection.GeneratedProtocolMessageType( - "AnnotateImageResponse", - (_message.Message,), - { - "DESCRIPTOR": _ANNOTATEIMAGERESPONSE, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Response to an image annotation request. - - Attributes: - face_annotations: - If present, face detection has completed successfully. - landmark_annotations: - If present, landmark detection has completed successfully. - logo_annotations: - If present, logo detection has completed successfully. - label_annotations: - If present, label detection has completed successfully. - text_annotations: - If present, text (OCR) detection has completed successfully. - full_text_annotation: - If present, text (OCR) detection or document (OCR) text - detection has completed successfully. This annotation provides - the structural hierarchy for the OCR detected text. - safe_search_annotation: - If present, safe-search annotation has completed successfully. - image_properties_annotation: - If present, image properties were extracted successfully. - crop_hints_annotation: - If present, crop hints have completed successfully. - web_detection: - If present, web detection has completed successfully. - error: - If set, represents the error message for the operation. Note - that filled-in image annotations are guaranteed to be correct, - even when ``error`` is set. - context: - If present, contextual information is needed to understand - where this image comes from. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.AnnotateImageResponse) - }, -) -_sym_db.RegisterMessage(AnnotateImageResponse) - -AnnotateFileResponse = _reflection.GeneratedProtocolMessageType( - "AnnotateFileResponse", - (_message.Message,), - { - "DESCRIPTOR": _ANNOTATEFILERESPONSE, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Response to a single file annotation request. A file may contain one - or more images, which individually have their own responses. - - Attributes: - input_config: - Information about the file for which this response is - generated. - responses: - Individual responses to images found within the file. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.AnnotateFileResponse) - }, -) -_sym_db.RegisterMessage(AnnotateFileResponse) - -BatchAnnotateImagesRequest = _reflection.GeneratedProtocolMessageType( - "BatchAnnotateImagesRequest", - (_message.Message,), - { - "DESCRIPTOR": _BATCHANNOTATEIMAGESREQUEST, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Multiple image annotation requests are batched into a single service - call. - - Attributes: - requests: - Required. Individual image annotation requests for this batch. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.BatchAnnotateImagesRequest) - }, -) -_sym_db.RegisterMessage(BatchAnnotateImagesRequest) - -BatchAnnotateImagesResponse = _reflection.GeneratedProtocolMessageType( - "BatchAnnotateImagesResponse", - (_message.Message,), - { - "DESCRIPTOR": _BATCHANNOTATEIMAGESRESPONSE, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Response to a batch image annotation request. - - Attributes: - responses: - Individual responses to image annotation requests within the - batch. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.BatchAnnotateImagesResponse) - }, -) -_sym_db.RegisterMessage(BatchAnnotateImagesResponse) - -AsyncAnnotateFileRequest = _reflection.GeneratedProtocolMessageType( - "AsyncAnnotateFileRequest", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCANNOTATEFILEREQUEST, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """An offline file annotation request. - - Attributes: - input_config: - Required. Information about the input file. - features: - Required. Requested features. - image_context: - Additional context that may accompany the image(s) in the - file. - output_config: - Required. The desired output location and metadata - (e.g. format). - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.AsyncAnnotateFileRequest) - }, -) -_sym_db.RegisterMessage(AsyncAnnotateFileRequest) - -AsyncAnnotateFileResponse = _reflection.GeneratedProtocolMessageType( - "AsyncAnnotateFileResponse", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCANNOTATEFILERESPONSE, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """The response for a single offline file annotation request. - - Attributes: - output_config: - The output location and metadata from - AsyncAnnotateFileRequest. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.AsyncAnnotateFileResponse) - }, -) -_sym_db.RegisterMessage(AsyncAnnotateFileResponse) - -AsyncBatchAnnotateFilesRequest = _reflection.GeneratedProtocolMessageType( - "AsyncBatchAnnotateFilesRequest", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCBATCHANNOTATEFILESREQUEST, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Multiple async file annotation requests are batched into a single - service call. - - Attributes: - requests: - Required. Individual async file annotation requests for this - batch. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.AsyncBatchAnnotateFilesRequest) - }, -) -_sym_db.RegisterMessage(AsyncBatchAnnotateFilesRequest) - -AsyncBatchAnnotateFilesResponse = _reflection.GeneratedProtocolMessageType( - "AsyncBatchAnnotateFilesResponse", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCBATCHANNOTATEFILESRESPONSE, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Response to an async batch file annotation request. - - Attributes: - responses: - The list of file annotation responses, one for each request in - AsyncBatchAnnotateFilesRequest. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.AsyncBatchAnnotateFilesResponse) - }, -) -_sym_db.RegisterMessage(AsyncBatchAnnotateFilesResponse) - -InputConfig = _reflection.GeneratedProtocolMessageType( - "InputConfig", - (_message.Message,), - { - "DESCRIPTOR": _INPUTCONFIG, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """The desired input location and metadata. - - Attributes: - gcs_source: - The Google Cloud Storage location to read the input from. - mime_type: - The type of the file. Currently only “application/pdf” and - “image/tiff” are supported. Wildcards are not supported. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.InputConfig) - }, -) -_sym_db.RegisterMessage(InputConfig) - -OutputConfig = _reflection.GeneratedProtocolMessageType( - "OutputConfig", - (_message.Message,), - { - "DESCRIPTOR": _OUTPUTCONFIG, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """The desired output location and metadata. - - Attributes: - gcs_destination: - The Google Cloud Storage location to write the output(s) to. - batch_size: - The max number of response protos to put into each output JSON - file on GCS. The valid range is [1, 100]. If not specified, - the default value is 20. For example, for one pdf file with - 100 pages, 100 response protos will be generated. If - ``batch_size`` = 20, then 5 json files each containing 20 - response protos will be written under the prefix - ``gcs_destination``.\ ``uri``. Currently, batch_size only - applies to GcsDestination, with potential future support for - other output configurations. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.OutputConfig) - }, -) -_sym_db.RegisterMessage(OutputConfig) - -GcsSource = _reflection.GeneratedProtocolMessageType( - "GcsSource", - (_message.Message,), - { - "DESCRIPTOR": _GCSSOURCE, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """The Google Cloud Storage location where the input will be read from. - - Attributes: - uri: - Google Cloud Storage URI for the input file. This must only be - a GCS object. Wildcards are not currently supported. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.GcsSource) - }, -) -_sym_db.RegisterMessage(GcsSource) - -GcsDestination = _reflection.GeneratedProtocolMessageType( - "GcsDestination", - (_message.Message,), - { - "DESCRIPTOR": _GCSDESTINATION, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """The Google Cloud Storage location where the output will be written to. - - Attributes: - uri: - Google Cloud Storage URI where the results will be stored. - Results will be in JSON format and preceded by its - corresponding input URI. This field can either represent a - single file, or a prefix for multiple outputs. Prefixes must - end in a ``/``. Examples: - File: gs://bucket- - name/filename.json - Prefix: gs://bucket-name/prefix/here/ - - File: gs://bucket-name/prefix/here If multiple outputs, each - response is still AnnotateFileResponse, each of which contains - some subset of the full list of AnnotateImageResponse. - Multiple outputs can happen if, for example, the output JSON - is too large and overflows into multiple sharded files. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.GcsDestination) - }, -) -_sym_db.RegisterMessage(GcsDestination) - -OperationMetadata = _reflection.GeneratedProtocolMessageType( - "OperationMetadata", - (_message.Message,), - { - "DESCRIPTOR": _OPERATIONMETADATA, - "__module__": "google.cloud.vision_v1p2beta1.proto.image_annotator_pb2", - "__doc__": """Contains metadata for the BatchAnnotateImages operation. - - Attributes: - state: - Current state of the batch operation. - create_time: - The time when the batch request was received. - update_time: - The time when the operation result was last updated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.OperationMetadata) - }, -) -_sym_db.RegisterMessage(OperationMetadata) - - -DESCRIPTOR._options = None -_BATCHANNOTATEIMAGESREQUEST.fields_by_name["requests"]._options = None -_ASYNCBATCHANNOTATEFILESREQUEST.fields_by_name["requests"]._options = None - -_IMAGEANNOTATOR = _descriptor.ServiceDescriptor( - name="ImageAnnotator", - full_name="google.cloud.vision.v1p2beta1.ImageAnnotator", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\025vision.googleapis.com\322A[https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-vision", - create_key=_descriptor._internal_create_key, - serialized_start=7311, - serialized_end=7876, - methods=[ - _descriptor.MethodDescriptor( - name="BatchAnnotateImages", - full_name="google.cloud.vision.v1p2beta1.ImageAnnotator.BatchAnnotateImages", - index=0, - containing_service=None, - input_type=_BATCHANNOTATEIMAGESREQUEST, - output_type=_BATCHANNOTATEIMAGESRESPONSE, - serialized_options=b'\202\323\344\223\002\037"\032/v1p2beta1/images:annotate:\001*\332A\010requests', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="AsyncBatchAnnotateFiles", - full_name="google.cloud.vision.v1p2beta1.ImageAnnotator.AsyncBatchAnnotateFiles", - index=1, - containing_service=None, - input_type=_ASYNCBATCHANNOTATEFILESREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002("#/v1p2beta1/files:asyncBatchAnnotate:\001*\332A\010requests\312A4\n\037AsyncBatchAnnotateFilesResponse\022\021OperationMetadata', - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_IMAGEANNOTATOR) - -DESCRIPTOR.services_by_name["ImageAnnotator"] = _IMAGEANNOTATOR - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p2beta1/proto/image_annotator_pb2_grpc.py b/google/cloud/vision_v1p2beta1/proto/image_annotator_pb2_grpc.py deleted file mode 100644 index cd37f887..00000000 --- a/google/cloud/vision_v1p2beta1/proto/image_annotator_pb2_grpc.py +++ /dev/null @@ -1,141 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.vision_v1p2beta1.proto import ( - image_annotator_pb2 as google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_image__annotator__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) - - -class ImageAnnotatorStub(object): - """Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.BatchAnnotateImages = channel.unary_unary( - "/google.cloud.vision.v1p2beta1.ImageAnnotator/BatchAnnotateImages", - request_serializer=google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesResponse.FromString, - ) - self.AsyncBatchAnnotateFiles = channel.unary_unary( - "/google.cloud.vision.v1p2beta1.ImageAnnotator/AsyncBatchAnnotateFiles", - request_serializer=google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_image__annotator__pb2.AsyncBatchAnnotateFilesRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - - -class ImageAnnotatorServicer(object): - """Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - def BatchAnnotateImages(self, request, context): - """Run image detection and annotation for a batch of images. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def AsyncBatchAnnotateFiles(self, request, context): - """Run async image detection and annotation for a list of generic files (e.g. - PDF) which may contain multiple pages and multiple images per page. - Progress and results can be retrieved through the - `google.longrunning.Operations` interface. - `Operation.metadata` contains `OperationMetadata` (metadata). - `Operation.response` contains `AsyncBatchAnnotateFilesResponse` (results). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_ImageAnnotatorServicer_to_server(servicer, server): - rpc_method_handlers = { - "BatchAnnotateImages": grpc.unary_unary_rpc_method_handler( - servicer.BatchAnnotateImages, - request_deserializer=google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesResponse.SerializeToString, - ), - "AsyncBatchAnnotateFiles": grpc.unary_unary_rpc_method_handler( - servicer.AsyncBatchAnnotateFiles, - request_deserializer=google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_image__annotator__pb2.AsyncBatchAnnotateFilesRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.vision.v1p2beta1.ImageAnnotator", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class ImageAnnotator(object): - """Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - @staticmethod - def BatchAnnotateImages( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p2beta1.ImageAnnotator/BatchAnnotateImages", - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def AsyncBatchAnnotateFiles( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p2beta1.ImageAnnotator/AsyncBatchAnnotateFiles", - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_image__annotator__pb2.AsyncBatchAnnotateFilesRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/vision_v1p2beta1/proto/product_search.proto b/google/cloud/vision_v1p2beta1/proto/product_search.proto deleted file mode 100644 index 85e4e078..00000000 --- a/google/cloud/vision_v1p2beta1/proto/product_search.proto +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2018 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package google.cloud.vision.v1p3beta1; - -import "google/api/annotations.proto"; -import "google/cloud/vision/v1p3beta1/geometry.proto"; -import "google/cloud/vision/v1p3beta1/product_search_service.proto"; -import "google/protobuf/timestamp.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p3beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "ProductSearchProto"; -option java_package = "com.google.cloud.vision.v1p3beta1"; - - -// Parameters for a product search request. -message ProductSearchParams { - // The resource name of the catalog to search. - // - // Format is: `productSearch/catalogs/CATALOG_NAME`. - string catalog_name = 1; - - // The category to search in. - // Optional. It is inferred by the system if it is not specified. - // [Deprecated] Use `product_category`. - ProductSearchCategory category = 2; - - // The product category to search in. - // Optional. It is inferred by the system if it is not specified. - // Supported values are `bag`, `shoe`, `sunglasses`, `dress`, `outerwear`, - // `skirt`, `top`, `shorts`, and `pants`. - string product_category = 5; - - // The bounding polygon around the area of interest in the image. - // Optional. If it is not specified, system discretion will be applied. - // [Deprecated] Use `bounding_poly`. - NormalizedBoundingPoly normalized_bounding_poly = 3; - - // The bounding polygon around the area of interest in the image. - // Optional. If it is not specified, system discretion will be applied. - BoundingPoly bounding_poly = 9; - - // Specifies the verbosity of the product search results. - // Optional. Defaults to `BASIC`. - ProductSearchResultsView view = 4; - - // The resource name of a [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] to be searched for similar images. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`. - string product_set = 6; - - // The list of product categories to search in. Currently, we only consider - // the first category, and either "homegoods" or "apparel" should be - // specified. - repeated string product_categories = 7; - - // The filtering expression. This can be used to restrict search results based - // on Product labels. We currently support an AND of OR of key-value - // expressions, where each expression within an OR must have the same key. - // - // For example, "(color = red OR color = blue) AND brand = Google" is - // acceptable, but not "(color = red OR brand = Google)" or "color: red". - string filter = 8; -} - -// Results for a product search request. -message ProductSearchResults { - // Information about a product. - message ProductInfo { - // Product ID. - string product_id = 1; - - // The URI of the image which matched the query image. - // - // This field is returned only if `view` is set to `FULL` in - // the request. - string image_uri = 2; - - // A confidence level on the match, ranging from 0 (no confidence) to - // 1 (full confidence). - // - // This field is returned only if `view` is set to `FULL` in - // the request. - float score = 3; - } - - // Information about a product. - message Result { - // The Product. - Product product = 1; - - // A confidence level on the match, ranging from 0 (no confidence) to - // 1 (full confidence). - // - // This field is returned only if `view` is set to `FULL` in - // the request. - float score = 2; - - // The resource name of the image from the product that is the closest match - // to the query. - string image = 3; - } - - // Product category. - // [Deprecated] Use `product_category`. - ProductSearchCategory category = 1; - - // Product category. - // Supported values are `bag` and `shoe`. - // [Deprecated] `product_category` is provided in each Product. - string product_category = 4; - - // Timestamp of the index which provided these results. Changes made after - // this time are not reflected in the current results. - google.protobuf.Timestamp index_time = 2; - - // List of detected products. - repeated ProductInfo products = 3; - - // List of results, one for each product match. - repeated Result results = 5; -} - -// Supported product search categories. -enum ProductSearchCategory { - // Default value used when a category is not specified. - PRODUCT_SEARCH_CATEGORY_UNSPECIFIED = 0; - - // Shoes category. - SHOES = 1; - - // Bags category. - BAGS = 2; -} - -// Specifies the fields to include in product search results. -enum ProductSearchResultsView { - // Product search results contain only `product_category` and `product_id`. - // Default value. - BASIC = 0; - - // Product search results contain `product_category`, `product_id`, - // `image_uri`, and `score`. - FULL = 1; -} diff --git a/google/cloud/vision_v1p2beta1/proto/product_search_service.proto b/google/cloud/vision_v1p2beta1/proto/product_search_service.proto deleted file mode 100644 index 90388e36..00000000 --- a/google/cloud/vision_v1p2beta1/proto/product_search_service.proto +++ /dev/null @@ -1,825 +0,0 @@ -// Copyright 2018 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package google.cloud.vision.v1p3beta1; - -import "google/api/annotations.proto"; -import "google/cloud/vision/v1p3beta1/geometry.proto"; -import "google/longrunning/operations.proto"; -import "google/protobuf/empty.proto"; -import "google/protobuf/field_mask.proto"; -import "google/protobuf/timestamp.proto"; -import "google/rpc/status.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p3beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "ProductSearchServiceProto"; -option java_package = "com.google.cloud.vision.v1p3beta1"; - - -// Manages Products and ProductSets of reference images for use in product -// search. It uses the following resource model: -// -// - The API has a collection of [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, named -// `projects/*/locations/*/productSets/*`, which acts as a way to put different -// products into groups to limit identification. -// -// In parallel, -// -// - The API has a collection of [Product][google.cloud.vision.v1p3beta1.Product] resources, named -// `projects/*/locations/*/products/*` -// -// - Each [Product][google.cloud.vision.v1p3beta1.Product] has a collection of [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] resources, named -// `projects/*/locations/*/products/*/referenceImages/*` -service ProductSearch { - // Creates and returns a new ProductSet resource. - // - // Possible errors: - // - // * Returns INVALID_ARGUMENT if display_name is missing, or is longer than - // 4096 characters. - rpc CreateProductSet(CreateProductSetRequest) returns (ProductSet) { - option (google.api.http) = { - post: "/v1p3beta1/{parent=projects/*/locations/*}/productSets" - body: "product_set" - }; - } - - // Lists ProductSets in an unspecified order. - // - // Possible errors: - // - // * Returns INVALID_ARGUMENT if page_size is greater than 100, or less - // than 1. - rpc ListProductSets(ListProductSetsRequest) returns (ListProductSetsResponse) { - option (google.api.http) = { - get: "/v1p3beta1/{parent=projects/*/locations/*}/productSets" - }; - } - - // Gets information associated with a ProductSet. - // - // Possible errors: - // - // * Returns NOT_FOUND if the ProductSet does not exist. - rpc GetProductSet(GetProductSetRequest) returns (ProductSet) { - option (google.api.http) = { - get: "/v1p3beta1/{name=projects/*/locations/*/productSets/*}" - }; - } - - // Makes changes to a ProductSet resource. - // Only display_name can be updated currently. - // - // Possible errors: - // - // * Returns NOT_FOUND if the ProductSet does not exist. - // * Returns INVALID_ARGUMENT if display_name is present in update_mask but - // missing from the request or longer than 4096 characters. - rpc UpdateProductSet(UpdateProductSetRequest) returns (ProductSet) { - option (google.api.http) = { - patch: "/v1p3beta1/{product_set.name=projects/*/locations/*/productSets/*}" - body: "product_set" - }; - } - - // Permanently deletes a ProductSet. All Products and ReferenceImages in the - // ProductSet will be deleted. - // - // The actual image files are not deleted from Google Cloud Storage. - // - // Possible errors: - // - // * Returns NOT_FOUND if the ProductSet does not exist. - rpc DeleteProductSet(DeleteProductSetRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v1p3beta1/{name=projects/*/locations/*/productSets/*}" - }; - } - - // Creates and returns a new product resource. - // - // Possible errors: - // - // * Returns INVALID_ARGUMENT if display_name is missing or longer than 4096 - // characters. - // * Returns INVALID_ARGUMENT if description is longer than 4096 characters. - // * Returns INVALID_ARGUMENT if product_category is missing or invalid. - rpc CreateProduct(CreateProductRequest) returns (Product) { - option (google.api.http) = { - post: "/v1p3beta1/{parent=projects/*/locations/*}/products" - body: "product" - }; - } - - // Lists products in an unspecified order. - // - // Possible errors: - // - // * Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1. - rpc ListProducts(ListProductsRequest) returns (ListProductsResponse) { - option (google.api.http) = { - get: "/v1p3beta1/{parent=projects/*/locations/*}/products" - }; - } - - // Gets information associated with a Product. - // - // Possible errors: - // - // * Returns NOT_FOUND if the Product does not exist. - rpc GetProduct(GetProductRequest) returns (Product) { - option (google.api.http) = { - get: "/v1p3beta1/{name=projects/*/locations/*/products/*}" - }; - } - - // Makes changes to a Product resource. - // Only display_name, description and labels can be updated right now. - // - // If labels are updated, the change will not be reflected in queries until - // the next index time. - // - // Possible errors: - // - // * Returns NOT_FOUND if the Product does not exist. - // * Returns INVALID_ARGUMENT if display_name is present in update_mask but is - // missing from the request or longer than 4096 characters. - // * Returns INVALID_ARGUMENT if description is present in update_mask but is - // longer than 4096 characters. - // * Returns INVALID_ARGUMENT if product_category is present in update_mask. - rpc UpdateProduct(UpdateProductRequest) returns (Product) { - option (google.api.http) = { - patch: "/v1p3beta1/{product.name=projects/*/locations/*/products/*}" - body: "product" - }; - } - - // Permanently deletes a product and its reference images. - // - // Metadata of the product and all its images will be deleted right away, but - // search queries against ProductSets containing the product may still work - // until all related caches are refreshed. - // - // Possible errors: - // - // * Returns NOT_FOUND if the product does not exist. - rpc DeleteProduct(DeleteProductRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v1p3beta1/{name=projects/*/locations/*/products/*}" - }; - } - - // Creates and returns a new ReferenceImage resource. - // - // The `bounding_poly` field is optional. If `bounding_poly` is not specified, - // the system will try to detect regions of interest in the image that are - // compatible with the product_category on the parent product. If it is - // specified, detection is ALWAYS skipped. The system converts polygons into - // non-rotated rectangles. - // - // Note that the pipeline will resize the image if the image resolution is too - // large to process (above 50MP). - // - // Possible errors: - // - // * Returns INVALID_ARGUMENT if the image_uri is missing or longer than 4096 - // characters. - // * Returns INVALID_ARGUMENT if the product does not exist. - // * Returns INVALID_ARGUMENT if bounding_poly is not provided, and nothing - // compatible with the parent product's product_category is detected. - // * Returns INVALID_ARGUMENT if bounding_poly contains more than 10 polygons. - rpc CreateReferenceImage(CreateReferenceImageRequest) returns (ReferenceImage) { - option (google.api.http) = { - post: "/v1p3beta1/{parent=projects/*/locations/*/products/*}/referenceImages" - body: "reference_image" - }; - } - - // Permanently deletes a reference image. - // - // The image metadata will be deleted right away, but search queries - // against ProductSets containing the image may still work until all related - // caches are refreshed. - // - // The actual image files are not deleted from Google Cloud Storage. - // - // Possible errors: - // - // * Returns NOT_FOUND if the reference image does not exist. - rpc DeleteReferenceImage(DeleteReferenceImageRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v1p3beta1/{name=projects/*/locations/*/products/*/referenceImages/*}" - }; - } - - // Lists reference images. - // - // Possible errors: - // - // * Returns NOT_FOUND if the parent product does not exist. - // * Returns INVALID_ARGUMENT if the page_size is greater than 100, or less - // than 1. - rpc ListReferenceImages(ListReferenceImagesRequest) returns (ListReferenceImagesResponse) { - option (google.api.http) = { - get: "/v1p3beta1/{parent=projects/*/locations/*/products/*}/referenceImages" - }; - } - - // Gets information associated with a ReferenceImage. - // - // Possible errors: - // - // * Returns NOT_FOUND if the specified image does not exist. - rpc GetReferenceImage(GetReferenceImageRequest) returns (ReferenceImage) { - option (google.api.http) = { - get: "/v1p3beta1/{name=projects/*/locations/*/products/*/referenceImages/*}" - }; - } - - // Adds a Product to the specified ProductSet. If the Product is already - // present, no change is made. - // - // One Product can be added to at most 100 ProductSets. - // - // Possible errors: - // - // * Returns NOT_FOUND if the Product or the ProductSet doesn't exist. - rpc AddProductToProductSet(AddProductToProductSetRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - post: "/v1p3beta1/{name=projects/*/locations/*/productSets/*}:addProduct" - body: "*" - }; - } - - // Removes a Product from the specified ProductSet. - // - // Possible errors: - // - // * Returns NOT_FOUND If the Product is not found under the ProductSet. - rpc RemoveProductFromProductSet(RemoveProductFromProductSetRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - post: "/v1p3beta1/{name=projects/*/locations/*/productSets/*}:removeProduct" - body: "*" - }; - } - - // Lists the Products in a ProductSet, in an unspecified order. If the - // ProductSet does not exist, the products field of the response will be - // empty. - // - // Possible errors: - // - // * Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1. - rpc ListProductsInProductSet(ListProductsInProductSetRequest) returns (ListProductsInProductSetResponse) { - option (google.api.http) = { - get: "/v1p3beta1/{name=projects/*/locations/*/productSets/*}/products" - }; - } - - // Asynchronous API that imports a list of reference images to specified - // product sets based on a list of image information. - // - // The [google.longrunning.Operation][google.longrunning.Operation] API can be used to keep track of the - // progress and results of the request. - // `Operation.metadata` contains `BatchOperationMetadata`. (progress) - // `Operation.response` contains `ImportProductSetsResponse`. (results) - // - // The input source of this method is a csv file on Google Cloud Storage. - // For the format of the csv file please see - // [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1p3beta1.ImportProductSetsGcsSource.csv_file_uri]. - rpc ImportProductSets(ImportProductSetsRequest) returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v1p3beta1/{parent=projects/*/locations/*}/productSets:import" - body: "*" - }; - } -} - -// A Product contains ReferenceImages. -message Product { - // A product label represented as a key-value pair. - message KeyValue { - // The key of the label attached to the product. Cannot be empty and cannot - // exceed 128 bytes. - string key = 1; - - // The value of the label attached to the product. Cannot be empty and - // cannot exceed 128 bytes. - string value = 2; - } - - // The resource name of the product. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`. - // - // This field is ignored when creating a product. - string name = 1; - - // The user-provided name for this Product. Must not be empty. Must be at most - // 4096 characters long. - string display_name = 2; - - // User-provided metadata to be stored with this product. Must be at most 4096 - // characters long. - string description = 3; - - // The category for the product identified by the reference image. This should - // be either "homegoods" or "apparel". - // - // This field is immutable. - string product_category = 4; - - // Key-value pairs that can be attached to a product. At query time, - // constraints can be specified based on the product_labels. - // - // Note that integer values can be provided as strings, e.g. "1199". Only - // strings with integer values can match a range-based restriction which is - // to be supported soon. - // - // Multiple values can be assigned to the same key. One product may have up to - // 100 product_labels. - repeated KeyValue product_labels = 5; -} - -// A ProductSet contains Products. A ProductSet can contain a maximum of 1 -// million reference images. If the limit is exceeded, periodic indexing will -// fail. -message ProductSet { - // The resource name of the ProductSet. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`. - // - // This field is ignored when creating a ProductSet. - string name = 1; - - // The user-provided name for this ProductSet. Must not be empty. Must be at - // most 4096 characters long. - string display_name = 2; - - // Output only. The time at which this ProductSet was last indexed. Query - // results will reflect all updates before this time. If this ProductSet has - // never been indexed, this field is 0. - // - // This field is ignored when creating a ProductSet. - google.protobuf.Timestamp index_time = 3; - - // Output only. If there was an error with indexing the product set, the field - // is populated. - // - // This field is ignored when creating a ProductSet. - google.rpc.Status index_error = 4; -} - -// A `ReferenceImage` represents a product image and its associated metadata, -// such as bounding boxes. -message ReferenceImage { - // The resource name of the reference image. - // - // Format is: - // - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`. - // - // This field is ignored when creating a reference image. - string name = 1; - - // The Google Cloud Storage URI of the reference image. - // - // The URI must start with `gs://`. - // - // Required. - string uri = 2; - - // Bounding polygons around the areas of interest in the reference image. - // Optional. If this field is empty, the system will try to detect regions of - // interest. At most 10 bounding polygons will be used. - // - // The provided shape is converted into a non-rotated rectangle. Once - // converted, the small edge of the rectangle must be greater than or equal - // to 300 pixels. The aspect ratio must be 1:4 or less (i.e. 1:3 is ok; 1:5 - // is not). - repeated BoundingPoly bounding_polys = 3; -} - -// Request message for the `CreateProduct` method. -message CreateProductRequest { - // The project in which the Product should be created. - // - // Format is - // `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1; - - // The product to create. - Product product = 2; - - // A user-supplied resource id for this Product. If set, the server will - // attempt to use this value as the resource id. If it is already in use, an - // error is returned with code ALREADY_EXISTS. Must be at most 128 characters - // long. It cannot contain the character `/`. - string product_id = 3; -} - -// Request message for the `ListProducts` method. -message ListProductsRequest { - // The project OR ProductSet from which Products should be listed. - // - // Format: - // `projects/PROJECT_ID/locations/LOC_ID` - string parent = 1; - - // The maximum number of items to return. Default 10, maximum 100. - int32 page_size = 2; - - // The next_page_token returned from a previous List request, if any. - string page_token = 3; -} - -// Response message for the `ListProducts` method. -message ListProductsResponse { - // List of products. - repeated Product products = 1; - - // Token to retrieve the next page of results, or empty if there are no more - // results in the list. - string next_page_token = 2; -} - -// Request message for the `GetProduct` method. -message GetProductRequest { - // Resource name of the Product to get. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID` - string name = 1; -} - -// Request message for the `UpdateProduct` method. -message UpdateProductRequest { - // The Product resource which replaces the one on the server. - // product.name is immutable. - Product product = 1; - - // The [FieldMask][google.protobuf.FieldMask] that specifies which fields - // to update. - // If update_mask isn't specified, all mutable fields are to be updated. - // Valid mask paths include `product_labels`, `display_name` and - // `description`. - google.protobuf.FieldMask update_mask = 2; -} - -// Request message for the `DeleteProduct` method. -message DeleteProductRequest { - // Resource name of product to delete. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID` - string name = 1; -} - -// Request message for the `CreateProductSet` method. -message CreateProductSetRequest { - // The project in which the ProductSet should be created. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1; - - // The ProductSet to create. - ProductSet product_set = 2; - - // A user-supplied resource id for this ProductSet. If set, the server will - // attempt to use this value as the resource id. If it is already in use, an - // error is returned with code ALREADY_EXISTS. Must be at most 128 characters - // long. It cannot contain the character `/`. - string product_set_id = 3; -} - -// Request message for the `ListProductSets` method. -message ListProductSetsRequest { - // The project from which ProductSets should be listed. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1; - - // The maximum number of items to return. Default 10, maximum 100. - int32 page_size = 2; - - // The next_page_token returned from a previous List request, if any. - string page_token = 3; -} - -// Response message for the `ListProductSets` method. -message ListProductSetsResponse { - // List of ProductSets. - repeated ProductSet product_sets = 1; - - // Token to retrieve the next page of results, or empty if there are no more - // results in the list. - string next_page_token = 2; -} - -// Request message for the `GetProductSet` method. -message GetProductSetRequest { - // Resource name of the ProductSet to get. - // - // Format is: - // `projects/PROJECT_ID/locations/LOG_ID/productSets/PRODUCT_SET_ID` - string name = 1; -} - -// Request message for the `UpdateProductSet` method. -message UpdateProductSetRequest { - // The ProductSet resource which replaces the one on the server. - ProductSet product_set = 1; - - // The [FieldMask][google.protobuf.FieldMask] that specifies which fields to - // update. - // If update_mask isn't specified, all mutable fields are to be updated. - // Valid mask path is `display_name`. - google.protobuf.FieldMask update_mask = 2; -} - -// Request message for the `DeleteProductSet` method. -message DeleteProductSetRequest { - // Resource name of the ProductSet to delete. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1; -} - -// Request message for the `CreateReferenceImage` method. -message CreateReferenceImageRequest { - // Resource name of the product in which to create the reference image. - // - // Format is - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`. - string parent = 1; - - // The reference image to create. - // If an image ID is specified, it is ignored. - ReferenceImage reference_image = 2; - - // A user-supplied resource id for the ReferenceImage to be added. If set, - // the server will attempt to use this value as the resource id. If it is - // already in use, an error is returned with code ALREADY_EXISTS. Must be at - // most 128 characters long. It cannot contain the character `/`. - string reference_image_id = 3; -} - -// Request message for the `ListReferenceImages` method. -message ListReferenceImagesRequest { - // Resource name of the product containing the reference images. - // - // Format is - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`. - string parent = 1; - - // The maximum number of items to return. Default 10, maximum 100. - int32 page_size = 2; - - // A token identifying a page of results to be returned. This is the value - // of `nextPageToken` returned in a previous reference image list request. - // - // Defaults to the first page if not specified. - string page_token = 3; -} - -// Response message for the `ListReferenceImages` method. -message ListReferenceImagesResponse { - // The list of reference images. - repeated ReferenceImage reference_images = 1; - - // The maximum number of items to return. Default 10, maximum 100. - int32 page_size = 2; - - // The next_page_token returned from a previous List request, if any. - string next_page_token = 3; -} - -// Request message for the `GetReferenceImage` method. -message GetReferenceImageRequest { - // The resource name of the ReferenceImage to get. - // - // Format is: - // - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`. - string name = 1; -} - -// Request message for the `DeleteReferenceImage` method. -message DeleteReferenceImageRequest { - // The resource name of the reference image to delete. - // - // Format is: - // - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID` - string name = 1; -} - -// Request message for the `AddProductToProductSet` method. -message AddProductToProductSetRequest { - // The resource name for the ProductSet to modify. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1; - - // The resource name for the Product to be added to this ProductSet. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID` - string product = 2; -} - -// Request message for the `RemoveProductFromProductSet` method. -message RemoveProductFromProductSetRequest { - // The resource name for the ProductSet to modify. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1; - - // The resource name for the Product to be removed from this ProductSet. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID` - string product = 2; -} - -// Request message for the `ListProductsInProductSet` method. -message ListProductsInProductSetRequest { - // The ProductSet resource for which to retrieve Products. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1; - - // The maximum number of items to return. Default 10, maximum 100. - int32 page_size = 2; - - // The next_page_token returned from a previous List request, if any. - string page_token = 3; -} - -// Response message for the `ListProductsInProductSet` method. -message ListProductsInProductSetResponse { - // The list of Products. - repeated Product products = 1; - - // Token to retrieve the next page of results, or empty if there are no more - // results in the list. - string next_page_token = 2; -} - -// The Google Cloud Storage location for a csv file which preserves a list of -// ImportProductSetRequests in each line. -message ImportProductSetsGcsSource { - // The Google Cloud Storage URI of the input csv file. - // - // The URI must start with gs:// - // - // The format of the input csv file should be one image per line. - // In each line, there are 6 columns. - // 1. image_uri - // 2, image_id - // 3. product_set_id - // 4. product_id - // 5, product_category - // 6, product_display_name - // 7, labels - // 8. bounding_poly - // - // Columns 1, 3, 4, and 5 are required, other columns are optional. A new - // ProductSet/Product with the same id will be created on the fly - // if the ProductSet/Product specified by product_set_id/product_id does not - // exist. - // - // The image_id field is optional but has to be unique if provided. If it is - // empty, we will automatically assign an unique id to the image. - // - // The product_display_name field is optional. If it is empty, a space (" ") - // is used as the place holder for the product display_name, which can - // be updated later through the realtime API. - // - // If the Product with product_id already exists, the fields - // product_display_name, product_category and labels are ignored. - // - // If a Product doesn't exist and needs to be created on the fly, the - // product_display_name field refers to [Product.display_name][google.cloud.vision.v1p3beta1.Product.display_name], the - // product_category field refers to [Product.product_category][google.cloud.vision.v1p3beta1.Product.product_category], and the - // labels field refers to [Product.labels][]. - // - // Labels (optional) should be a line containing a list of comma-separated - // key-value pairs, with the format - // "key_1=value_1,key_2=value_2,...,key_n=value_n". - // - // The bounding_poly (optional) field is used to identify one region of - // interest from the image in the same manner as CreateReferenceImage. If no - // bounding_poly is specified, the system will try to detect regions of - // interest automatically. - // - // Note that the pipeline will resize the image if the image resolution is too - // large to process (above 20MP). - // - // Also note that at most one bounding_poly is allowed per line. If the image - // contains multiple regions of interest, the csv should contain one line per - // region of interest. - // - // The bounding_poly column should contain an even number of comma-separated - // numbers, with the format "p1_x,p1_y,p2_x,p2_y,...,pn_x,pn_y". Nonnegative - // integers should be used for absolute bounding polygons, and float values - // in [0, 1] should be used for normalized bounding polygons. - string csv_file_uri = 1; -} - -// The input content for the `ImportProductSets` method. -message ImportProductSetsInputConfig { - // The source of the input. - oneof source { - // The Google Cloud Storage location for a csv file which preserves a list - // of ImportProductSetRequests in each line. - ImportProductSetsGcsSource gcs_source = 1; - } -} - -// Request message for the `ImportProductSets` method. -message ImportProductSetsRequest { - // The project in which the ProductSets should be imported. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1; - - // The input content for the list of requests. - ImportProductSetsInputConfig input_config = 2; -} - -// Response message for the `ImportProductSets` method. -// -// This message is returned by the -// [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] method in the returned -// [google.longrunning.Operation.response][google.longrunning.Operation.response] field. -message ImportProductSetsResponse { - // The list of reference_images that are imported successfully. - repeated ReferenceImage reference_images = 1; - - // The rpc status for each ImportProductSet request, including both successes - // and errors. - // - // The number of statuses here matches the number of lines in the csv file, - // and statuses[i] stores the success or failure status of processing the i-th - // line of the csv, starting from line 0. - repeated google.rpc.Status statuses = 2; -} - -// Metadata for the batch operations such as the current state. -// -// This is included in the `metadata` field of the `Operation` returned by the -// `GetOperation` call of the `google::longrunning::Operations` service. -message BatchOperationMetadata { - // Enumerates the possible states that the batch request can be in. - enum State { - // Invalid. - STATE_UNSPECIFIED = 0; - - // Request is actively being processed. - PROCESSING = 1; - - // The request is done and at least one item has been successfully - // processed. - SUCCESSFUL = 2; - - // The request is done and no item has been successfully processed. - FAILED = 3; - - // The request is done after the longrunning.Operations.CancelOperation has - // been called by the user. Any records that were processed before the - // cancel command are output as specified in the request. - CANCELLED = 4; - } - - // The current state of the batch operation. - State state = 1; - - // The time when the batch request was submitted to the server. - google.protobuf.Timestamp submit_time = 2; - - // The time when the batch request is finished and - // [google.longrunning.Operation.done][google.longrunning.Operation.done] is set to true. - google.protobuf.Timestamp end_time = 3; -} diff --git a/google/cloud/vision_v1p2beta1/proto/text_annotation_pb2.py b/google/cloud/vision_v1p2beta1/proto/text_annotation_pb2.py deleted file mode 100644 index 87720f18..00000000 --- a/google/cloud/vision_v1p2beta1/proto/text_annotation_pb2.py +++ /dev/null @@ -1,1224 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p2beta1/proto/text_annotation.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.cloud.vision_v1p2beta1.proto import ( - geometry_pb2 as google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_geometry__pb2, -) - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p2beta1/proto/text_annotation.proto", - package="google.cloud.vision.v1p2beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p2beta1B\023TextAnnotationProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p2beta1;vision\370\001\001", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n9google/cloud/vision_v1p2beta1/proto/text_annotation.proto\x12\x1dgoogle.cloud.vision.v1p2beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x32google/cloud/vision_v1p2beta1/proto/geometry.proto"\xb2\x04\n\x0eTextAnnotation\x12\x32\n\x05pages\x18\x01 \x03(\x0b\x32#.google.cloud.vision.v1p2beta1.Page\x12\x0c\n\x04text\x18\x02 \x01(\t\x1a=\n\x10\x44\x65tectedLanguage\x12\x15\n\rlanguage_code\x18\x01 \x01(\t\x12\x12\n\nconfidence\x18\x02 \x01(\x02\x1a\xdc\x01\n\rDetectedBreak\x12S\n\x04type\x18\x01 \x01(\x0e\x32\x45.google.cloud.vision.v1p2beta1.TextAnnotation.DetectedBreak.BreakType\x12\x11\n\tis_prefix\x18\x02 \x01(\x08"c\n\tBreakType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\t\n\x05SPACE\x10\x01\x12\x0e\n\nSURE_SPACE\x10\x02\x12\x12\n\x0e\x45OL_SURE_SPACE\x10\x03\x12\n\n\x06HYPHEN\x10\x04\x12\x0e\n\nLINE_BREAK\x10\x05\x1a\xbf\x01\n\x0cTextProperty\x12Z\n\x12\x64\x65tected_languages\x18\x01 \x03(\x0b\x32>.google.cloud.vision.v1p2beta1.TextAnnotation.DetectedLanguage\x12S\n\x0e\x64\x65tected_break\x18\x02 \x01(\x0b\x32;.google.cloud.vision.v1p2beta1.TextAnnotation.DetectedBreak"\xbd\x01\n\x04Page\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p2beta1.TextAnnotation.TextProperty\x12\r\n\x05width\x18\x02 \x01(\x05\x12\x0e\n\x06height\x18\x03 \x01(\x05\x12\x34\n\x06\x62locks\x18\x04 \x03(\x0b\x32$.google.cloud.vision.v1p2beta1.Block\x12\x12\n\nconfidence\x18\x05 \x01(\x02"\x82\x03\n\x05\x42lock\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p2beta1.TextAnnotation.TextProperty\x12\x41\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p2beta1.BoundingPoly\x12<\n\nparagraphs\x18\x03 \x03(\x0b\x32(.google.cloud.vision.v1p2beta1.Paragraph\x12\x42\n\nblock_type\x18\x04 \x01(\x0e\x32..google.cloud.vision.v1p2beta1.Block.BlockType\x12\x12\n\nconfidence\x18\x05 \x01(\x02"R\n\tBlockType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x08\n\x04TEXT\x10\x01\x12\t\n\x05TABLE\x10\x02\x12\x0b\n\x07PICTURE\x10\x03\x12\t\n\x05RULER\x10\x04\x12\x0b\n\x07\x42\x41RCODE\x10\x05"\xe4\x01\n\tParagraph\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p2beta1.TextAnnotation.TextProperty\x12\x41\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p2beta1.BoundingPoly\x12\x32\n\x05words\x18\x03 \x03(\x0b\x32#.google.cloud.vision.v1p2beta1.Word\x12\x12\n\nconfidence\x18\x04 \x01(\x02"\xe3\x01\n\x04Word\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p2beta1.TextAnnotation.TextProperty\x12\x41\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p2beta1.BoundingPoly\x12\x36\n\x07symbols\x18\x03 \x03(\x0b\x32%.google.cloud.vision.v1p2beta1.Symbol\x12\x12\n\nconfidence\x18\x04 \x01(\x02"\xbb\x01\n\x06Symbol\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p2beta1.TextAnnotation.TextProperty\x12\x41\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p2beta1.BoundingPoly\x12\x0c\n\x04text\x18\x03 \x01(\t\x12\x12\n\nconfidence\x18\x04 \x01(\x02\x42\x82\x01\n!com.google.cloud.vision.v1p2beta1B\x13TextAnnotationProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p2beta1;vision\xf8\x01\x01\x62\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_geometry__pb2.DESCRIPTOR, - ], -) - - -_TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE = _descriptor.EnumDescriptor( - name="BreakType", - full_name="google.cloud.vision.v1p2beta1.TextAnnotation.DetectedBreak.BreakType", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNKNOWN", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SPACE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SURE_SPACE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="EOL_SURE_SPACE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="HYPHEN", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LINE_BREAK", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=444, - serialized_end=543, -) -_sym_db.RegisterEnumDescriptor(_TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE) - -_BLOCK_BLOCKTYPE = _descriptor.EnumDescriptor( - name="BlockType", - full_name="google.cloud.vision.v1p2beta1.Block.BlockType", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNKNOWN", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="TEXT", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="TABLE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="PICTURE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RULER", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="BARCODE", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=1236, - serialized_end=1318, -) -_sym_db.RegisterEnumDescriptor(_BLOCK_BLOCKTYPE) - - -_TEXTANNOTATION_DETECTEDLANGUAGE = _descriptor.Descriptor( - name="DetectedLanguage", - full_name="google.cloud.vision.v1p2beta1.TextAnnotation.DetectedLanguage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="language_code", - full_name="google.cloud.vision.v1p2beta1.TextAnnotation.DetectedLanguage.language_code", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p2beta1.TextAnnotation.DetectedLanguage.confidence", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=259, - serialized_end=320, -) - -_TEXTANNOTATION_DETECTEDBREAK = _descriptor.Descriptor( - name="DetectedBreak", - full_name="google.cloud.vision.v1p2beta1.TextAnnotation.DetectedBreak", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="type", - full_name="google.cloud.vision.v1p2beta1.TextAnnotation.DetectedBreak.type", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="is_prefix", - full_name="google.cloud.vision.v1p2beta1.TextAnnotation.DetectedBreak.is_prefix", - index=1, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=323, - serialized_end=543, -) - -_TEXTANNOTATION_TEXTPROPERTY = _descriptor.Descriptor( - name="TextProperty", - full_name="google.cloud.vision.v1p2beta1.TextAnnotation.TextProperty", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="detected_languages", - full_name="google.cloud.vision.v1p2beta1.TextAnnotation.TextProperty.detected_languages", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="detected_break", - full_name="google.cloud.vision.v1p2beta1.TextAnnotation.TextProperty.detected_break", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=546, - serialized_end=737, -) - -_TEXTANNOTATION = _descriptor.Descriptor( - name="TextAnnotation", - full_name="google.cloud.vision.v1p2beta1.TextAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="pages", - full_name="google.cloud.vision.v1p2beta1.TextAnnotation.pages", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="text", - full_name="google.cloud.vision.v1p2beta1.TextAnnotation.text", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _TEXTANNOTATION_DETECTEDLANGUAGE, - _TEXTANNOTATION_DETECTEDBREAK, - _TEXTANNOTATION_TEXTPROPERTY, - ], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=175, - serialized_end=737, -) - - -_PAGE = _descriptor.Descriptor( - name="Page", - full_name="google.cloud.vision.v1p2beta1.Page", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p2beta1.Page.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="width", - full_name="google.cloud.vision.v1p2beta1.Page.width", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="height", - full_name="google.cloud.vision.v1p2beta1.Page.height", - index=2, - number=3, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="blocks", - full_name="google.cloud.vision.v1p2beta1.Page.blocks", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p2beta1.Page.confidence", - index=4, - number=5, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=740, - serialized_end=929, -) - - -_BLOCK = _descriptor.Descriptor( - name="Block", - full_name="google.cloud.vision.v1p2beta1.Block", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p2beta1.Block.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_box", - full_name="google.cloud.vision.v1p2beta1.Block.bounding_box", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="paragraphs", - full_name="google.cloud.vision.v1p2beta1.Block.paragraphs", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="block_type", - full_name="google.cloud.vision.v1p2beta1.Block.block_type", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p2beta1.Block.confidence", - index=4, - number=5, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_BLOCK_BLOCKTYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=932, - serialized_end=1318, -) - - -_PARAGRAPH = _descriptor.Descriptor( - name="Paragraph", - full_name="google.cloud.vision.v1p2beta1.Paragraph", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p2beta1.Paragraph.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_box", - full_name="google.cloud.vision.v1p2beta1.Paragraph.bounding_box", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="words", - full_name="google.cloud.vision.v1p2beta1.Paragraph.words", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p2beta1.Paragraph.confidence", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1321, - serialized_end=1549, -) - - -_WORD = _descriptor.Descriptor( - name="Word", - full_name="google.cloud.vision.v1p2beta1.Word", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p2beta1.Word.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_box", - full_name="google.cloud.vision.v1p2beta1.Word.bounding_box", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="symbols", - full_name="google.cloud.vision.v1p2beta1.Word.symbols", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p2beta1.Word.confidence", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1552, - serialized_end=1779, -) - - -_SYMBOL = _descriptor.Descriptor( - name="Symbol", - full_name="google.cloud.vision.v1p2beta1.Symbol", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p2beta1.Symbol.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_box", - full_name="google.cloud.vision.v1p2beta1.Symbol.bounding_box", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="text", - full_name="google.cloud.vision.v1p2beta1.Symbol.text", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p2beta1.Symbol.confidence", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1782, - serialized_end=1969, -) - -_TEXTANNOTATION_DETECTEDLANGUAGE.containing_type = _TEXTANNOTATION -_TEXTANNOTATION_DETECTEDBREAK.fields_by_name[ - "type" -].enum_type = _TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE -_TEXTANNOTATION_DETECTEDBREAK.containing_type = _TEXTANNOTATION -_TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE.containing_type = _TEXTANNOTATION_DETECTEDBREAK -_TEXTANNOTATION_TEXTPROPERTY.fields_by_name[ - "detected_languages" -].message_type = _TEXTANNOTATION_DETECTEDLANGUAGE -_TEXTANNOTATION_TEXTPROPERTY.fields_by_name[ - "detected_break" -].message_type = _TEXTANNOTATION_DETECTEDBREAK -_TEXTANNOTATION_TEXTPROPERTY.containing_type = _TEXTANNOTATION -_TEXTANNOTATION.fields_by_name["pages"].message_type = _PAGE -_PAGE.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_PAGE.fields_by_name["blocks"].message_type = _BLOCK -_BLOCK.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_BLOCK.fields_by_name[ - "bounding_box" -].message_type = ( - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_BLOCK.fields_by_name["paragraphs"].message_type = _PARAGRAPH -_BLOCK.fields_by_name["block_type"].enum_type = _BLOCK_BLOCKTYPE -_BLOCK_BLOCKTYPE.containing_type = _BLOCK -_PARAGRAPH.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_PARAGRAPH.fields_by_name[ - "bounding_box" -].message_type = ( - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_PARAGRAPH.fields_by_name["words"].message_type = _WORD -_WORD.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_WORD.fields_by_name[ - "bounding_box" -].message_type = ( - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_WORD.fields_by_name["symbols"].message_type = _SYMBOL -_SYMBOL.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_SYMBOL.fields_by_name[ - "bounding_box" -].message_type = ( - google_dot_cloud_dot_vision__v1p2beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -DESCRIPTOR.message_types_by_name["TextAnnotation"] = _TEXTANNOTATION -DESCRIPTOR.message_types_by_name["Page"] = _PAGE -DESCRIPTOR.message_types_by_name["Block"] = _BLOCK -DESCRIPTOR.message_types_by_name["Paragraph"] = _PARAGRAPH -DESCRIPTOR.message_types_by_name["Word"] = _WORD -DESCRIPTOR.message_types_by_name["Symbol"] = _SYMBOL -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -TextAnnotation = _reflection.GeneratedProtocolMessageType( - "TextAnnotation", - (_message.Message,), - { - "DetectedLanguage": _reflection.GeneratedProtocolMessageType( - "DetectedLanguage", - (_message.Message,), - { - "DESCRIPTOR": _TEXTANNOTATION_DETECTEDLANGUAGE, - "__module__": "google.cloud.vision_v1p2beta1.proto.text_annotation_pb2", - "__doc__": """Detected language for a structural component. - - Attributes: - language_code: - The BCP-47 language code, such as “en-US” or “sr-Latn”. For - more information, see http://www.unicode.org/reports/tr35/#Uni - code_locale_identifier. - confidence: - Confidence of detected language. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.TextAnnotation.DetectedLanguage) - }, - ), - "DetectedBreak": _reflection.GeneratedProtocolMessageType( - "DetectedBreak", - (_message.Message,), - { - "DESCRIPTOR": _TEXTANNOTATION_DETECTEDBREAK, - "__module__": "google.cloud.vision_v1p2beta1.proto.text_annotation_pb2", - "__doc__": """Detected start or end of a structural component. - - Attributes: - type: - Detected break type. - is_prefix: - True if break prepends the element. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.TextAnnotation.DetectedBreak) - }, - ), - "TextProperty": _reflection.GeneratedProtocolMessageType( - "TextProperty", - (_message.Message,), - { - "DESCRIPTOR": _TEXTANNOTATION_TEXTPROPERTY, - "__module__": "google.cloud.vision_v1p2beta1.proto.text_annotation_pb2", - "__doc__": """Additional information detected on the structural component. - - Attributes: - detected_languages: - A list of detected languages together with confidence. - detected_break: - Detected start or end of a text segment. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.TextAnnotation.TextProperty) - }, - ), - "DESCRIPTOR": _TEXTANNOTATION, - "__module__": "google.cloud.vision_v1p2beta1.proto.text_annotation_pb2", - "__doc__": """TextAnnotation contains a structured representation of OCR extracted - text. The hierarchy of an OCR extracted text structure is like this: - TextAnnotation -> Page -> Block -> Paragraph -> Word -> Symbol Each - structural component, starting from Page, may further have their own - properties. Properties describe detected languages, breaks etc.. - Please refer to the [TextAnnotation.TextProperty][google.cloud.vision. - v1p2beta1.TextAnnotation.TextProperty] message definition below for - more detail. - - Attributes: - pages: - List of pages detected by OCR. - text: - UTF-8 text detected on the pages. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.TextAnnotation) - }, -) -_sym_db.RegisterMessage(TextAnnotation) -_sym_db.RegisterMessage(TextAnnotation.DetectedLanguage) -_sym_db.RegisterMessage(TextAnnotation.DetectedBreak) -_sym_db.RegisterMessage(TextAnnotation.TextProperty) - -Page = _reflection.GeneratedProtocolMessageType( - "Page", - (_message.Message,), - { - "DESCRIPTOR": _PAGE, - "__module__": "google.cloud.vision_v1p2beta1.proto.text_annotation_pb2", - "__doc__": """Detected page from OCR. - - Attributes: - property: - Additional information detected on the page. - width: - Page width. For PDFs the unit is points. For images (including - TIFFs) the unit is pixels. - height: - Page height. For PDFs the unit is points. For images - (including TIFFs) the unit is pixels. - blocks: - List of blocks of text, images etc on this page. - confidence: - Confidence of the OCR results on the page. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.Page) - }, -) -_sym_db.RegisterMessage(Page) - -Block = _reflection.GeneratedProtocolMessageType( - "Block", - (_message.Message,), - { - "DESCRIPTOR": _BLOCK, - "__module__": "google.cloud.vision_v1p2beta1.proto.text_annotation_pb2", - "__doc__": """Logical element on the page. - - Attributes: - property: - Additional information detected for the block. - bounding_box: - The bounding box for the block. The vertices are in the order - of top-left, top-right, bottom-right, bottom-left. When a - rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: - - when the text is horizontal it might look like: :: - 0----1 | | 3----2 - when it’s rotated 180 - degrees around the top-left corner it becomes: :: - 2----3 | | 1----0 and the vertice order - will still be (0, 1, 2, 3). - paragraphs: - List of paragraphs in this block (if this blocks is of type - text). - block_type: - Detected block type (text, image etc) for this block. - confidence: - Confidence of the OCR results on the block. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.Block) - }, -) -_sym_db.RegisterMessage(Block) - -Paragraph = _reflection.GeneratedProtocolMessageType( - "Paragraph", - (_message.Message,), - { - "DESCRIPTOR": _PARAGRAPH, - "__module__": "google.cloud.vision_v1p2beta1.proto.text_annotation_pb2", - "__doc__": """Structural unit of text representing a number of words in certain - order. - - Attributes: - property: - Additional information detected for the paragraph. - bounding_box: - The bounding box for the paragraph. The vertices are in the - order of top-left, top-right, bottom-right, bottom-left. When - a rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: \* - when the text is horizontal it might look like: 0—-1 \| \| - 3—-2 \* when it’s rotated 180 degrees around the top-left - corner it becomes: 2—-3 \| \| 1—-0 and the vertice order will - still be (0, 1, 2, 3). - words: - List of words in this paragraph. - confidence: - Confidence of the OCR results for the paragraph. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.Paragraph) - }, -) -_sym_db.RegisterMessage(Paragraph) - -Word = _reflection.GeneratedProtocolMessageType( - "Word", - (_message.Message,), - { - "DESCRIPTOR": _WORD, - "__module__": "google.cloud.vision_v1p2beta1.proto.text_annotation_pb2", - "__doc__": """A word representation. - - Attributes: - property: - Additional information detected for the word. - bounding_box: - The bounding box for the word. The vertices are in the order - of top-left, top-right, bottom-right, bottom-left. When a - rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: \* - when the text is horizontal it might look like: 0—-1 \| \| - 3—-2 \* when it’s rotated 180 degrees around the top-left - corner it becomes: 2—-3 \| \| 1—-0 and the vertice order will - still be (0, 1, 2, 3). - symbols: - List of symbols in the word. The order of the symbols follows - the natural reading order. - confidence: - Confidence of the OCR results for the word. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.Word) - }, -) -_sym_db.RegisterMessage(Word) - -Symbol = _reflection.GeneratedProtocolMessageType( - "Symbol", - (_message.Message,), - { - "DESCRIPTOR": _SYMBOL, - "__module__": "google.cloud.vision_v1p2beta1.proto.text_annotation_pb2", - "__doc__": """A single symbol representation. - - Attributes: - property: - Additional information detected for the symbol. - bounding_box: - The bounding box for the symbol. The vertices are in the order - of top-left, top-right, bottom-right, bottom-left. When a - rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: \* - when the text is horizontal it might look like: 0—-1 \| \| - 3—-2 \* when it’s rotated 180 degrees around the top-left - corner it becomes: 2—-3 \| \| 1—-0 and the vertice order will - still be (0, 1, 2, 3). - text: - The actual UTF-8 representation of the symbol. - confidence: - Confidence of the OCR results for the symbol. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.Symbol) - }, -) -_sym_db.RegisterMessage(Symbol) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p2beta1/proto/text_annotation_pb2_grpc.py b/google/cloud/vision_v1p2beta1/proto/text_annotation_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/vision_v1p2beta1/proto/text_annotation_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/vision_v1p2beta1/proto/web_detection_pb2.py b/google/cloud/vision_v1p2beta1/proto/web_detection_pb2.py deleted file mode 100644 index 1bc4ec76..00000000 --- a/google/cloud/vision_v1p2beta1/proto/web_detection_pb2.py +++ /dev/null @@ -1,628 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p2beta1/proto/web_detection.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p2beta1/proto/web_detection.proto", - package="google.cloud.vision.v1p2beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p2beta1B\021WebDetectionProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p2beta1;vision\370\001\001", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n7google/cloud/vision_v1p2beta1/proto/web_detection.proto\x12\x1dgoogle.cloud.vision.v1p2beta1\x1a\x1cgoogle/api/annotations.proto"\x8c\x07\n\x0cWebDetection\x12K\n\x0cweb_entities\x18\x01 \x03(\x0b\x32\x35.google.cloud.vision.v1p2beta1.WebDetection.WebEntity\x12R\n\x14\x66ull_matching_images\x18\x02 \x03(\x0b\x32\x34.google.cloud.vision.v1p2beta1.WebDetection.WebImage\x12U\n\x17partial_matching_images\x18\x03 \x03(\x0b\x32\x34.google.cloud.vision.v1p2beta1.WebDetection.WebImage\x12W\n\x1apages_with_matching_images\x18\x04 \x03(\x0b\x32\x33.google.cloud.vision.v1p2beta1.WebDetection.WebPage\x12U\n\x17visually_similar_images\x18\x06 \x03(\x0b\x32\x34.google.cloud.vision.v1p2beta1.WebDetection.WebImage\x12O\n\x11\x62\x65st_guess_labels\x18\x08 \x03(\x0b\x32\x34.google.cloud.vision.v1p2beta1.WebDetection.WebLabel\x1a\x42\n\tWebEntity\x12\x11\n\tentity_id\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\x1a&\n\x08WebImage\x12\x0b\n\x03url\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x1a\xe4\x01\n\x07WebPage\x12\x0b\n\x03url\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x12\n\npage_title\x18\x03 \x01(\t\x12R\n\x14\x66ull_matching_images\x18\x04 \x03(\x0b\x32\x34.google.cloud.vision.v1p2beta1.WebDetection.WebImage\x12U\n\x17partial_matching_images\x18\x05 \x03(\x0b\x32\x34.google.cloud.vision.v1p2beta1.WebDetection.WebImage\x1a\x30\n\x08WebLabel\x12\r\n\x05label\x18\x01 \x01(\t\x12\x15\n\rlanguage_code\x18\x02 \x01(\tB\x80\x01\n!com.google.cloud.vision.v1p2beta1B\x11WebDetectionProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p2beta1;vision\xf8\x01\x01\x62\x06proto3', - dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,], -) - - -_WEBDETECTION_WEBENTITY = _descriptor.Descriptor( - name="WebEntity", - full_name="google.cloud.vision.v1p2beta1.WebDetection.WebEntity", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="entity_id", - full_name="google.cloud.vision.v1p2beta1.WebDetection.WebEntity.entity_id", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p2beta1.WebDetection.WebEntity.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.vision.v1p2beta1.WebDetection.WebEntity.description", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=642, - serialized_end=708, -) - -_WEBDETECTION_WEBIMAGE = _descriptor.Descriptor( - name="WebImage", - full_name="google.cloud.vision.v1p2beta1.WebDetection.WebImage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="url", - full_name="google.cloud.vision.v1p2beta1.WebDetection.WebImage.url", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p2beta1.WebDetection.WebImage.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=710, - serialized_end=748, -) - -_WEBDETECTION_WEBPAGE = _descriptor.Descriptor( - name="WebPage", - full_name="google.cloud.vision.v1p2beta1.WebDetection.WebPage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="url", - full_name="google.cloud.vision.v1p2beta1.WebDetection.WebPage.url", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p2beta1.WebDetection.WebPage.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_title", - full_name="google.cloud.vision.v1p2beta1.WebDetection.WebPage.page_title", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="full_matching_images", - full_name="google.cloud.vision.v1p2beta1.WebDetection.WebPage.full_matching_images", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="partial_matching_images", - full_name="google.cloud.vision.v1p2beta1.WebDetection.WebPage.partial_matching_images", - index=4, - number=5, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=751, - serialized_end=979, -) - -_WEBDETECTION_WEBLABEL = _descriptor.Descriptor( - name="WebLabel", - full_name="google.cloud.vision.v1p2beta1.WebDetection.WebLabel", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="label", - full_name="google.cloud.vision.v1p2beta1.WebDetection.WebLabel.label", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="language_code", - full_name="google.cloud.vision.v1p2beta1.WebDetection.WebLabel.language_code", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=981, - serialized_end=1029, -) - -_WEBDETECTION = _descriptor.Descriptor( - name="WebDetection", - full_name="google.cloud.vision.v1p2beta1.WebDetection", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="web_entities", - full_name="google.cloud.vision.v1p2beta1.WebDetection.web_entities", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="full_matching_images", - full_name="google.cloud.vision.v1p2beta1.WebDetection.full_matching_images", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="partial_matching_images", - full_name="google.cloud.vision.v1p2beta1.WebDetection.partial_matching_images", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="pages_with_matching_images", - full_name="google.cloud.vision.v1p2beta1.WebDetection.pages_with_matching_images", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="visually_similar_images", - full_name="google.cloud.vision.v1p2beta1.WebDetection.visually_similar_images", - index=4, - number=6, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="best_guess_labels", - full_name="google.cloud.vision.v1p2beta1.WebDetection.best_guess_labels", - index=5, - number=8, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _WEBDETECTION_WEBENTITY, - _WEBDETECTION_WEBIMAGE, - _WEBDETECTION_WEBPAGE, - _WEBDETECTION_WEBLABEL, - ], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=121, - serialized_end=1029, -) - -_WEBDETECTION_WEBENTITY.containing_type = _WEBDETECTION -_WEBDETECTION_WEBIMAGE.containing_type = _WEBDETECTION -_WEBDETECTION_WEBPAGE.fields_by_name[ - "full_matching_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION_WEBPAGE.fields_by_name[ - "partial_matching_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION_WEBPAGE.containing_type = _WEBDETECTION -_WEBDETECTION_WEBLABEL.containing_type = _WEBDETECTION -_WEBDETECTION.fields_by_name["web_entities"].message_type = _WEBDETECTION_WEBENTITY -_WEBDETECTION.fields_by_name[ - "full_matching_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION.fields_by_name[ - "partial_matching_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION.fields_by_name[ - "pages_with_matching_images" -].message_type = _WEBDETECTION_WEBPAGE -_WEBDETECTION.fields_by_name[ - "visually_similar_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION.fields_by_name["best_guess_labels"].message_type = _WEBDETECTION_WEBLABEL -DESCRIPTOR.message_types_by_name["WebDetection"] = _WEBDETECTION -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -WebDetection = _reflection.GeneratedProtocolMessageType( - "WebDetection", - (_message.Message,), - { - "WebEntity": _reflection.GeneratedProtocolMessageType( - "WebEntity", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTION_WEBENTITY, - "__module__": "google.cloud.vision_v1p2beta1.proto.web_detection_pb2", - "__doc__": """Entity deduced from similar images on the Internet. - - Attributes: - entity_id: - Opaque entity ID. - score: - Overall relevancy score for the entity. Not normalized and not - comparable across different image queries. - description: - Canonical description of the entity, in English. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.WebDetection.WebEntity) - }, - ), - "WebImage": _reflection.GeneratedProtocolMessageType( - "WebImage", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTION_WEBIMAGE, - "__module__": "google.cloud.vision_v1p2beta1.proto.web_detection_pb2", - "__doc__": """Metadata for online images. - - Attributes: - url: - The result image URL. - score: - (Deprecated) Overall relevancy score for the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.WebDetection.WebImage) - }, - ), - "WebPage": _reflection.GeneratedProtocolMessageType( - "WebPage", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTION_WEBPAGE, - "__module__": "google.cloud.vision_v1p2beta1.proto.web_detection_pb2", - "__doc__": """Metadata for web pages. - - Attributes: - url: - The result web page URL. - score: - (Deprecated) Overall relevancy score for the web page. - page_title: - Title for the web page, may contain HTML markups. - full_matching_images: - Fully matching images on the page. Can include resized copies - of the query image. - partial_matching_images: - Partial matching images on the page. Those images are similar - enough to share some key-point features. For example an - original image will likely have partial matching for its - crops. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.WebDetection.WebPage) - }, - ), - "WebLabel": _reflection.GeneratedProtocolMessageType( - "WebLabel", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTION_WEBLABEL, - "__module__": "google.cloud.vision_v1p2beta1.proto.web_detection_pb2", - "__doc__": """Label to provide extra metadata for the web detection. - - Attributes: - label: - Label for extra metadata. - language_code: - The BCP-47 language code for ``label``, such as “en-US” or - “sr-Latn”. For more information, see http://www.unicode.org/re - ports/tr35/#Unicode_locale_identifier. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.WebDetection.WebLabel) - }, - ), - "DESCRIPTOR": _WEBDETECTION, - "__module__": "google.cloud.vision_v1p2beta1.proto.web_detection_pb2", - "__doc__": """Relevant information for the image from the Internet. - - Attributes: - web_entities: - Deduced entities from similar images on the Internet. - full_matching_images: - Fully matching images from the Internet. Can include resized - copies of the query image. - partial_matching_images: - Partial matching images from the Internet. Those images are - similar enough to share some key-point features. For example - an original image will likely have partial matching for its - crops. - pages_with_matching_images: - Web pages containing the matching images from the Internet. - visually_similar_images: - The visually similar image results. - best_guess_labels: - Best guess text labels for the request image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p2beta1.WebDetection) - }, -) -_sym_db.RegisterMessage(WebDetection) -_sym_db.RegisterMessage(WebDetection.WebEntity) -_sym_db.RegisterMessage(WebDetection.WebImage) -_sym_db.RegisterMessage(WebDetection.WebPage) -_sym_db.RegisterMessage(WebDetection.WebLabel) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p2beta1/proto/web_detection_pb2_grpc.py b/google/cloud/vision_v1p2beta1/proto/web_detection_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/vision_v1p2beta1/proto/web_detection_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/vision_v1p2beta1/py.typed b/google/cloud/vision_v1p2beta1/py.typed new file mode 100644 index 00000000..8cb07491 --- /dev/null +++ b/google/cloud/vision_v1p2beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-vision package uses inline types. diff --git a/google/cloud/vision_v1p2beta1/services/__init__.py b/google/cloud/vision_v1p2beta1/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/vision_v1p2beta1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/__init__.py b/google/cloud/vision_v1p2beta1/services/image_annotator/__init__.py new file mode 100644 index 00000000..2b601881 --- /dev/null +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import ImageAnnotatorClient +from .async_client import ImageAnnotatorAsyncClient + +__all__ = ( + "ImageAnnotatorClient", + "ImageAnnotatorAsyncClient", +) diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/async_client.py b/google/cloud/vision_v1p2beta1/services/image_annotator/async_client.py new file mode 100644 index 00000000..2e9b27a3 --- /dev/null +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/async_client.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1p2beta1.types import image_annotator + +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport +from .client import ImageAnnotatorClient + + +class ImageAnnotatorAsyncClient: + """Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + """ + + _client: ImageAnnotatorClient + + DEFAULT_ENDPOINT = ImageAnnotatorClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + + from_service_account_file = ImageAnnotatorClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(ImageAnnotatorClient).get_transport_class, type(ImageAnnotatorClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, ImageAnnotatorTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the image annotator client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ImageAnnotatorTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = ImageAnnotatorClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def batch_annotate_images( + self, + request: image_annotator.BatchAnnotateImagesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateImageRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: + r"""Run image detection and annotation for a batch of + images. + + Args: + request (:class:`~.image_annotator.BatchAnnotateImagesRequest`): + The request object. Multiple image annotation requests + are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AnnotateImageRequest]`): + Required. Individual image annotation + requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.image_annotator.BatchAnnotateImagesResponse: + Response to a batch image annotation + request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([requests]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = image_annotator.BatchAnnotateImagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_annotate_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def async_batch_annotate_files( + self, + request: image_annotator.AsyncBatchAnnotateFilesRequest = None, + *, + requests: Sequence[image_annotator.AsyncAnnotateFileRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Run async image detection and annotation for a list of generic + files (e.g. PDF) which may contain multiple pages and multiple + images per page. Progress and results can be retrieved through + the ``google.longrunning.Operations`` interface. + ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateFilesResponse`` (results). + + Args: + request (:class:`~.image_annotator.AsyncBatchAnnotateFilesRequest`): + The request object. Multiple async file annotation + requests are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AsyncAnnotateFileRequest]`): + Required. Individual async file + annotation requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.image_annotator.AsyncBatchAnnotateFilesResponse``: + Response to an async batch file annotation request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([requests]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = image_annotator.AsyncBatchAnnotateFilesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.async_batch_annotate_files, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + image_annotator.AsyncBatchAnnotateFilesResponse, + metadata_type=image_annotator.OperationMetadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ImageAnnotatorAsyncClient",) diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/client.py b/google/cloud/vision_v1p2beta1/services/image_annotator/client.py new file mode 100644 index 00000000..66a4e53c --- /dev/null +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/client.py @@ -0,0 +1,424 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1p2beta1.types import image_annotator + +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ImageAnnotatorGrpcTransport +from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport + + +class ImageAnnotatorClientMeta(type): + """Metaclass for the ImageAnnotator client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[ImageAnnotatorTransport]] + _transport_registry["grpc"] = ImageAnnotatorGrpcTransport + _transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[ImageAnnotatorTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ImageAnnotatorClient(metaclass=ImageAnnotatorClientMeta): + """Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "vision.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + def __init__( + self, + *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, ImageAnnotatorTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the image annotator client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ImageAnnotatorTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ImageAnnotatorTransport): + # transport is a ImageAnnotatorTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def batch_annotate_images( + self, + request: image_annotator.BatchAnnotateImagesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateImageRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: + r"""Run image detection and annotation for a batch of + images. + + Args: + request (:class:`~.image_annotator.BatchAnnotateImagesRequest`): + The request object. Multiple image annotation requests + are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AnnotateImageRequest]`): + Required. Individual image annotation + requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.image_annotator.BatchAnnotateImagesResponse: + Response to a batch image annotation + request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([requests]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a image_annotator.BatchAnnotateImagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, image_annotator.BatchAnnotateImagesRequest): + request = image_annotator.BatchAnnotateImagesRequest(request) + if requests is not None: + for i in range(len(requests)): + requests[i] = image_annotator.AnnotateImageRequest(requests[i]) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_annotate_images] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def async_batch_annotate_files( + self, + request: image_annotator.AsyncBatchAnnotateFilesRequest = None, + *, + requests: Sequence[image_annotator.AsyncAnnotateFileRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Run async image detection and annotation for a list of generic + files (e.g. PDF) which may contain multiple pages and multiple + images per page. Progress and results can be retrieved through + the ``google.longrunning.Operations`` interface. + ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateFilesResponse`` (results). + + Args: + request (:class:`~.image_annotator.AsyncBatchAnnotateFilesRequest`): + The request object. Multiple async file annotation + requests are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AsyncAnnotateFileRequest]`): + Required. Individual async file + annotation requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.image_annotator.AsyncBatchAnnotateFilesResponse``: + Response to an async batch file annotation request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([requests]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a image_annotator.AsyncBatchAnnotateFilesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, image_annotator.AsyncBatchAnnotateFilesRequest): + request = image_annotator.AsyncBatchAnnotateFilesRequest(request) + if requests is not None: + for i in range(len(requests)): + requests[i] = image_annotator.AsyncAnnotateFileRequest(requests[i]) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.async_batch_annotate_files + ] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + image_annotator.AsyncBatchAnnotateFilesResponse, + metadata_type=image_annotator.OperationMetadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ImageAnnotatorClient",) diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/__init__.py b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/__init__.py new file mode 100644 index 00000000..f2315e0d --- /dev/null +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import ImageAnnotatorTransport +from .grpc import ImageAnnotatorGrpcTransport +from .grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ImageAnnotatorTransport]] +_transport_registry["grpc"] = ImageAnnotatorGrpcTransport +_transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport + + +__all__ = ( + "ImageAnnotatorTransport", + "ImageAnnotatorGrpcTransport", + "ImageAnnotatorGrpcAsyncIOTransport", +) diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py new file mode 100644 index 00000000..f71e6662 --- /dev/null +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.vision_v1p2beta1.types import image_annotator +from google.longrunning import operations_pb2 as operations # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ImageAnnotatorTransport(abc.ABC): + """Abstract transport class for ImageAnnotator.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ) + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.batch_annotate_images: gapic_v1.method.wrap_method( + self.batch_annotate_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.async_batch_annotate_files: gapic_v1.method.wrap_method( + self.async_batch_annotate_files, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def batch_annotate_images( + self, + ) -> typing.Callable[ + [image_annotator.BatchAnnotateImagesRequest], + typing.Union[ + image_annotator.BatchAnnotateImagesResponse, + typing.Awaitable[image_annotator.BatchAnnotateImagesResponse], + ], + ]: + raise NotImplementedError() + + @property + def async_batch_annotate_files( + self, + ) -> typing.Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + +__all__ = ("ImageAnnotatorTransport",) diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py new file mode 100644 index 00000000..6bb99a4d --- /dev/null +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py @@ -0,0 +1,318 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.vision_v1p2beta1.types import image_annotator +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO + + +class ImageAnnotatorGrpcTransport(ImageAnnotatorTransport): + """gRPC backend transport for ImageAnnotator. + + Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def batch_annotate_images( + self, + ) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + image_annotator.BatchAnnotateImagesResponse, + ]: + r"""Return a callable for the batch annotate images method over gRPC. + + Run image detection and annotation for a batch of + images. + + Returns: + Callable[[~.BatchAnnotateImagesRequest], + ~.BatchAnnotateImagesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_annotate_images" not in self._stubs: + self._stubs["batch_annotate_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p2beta1.ImageAnnotator/BatchAnnotateImages", + request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, + response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, + ) + return self._stubs["batch_annotate_images"] + + @property + def async_batch_annotate_files( + self, + ) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], operations.Operation + ]: + r"""Return a callable for the async batch annotate files method over gRPC. + + Run async image detection and annotation for a list of generic + files (e.g. PDF) which may contain multiple pages and multiple + images per page. Progress and results can be retrieved through + the ``google.longrunning.Operations`` interface. + ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateFilesResponse`` (results). + + Returns: + Callable[[~.AsyncBatchAnnotateFilesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "async_batch_annotate_files" not in self._stubs: + self._stubs["async_batch_annotate_files"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p2beta1.ImageAnnotator/AsyncBatchAnnotateFiles", + request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["async_batch_annotate_files"] + + +__all__ = ("ImageAnnotatorGrpcTransport",) diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc_asyncio.py b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc_asyncio.py new file mode 100644 index 00000000..ea82d15b --- /dev/null +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc_asyncio.py @@ -0,0 +1,319 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.vision_v1p2beta1.types import image_annotator +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .grpc import ImageAnnotatorGrpcTransport + + +class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): + """gRPC AsyncIO backend transport for ImageAnnotator. + + Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def batch_annotate_images( + self, + ) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + Awaitable[image_annotator.BatchAnnotateImagesResponse], + ]: + r"""Return a callable for the batch annotate images method over gRPC. + + Run image detection and annotation for a batch of + images. + + Returns: + Callable[[~.BatchAnnotateImagesRequest], + Awaitable[~.BatchAnnotateImagesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_annotate_images" not in self._stubs: + self._stubs["batch_annotate_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p2beta1.ImageAnnotator/BatchAnnotateImages", + request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, + response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, + ) + return self._stubs["batch_annotate_images"] + + @property + def async_batch_annotate_files( + self, + ) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + Awaitable[operations.Operation], + ]: + r"""Return a callable for the async batch annotate files method over gRPC. + + Run async image detection and annotation for a list of generic + files (e.g. PDF) which may contain multiple pages and multiple + images per page. Progress and results can be retrieved through + the ``google.longrunning.Operations`` interface. + ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateFilesResponse`` (results). + + Returns: + Callable[[~.AsyncBatchAnnotateFilesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "async_batch_annotate_files" not in self._stubs: + self._stubs["async_batch_annotate_files"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p2beta1.ImageAnnotator/AsyncBatchAnnotateFiles", + request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["async_batch_annotate_files"] + + +__all__ = ("ImageAnnotatorGrpcAsyncIOTransport",) diff --git a/google/cloud/vision_v1p2beta1/types.py b/google/cloud/vision_v1p2beta1/types.py deleted file mode 100644 index 74d539aa..00000000 --- a/google/cloud/vision_v1p2beta1/types.py +++ /dev/null @@ -1,66 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.vision_v1p2beta1.proto import geometry_pb2 -from google.cloud.vision_v1p2beta1.proto import image_annotator_pb2 -from google.cloud.vision_v1p2beta1.proto import text_annotation_pb2 -from google.cloud.vision_v1p2beta1.proto import web_detection_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import any_pb2 -from google.protobuf import timestamp_pb2 -from google.protobuf import wrappers_pb2 -from google.rpc import status_pb2 -from google.type import color_pb2 -from google.type import latlng_pb2 - - -_shared_modules = [ - operations_pb2, - any_pb2, - timestamp_pb2, - wrappers_pb2, - status_pb2, - color_pb2, - latlng_pb2, -] - -_local_modules = [ - geometry_pb2, - image_annotator_pb2, - text_annotation_pb2, - web_detection_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.vision_v1p2beta1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/vision_v1p2beta1/types/__init__.py b/google/cloud/vision_v1p2beta1/types/__init__.py new file mode 100644 index 00000000..c58236aa --- /dev/null +++ b/google/cloud/vision_v1p2beta1/types/__init__.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .geometry import ( + Vertex, + NormalizedVertex, + BoundingPoly, + Position, +) +from .text_annotation import ( + TextAnnotation, + Page, + Block, + Paragraph, + Word, + Symbol, +) +from .web_detection import WebDetection +from .image_annotator import ( + Feature, + ImageSource, + Image, + FaceAnnotation, + LocationInfo, + Property, + EntityAnnotation, + SafeSearchAnnotation, + LatLongRect, + ColorInfo, + DominantColorsAnnotation, + ImageProperties, + CropHint, + CropHintsAnnotation, + CropHintsParams, + WebDetectionParams, + ImageContext, + AnnotateImageRequest, + ImageAnnotationContext, + AnnotateImageResponse, + AnnotateFileResponse, + BatchAnnotateImagesRequest, + BatchAnnotateImagesResponse, + AsyncAnnotateFileRequest, + AsyncAnnotateFileResponse, + AsyncBatchAnnotateFilesRequest, + AsyncBatchAnnotateFilesResponse, + InputConfig, + OutputConfig, + GcsSource, + GcsDestination, + OperationMetadata, +) + + +__all__ = ( + "Vertex", + "NormalizedVertex", + "BoundingPoly", + "Position", + "TextAnnotation", + "Page", + "Block", + "Paragraph", + "Word", + "Symbol", + "WebDetection", + "Feature", + "ImageSource", + "Image", + "FaceAnnotation", + "LocationInfo", + "Property", + "EntityAnnotation", + "SafeSearchAnnotation", + "LatLongRect", + "ColorInfo", + "DominantColorsAnnotation", + "ImageProperties", + "CropHint", + "CropHintsAnnotation", + "CropHintsParams", + "WebDetectionParams", + "ImageContext", + "AnnotateImageRequest", + "ImageAnnotationContext", + "AnnotateImageResponse", + "AnnotateFileResponse", + "BatchAnnotateImagesRequest", + "BatchAnnotateImagesResponse", + "AsyncAnnotateFileRequest", + "AsyncAnnotateFileResponse", + "AsyncBatchAnnotateFilesRequest", + "AsyncBatchAnnotateFilesResponse", + "InputConfig", + "OutputConfig", + "GcsSource", + "GcsDestination", + "OperationMetadata", +) diff --git a/google/cloud/vision_v1p2beta1/types/geometry.py b/google/cloud/vision_v1p2beta1/types/geometry.py new file mode 100644 index 00000000..ce17fcf1 --- /dev/null +++ b/google/cloud/vision_v1p2beta1/types/geometry.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p2beta1", + manifest={"Vertex", "NormalizedVertex", "BoundingPoly", "Position",}, +) + + +class Vertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the vertex coordinates are in the same scale as the + original image. + + Attributes: + x (int): + X coordinate. + y (int): + Y coordinate. + """ + + x = proto.Field(proto.INT32, number=1) + + y = proto.Field(proto.INT32, number=2) + + +class NormalizedVertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the normalized vertex coordinates are relative to the + original image and range from 0 to 1. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate. + """ + + x = proto.Field(proto.FLOAT, number=1) + + y = proto.Field(proto.FLOAT, number=2) + + +class BoundingPoly(proto.Message): + r"""A bounding polygon for the detected image annotation. + + Attributes: + vertices (Sequence[~.geometry.Vertex]): + The bounding polygon vertices. + normalized_vertices (Sequence[~.geometry.NormalizedVertex]): + The bounding polygon normalized vertices. + """ + + vertices = proto.RepeatedField(proto.MESSAGE, number=1, message=Vertex,) + + normalized_vertices = proto.RepeatedField( + proto.MESSAGE, number=2, message=NormalizedVertex, + ) + + +class Position(proto.Message): + r"""A 3D position in the image, used primarily for Face detection + landmarks. A valid Position must have both x and y coordinates. + The position coordinates are in the same scale as the original + image. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate. + z (float): + Z coordinate (or depth). + """ + + x = proto.Field(proto.FLOAT, number=1) + + y = proto.Field(proto.FLOAT, number=2) + + z = proto.Field(proto.FLOAT, number=3) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p2beta1/types/image_annotator.py b/google/cloud/vision_v1p2beta1/types/image_annotator.py new file mode 100644 index 00000000..a1f2ad65 --- /dev/null +++ b/google/cloud/vision_v1p2beta1/types/image_annotator.py @@ -0,0 +1,983 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.vision_v1p2beta1.types import geometry +from google.cloud.vision_v1p2beta1.types import text_annotation +from google.cloud.vision_v1p2beta1.types import web_detection as gcv_web_detection +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore +from google.type import color_pb2 as gt_color # type: ignore +from google.type import latlng_pb2 as latlng # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p2beta1", + manifest={ + "Likelihood", + "Feature", + "ImageSource", + "Image", + "FaceAnnotation", + "LocationInfo", + "Property", + "EntityAnnotation", + "SafeSearchAnnotation", + "LatLongRect", + "ColorInfo", + "DominantColorsAnnotation", + "ImageProperties", + "CropHint", + "CropHintsAnnotation", + "CropHintsParams", + "WebDetectionParams", + "ImageContext", + "AnnotateImageRequest", + "ImageAnnotationContext", + "AnnotateImageResponse", + "AnnotateFileResponse", + "BatchAnnotateImagesRequest", + "BatchAnnotateImagesResponse", + "AsyncAnnotateFileRequest", + "AsyncAnnotateFileResponse", + "AsyncBatchAnnotateFilesRequest", + "AsyncBatchAnnotateFilesResponse", + "InputConfig", + "OutputConfig", + "GcsSource", + "GcsDestination", + "OperationMetadata", + }, +) + + +class Likelihood(proto.Enum): + r"""A bucketized representation of likelihood, which is intended + to give clients highly stable results across model upgrades. + """ + UNKNOWN = 0 + VERY_UNLIKELY = 1 + UNLIKELY = 2 + POSSIBLE = 3 + LIKELY = 4 + VERY_LIKELY = 5 + + +class Feature(proto.Message): + r"""The type of Google Cloud Vision API detection to perform, and the + maximum number of results to return for that type. Multiple + ``Feature`` objects can be specified in the ``features`` list. + + Attributes: + type_ (~.image_annotator.Feature.Type): + The feature type. + max_results (int): + Maximum number of results of this type. Does not apply to + ``TEXT_DETECTION``, ``DOCUMENT_TEXT_DETECTION``, or + ``CROP_HINTS``. + model (str): + Model to use for the feature. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + class Type(proto.Enum): + r"""Type of Google Cloud Vision API feature to be extracted.""" + TYPE_UNSPECIFIED = 0 + FACE_DETECTION = 1 + LANDMARK_DETECTION = 2 + LOGO_DETECTION = 3 + LABEL_DETECTION = 4 + TEXT_DETECTION = 5 + DOCUMENT_TEXT_DETECTION = 11 + SAFE_SEARCH_DETECTION = 6 + IMAGE_PROPERTIES = 7 + CROP_HINTS = 9 + WEB_DETECTION = 10 + + type_ = proto.Field(proto.ENUM, number=1, enum=Type,) + + max_results = proto.Field(proto.INT32, number=2) + + model = proto.Field(proto.STRING, number=3) + + +class ImageSource(proto.Message): + r"""External image source (Google Cloud Storage or web URL image + location). + + Attributes: + gcs_image_uri (str): + **Use ``image_uri`` instead.** + + The Google Cloud Storage URI of the form + ``gs://bucket_name/object_name``. Object versioning is not + supported. See `Google Cloud Storage Request + URIs `__ + for more info. + image_uri (str): + The URI of the source image. Can be either: + + 1. A Google Cloud Storage URI of the form + ``gs://bucket_name/object_name``. Object versioning is + not supported. See `Google Cloud Storage Request + URIs `__ + for more info. + + 2. A publicly-accessible image HTTP/HTTPS URL. When fetching + images from HTTP/HTTPS URLs, Google cannot guarantee that + the request will be completed. Your request may fail if + the specified host denies the request (e.g. due to + request throttling or DOS prevention), or if Google + throttles requests to the site for abuse prevention. You + should not depend on externally-hosted images for + production applications. + + When both ``gcs_image_uri`` and ``image_uri`` are specified, + ``image_uri`` takes precedence. + """ + + gcs_image_uri = proto.Field(proto.STRING, number=1) + + image_uri = proto.Field(proto.STRING, number=2) + + +class Image(proto.Message): + r"""Client image to perform Google Cloud Vision API tasks over. + + Attributes: + content (bytes): + Image content, represented as a stream of bytes. Note: As + with all ``bytes`` fields, protobuffers use a pure binary + representation, whereas JSON representations use base64. + source (~.image_annotator.ImageSource): + Google Cloud Storage image location, or publicly-accessible + image URL. If both ``content`` and ``source`` are provided + for an image, ``content`` takes precedence and is used to + perform the image annotation request. + """ + + content = proto.Field(proto.BYTES, number=1) + + source = proto.Field(proto.MESSAGE, number=2, message=ImageSource,) + + +class FaceAnnotation(proto.Message): + r"""A face annotation object contains the results of face + detection. + + Attributes: + bounding_poly (~.geometry.BoundingPoly): + The bounding polygon around the face. The coordinates of the + bounding box are in the original image's scale, as returned + in ``ImageParams``. The bounding box is computed to "frame" + the face in accordance with human expectations. It is based + on the landmarker results. Note that one or more x and/or y + coordinates may not be generated in the ``BoundingPoly`` + (the polygon will be unbounded) if only a partial face + appears in the image to be annotated. + fd_bounding_poly (~.geometry.BoundingPoly): + The ``fd_bounding_poly`` bounding polygon is tighter than + the ``boundingPoly``, and encloses only the skin part of the + face. Typically, it is used to eliminate the face from any + image analysis that detects the "amount of skin" visible in + an image. It is not based on the landmarker results, only on + the initial face detection, hence the fd (face detection) + prefix. + landmarks (Sequence[~.image_annotator.FaceAnnotation.Landmark]): + Detected face landmarks. + roll_angle (float): + Roll angle, which indicates the amount of + clockwise/anti-clockwise rotation of the face relative to + the image vertical about the axis perpendicular to the face. + Range [-180,180]. + pan_angle (float): + Yaw angle, which indicates the leftward/rightward angle that + the face is pointing relative to the vertical plane + perpendicular to the image. Range [-180,180]. + tilt_angle (float): + Pitch angle, which indicates the upwards/downwards angle + that the face is pointing relative to the image's horizontal + plane. Range [-180,180]. + detection_confidence (float): + Detection confidence. Range [0, 1]. + landmarking_confidence (float): + Face landmarking confidence. Range [0, 1]. + joy_likelihood (~.image_annotator.Likelihood): + Joy likelihood. + sorrow_likelihood (~.image_annotator.Likelihood): + Sorrow likelihood. + anger_likelihood (~.image_annotator.Likelihood): + Anger likelihood. + surprise_likelihood (~.image_annotator.Likelihood): + Surprise likelihood. + under_exposed_likelihood (~.image_annotator.Likelihood): + Under-exposed likelihood. + blurred_likelihood (~.image_annotator.Likelihood): + Blurred likelihood. + headwear_likelihood (~.image_annotator.Likelihood): + Headwear likelihood. + """ + + class Landmark(proto.Message): + r"""A face-specific landmark (for example, a face feature). + + Attributes: + type_ (~.image_annotator.FaceAnnotation.Landmark.Type): + Face landmark type. + position (~.geometry.Position): + Face landmark position. + """ + + class Type(proto.Enum): + r"""Face landmark (feature) type. Left and right are defined from the + vantage of the viewer of the image without considering mirror + projections typical of photos. So, ``LEFT_EYE``, typically, is the + person's right eye. + """ + UNKNOWN_LANDMARK = 0 + LEFT_EYE = 1 + RIGHT_EYE = 2 + LEFT_OF_LEFT_EYEBROW = 3 + RIGHT_OF_LEFT_EYEBROW = 4 + LEFT_OF_RIGHT_EYEBROW = 5 + RIGHT_OF_RIGHT_EYEBROW = 6 + MIDPOINT_BETWEEN_EYES = 7 + NOSE_TIP = 8 + UPPER_LIP = 9 + LOWER_LIP = 10 + MOUTH_LEFT = 11 + MOUTH_RIGHT = 12 + MOUTH_CENTER = 13 + NOSE_BOTTOM_RIGHT = 14 + NOSE_BOTTOM_LEFT = 15 + NOSE_BOTTOM_CENTER = 16 + LEFT_EYE_TOP_BOUNDARY = 17 + LEFT_EYE_RIGHT_CORNER = 18 + LEFT_EYE_BOTTOM_BOUNDARY = 19 + LEFT_EYE_LEFT_CORNER = 20 + RIGHT_EYE_TOP_BOUNDARY = 21 + RIGHT_EYE_RIGHT_CORNER = 22 + RIGHT_EYE_BOTTOM_BOUNDARY = 23 + RIGHT_EYE_LEFT_CORNER = 24 + LEFT_EYEBROW_UPPER_MIDPOINT = 25 + RIGHT_EYEBROW_UPPER_MIDPOINT = 26 + LEFT_EAR_TRAGION = 27 + RIGHT_EAR_TRAGION = 28 + LEFT_EYE_PUPIL = 29 + RIGHT_EYE_PUPIL = 30 + FOREHEAD_GLABELLA = 31 + CHIN_GNATHION = 32 + CHIN_LEFT_GONION = 33 + CHIN_RIGHT_GONION = 34 + + type_ = proto.Field(proto.ENUM, number=3, enum="FaceAnnotation.Landmark.Type",) + + position = proto.Field(proto.MESSAGE, number=4, message=geometry.Position,) + + bounding_poly = proto.Field(proto.MESSAGE, number=1, message=geometry.BoundingPoly,) + + fd_bounding_poly = proto.Field( + proto.MESSAGE, number=2, message=geometry.BoundingPoly, + ) + + landmarks = proto.RepeatedField(proto.MESSAGE, number=3, message=Landmark,) + + roll_angle = proto.Field(proto.FLOAT, number=4) + + pan_angle = proto.Field(proto.FLOAT, number=5) + + tilt_angle = proto.Field(proto.FLOAT, number=6) + + detection_confidence = proto.Field(proto.FLOAT, number=7) + + landmarking_confidence = proto.Field(proto.FLOAT, number=8) + + joy_likelihood = proto.Field(proto.ENUM, number=9, enum="Likelihood",) + + sorrow_likelihood = proto.Field(proto.ENUM, number=10, enum="Likelihood",) + + anger_likelihood = proto.Field(proto.ENUM, number=11, enum="Likelihood",) + + surprise_likelihood = proto.Field(proto.ENUM, number=12, enum="Likelihood",) + + under_exposed_likelihood = proto.Field(proto.ENUM, number=13, enum="Likelihood",) + + blurred_likelihood = proto.Field(proto.ENUM, number=14, enum="Likelihood",) + + headwear_likelihood = proto.Field(proto.ENUM, number=15, enum="Likelihood",) + + +class LocationInfo(proto.Message): + r"""Detected entity location information. + + Attributes: + lat_lng (~.latlng.LatLng): + lat/long location coordinates. + """ + + lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng.LatLng,) + + +class Property(proto.Message): + r"""A ``Property`` consists of a user-supplied name/value pair. + + Attributes: + name (str): + Name of the property. + value (str): + Value of the property. + uint64_value (int): + Value of numeric properties. + """ + + name = proto.Field(proto.STRING, number=1) + + value = proto.Field(proto.STRING, number=2) + + uint64_value = proto.Field(proto.UINT64, number=3) + + +class EntityAnnotation(proto.Message): + r"""Set of detected entity features. + + Attributes: + mid (str): + Opaque entity ID. Some IDs may be available in `Google + Knowledge Graph Search + API `__. + locale (str): + The language code for the locale in which the entity textual + ``description`` is expressed. + description (str): + Entity textual description, expressed in its ``locale`` + language. + score (float): + Overall score of the result. Range [0, 1]. + confidence (float): + **Deprecated. Use ``score`` instead.** The accuracy of the + entity detection in an image. For example, for an image in + which the "Eiffel Tower" entity is detected, this field + represents the confidence that there is a tower in the query + image. Range [0, 1]. + topicality (float): + The relevancy of the ICA (Image Content Annotation) label to + the image. For example, the relevancy of "tower" is likely + higher to an image containing the detected "Eiffel Tower" + than to an image containing a detected distant towering + building, even though the confidence that there is a tower + in each image may be the same. Range [0, 1]. + bounding_poly (~.geometry.BoundingPoly): + Image region to which this entity belongs. Not produced for + ``LABEL_DETECTION`` features. + locations (Sequence[~.image_annotator.LocationInfo]): + The location information for the detected entity. Multiple + ``LocationInfo`` elements can be present because one + location may indicate the location of the scene in the + image, and another location may indicate the location of the + place where the image was taken. Location information is + usually present for landmarks. + properties (Sequence[~.image_annotator.Property]): + Some entities may have optional user-supplied ``Property`` + (name/value) fields, such a score or string that qualifies + the entity. + """ + + mid = proto.Field(proto.STRING, number=1) + + locale = proto.Field(proto.STRING, number=2) + + description = proto.Field(proto.STRING, number=3) + + score = proto.Field(proto.FLOAT, number=4) + + confidence = proto.Field(proto.FLOAT, number=5) + + topicality = proto.Field(proto.FLOAT, number=6) + + bounding_poly = proto.Field(proto.MESSAGE, number=7, message=geometry.BoundingPoly,) + + locations = proto.RepeatedField(proto.MESSAGE, number=8, message=LocationInfo,) + + properties = proto.RepeatedField(proto.MESSAGE, number=9, message=Property,) + + +class SafeSearchAnnotation(proto.Message): + r"""Set of features pertaining to the image, computed by computer + vision methods over safe-search verticals (for example, adult, + spoof, medical, violence). + + Attributes: + adult (~.image_annotator.Likelihood): + Represents the adult content likelihood for + the image. Adult content may contain elements + such as nudity, pornographic images or cartoons, + or sexual activities. + spoof (~.image_annotator.Likelihood): + Spoof likelihood. The likelihood that an + modification was made to the image's canonical + version to make it appear funny or offensive. + medical (~.image_annotator.Likelihood): + Likelihood that this is a medical image. + violence (~.image_annotator.Likelihood): + Likelihood that this image contains violent + content. + racy (~.image_annotator.Likelihood): + Likelihood that the request image contains + racy content. Racy content may include (but is + not limited to) skimpy or sheer clothing, + strategically covered nudity, lewd or + provocative poses, or close-ups of sensitive + body areas. + """ + + adult = proto.Field(proto.ENUM, number=1, enum="Likelihood",) + + spoof = proto.Field(proto.ENUM, number=2, enum="Likelihood",) + + medical = proto.Field(proto.ENUM, number=3, enum="Likelihood",) + + violence = proto.Field(proto.ENUM, number=4, enum="Likelihood",) + + racy = proto.Field(proto.ENUM, number=9, enum="Likelihood",) + + +class LatLongRect(proto.Message): + r"""Rectangle determined by min and max ``LatLng`` pairs. + + Attributes: + min_lat_lng (~.latlng.LatLng): + Min lat/long pair. + max_lat_lng (~.latlng.LatLng): + Max lat/long pair. + """ + + min_lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng.LatLng,) + + max_lat_lng = proto.Field(proto.MESSAGE, number=2, message=latlng.LatLng,) + + +class ColorInfo(proto.Message): + r"""Color information consists of RGB channels, score, and the + fraction of the image that the color occupies in the image. + + Attributes: + color (~.gt_color.Color): + RGB components of the color. + score (float): + Image-specific score for this color. Value in range [0, 1]. + pixel_fraction (float): + The fraction of pixels the color occupies in the image. + Value in range [0, 1]. + """ + + color = proto.Field(proto.MESSAGE, number=1, message=gt_color.Color,) + + score = proto.Field(proto.FLOAT, number=2) + + pixel_fraction = proto.Field(proto.FLOAT, number=3) + + +class DominantColorsAnnotation(proto.Message): + r"""Set of dominant colors and their corresponding scores. + + Attributes: + colors (Sequence[~.image_annotator.ColorInfo]): + RGB color values with their score and pixel + fraction. + """ + + colors = proto.RepeatedField(proto.MESSAGE, number=1, message=ColorInfo,) + + +class ImageProperties(proto.Message): + r"""Stores image properties, such as dominant colors. + + Attributes: + dominant_colors (~.image_annotator.DominantColorsAnnotation): + If present, dominant colors completed + successfully. + """ + + dominant_colors = proto.Field( + proto.MESSAGE, number=1, message=DominantColorsAnnotation, + ) + + +class CropHint(proto.Message): + r"""Single crop hint that is used to generate a new crop when + serving an image. + + Attributes: + bounding_poly (~.geometry.BoundingPoly): + The bounding polygon for the crop region. The coordinates of + the bounding box are in the original image's scale, as + returned in ``ImageParams``. + confidence (float): + Confidence of this being a salient region. Range [0, 1]. + importance_fraction (float): + Fraction of importance of this salient region + with respect to the original image. + """ + + bounding_poly = proto.Field(proto.MESSAGE, number=1, message=geometry.BoundingPoly,) + + confidence = proto.Field(proto.FLOAT, number=2) + + importance_fraction = proto.Field(proto.FLOAT, number=3) + + +class CropHintsAnnotation(proto.Message): + r"""Set of crop hints that are used to generate new crops when + serving images. + + Attributes: + crop_hints (Sequence[~.image_annotator.CropHint]): + Crop hint results. + """ + + crop_hints = proto.RepeatedField(proto.MESSAGE, number=1, message=CropHint,) + + +class CropHintsParams(proto.Message): + r"""Parameters for crop hints annotation request. + + Attributes: + aspect_ratios (Sequence[float]): + Aspect ratios in floats, representing the + ratio of the width to the height of the image. + For example, if the desired aspect ratio is 4/3, + the corresponding float value should be 1.33333. + If not specified, the best possible crop is + returned. The number of provided aspect ratios + is limited to a maximum of 16; any aspect ratios + provided after the 16th are ignored. + """ + + aspect_ratios = proto.RepeatedField(proto.FLOAT, number=1) + + +class WebDetectionParams(proto.Message): + r"""Parameters for web detection request. + + Attributes: + include_geo_results (bool): + Whether to include results derived from the + geo information in the image. + """ + + include_geo_results = proto.Field(proto.BOOL, number=2) + + +class ImageContext(proto.Message): + r"""Image context and/or feature-specific parameters. + + Attributes: + lat_long_rect (~.image_annotator.LatLongRect): + Not used. + language_hints (Sequence[str]): + List of languages to use for TEXT_DETECTION. In most cases, + an empty value yields the best results since it enables + automatic language detection. For languages based on the + Latin alphabet, setting ``language_hints`` is not needed. In + rare cases, when the language of the text in the image is + known, setting a hint will help get better results (although + it will be a significant hindrance if the hint is wrong). + Text detection returns an error if one or more of the + specified languages is not one of the `supported + languages `__. + crop_hints_params (~.image_annotator.CropHintsParams): + Parameters for crop hints annotation request. + web_detection_params (~.image_annotator.WebDetectionParams): + Parameters for web detection. + """ + + lat_long_rect = proto.Field(proto.MESSAGE, number=1, message=LatLongRect,) + + language_hints = proto.RepeatedField(proto.STRING, number=2) + + crop_hints_params = proto.Field(proto.MESSAGE, number=4, message=CropHintsParams,) + + web_detection_params = proto.Field( + proto.MESSAGE, number=6, message=WebDetectionParams, + ) + + +class AnnotateImageRequest(proto.Message): + r"""Request for performing Google Cloud Vision API tasks over a + user-provided image, with user-requested features. + + Attributes: + image (~.image_annotator.Image): + The image to be processed. + features (Sequence[~.image_annotator.Feature]): + Requested features. + image_context (~.image_annotator.ImageContext): + Additional context that may accompany the + image. + """ + + image = proto.Field(proto.MESSAGE, number=1, message=Image,) + + features = proto.RepeatedField(proto.MESSAGE, number=2, message=Feature,) + + image_context = proto.Field(proto.MESSAGE, number=3, message=ImageContext,) + + +class ImageAnnotationContext(proto.Message): + r"""If an image was produced from a file (e.g. a PDF), this + message gives information about the source of that image. + + Attributes: + uri (str): + The URI of the file used to produce the + image. + page_number (int): + If the file was a PDF or TIFF, this field + gives the page number within the file used to + produce the image. + """ + + uri = proto.Field(proto.STRING, number=1) + + page_number = proto.Field(proto.INT32, number=2) + + +class AnnotateImageResponse(proto.Message): + r"""Response to an image annotation request. + + Attributes: + face_annotations (Sequence[~.image_annotator.FaceAnnotation]): + If present, face detection has completed + successfully. + landmark_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, landmark detection has completed + successfully. + logo_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, logo detection has completed + successfully. + label_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, label detection has completed + successfully. + text_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, text (OCR) detection has + completed successfully. + full_text_annotation (~.text_annotation.TextAnnotation): + If present, text (OCR) detection or document + (OCR) text detection has completed successfully. + This annotation provides the structural + hierarchy for the OCR detected text. + safe_search_annotation (~.image_annotator.SafeSearchAnnotation): + If present, safe-search annotation has + completed successfully. + image_properties_annotation (~.image_annotator.ImageProperties): + If present, image properties were extracted + successfully. + crop_hints_annotation (~.image_annotator.CropHintsAnnotation): + If present, crop hints have completed + successfully. + web_detection (~.gcv_web_detection.WebDetection): + If present, web detection has completed + successfully. + error (~.status.Status): + If set, represents the error message for the operation. Note + that filled-in image annotations are guaranteed to be + correct, even when ``error`` is set. + context (~.image_annotator.ImageAnnotationContext): + If present, contextual information is needed + to understand where this image comes from. + """ + + face_annotations = proto.RepeatedField( + proto.MESSAGE, number=1, message=FaceAnnotation, + ) + + landmark_annotations = proto.RepeatedField( + proto.MESSAGE, number=2, message=EntityAnnotation, + ) + + logo_annotations = proto.RepeatedField( + proto.MESSAGE, number=3, message=EntityAnnotation, + ) + + label_annotations = proto.RepeatedField( + proto.MESSAGE, number=4, message=EntityAnnotation, + ) + + text_annotations = proto.RepeatedField( + proto.MESSAGE, number=5, message=EntityAnnotation, + ) + + full_text_annotation = proto.Field( + proto.MESSAGE, number=12, message=text_annotation.TextAnnotation, + ) + + safe_search_annotation = proto.Field( + proto.MESSAGE, number=6, message=SafeSearchAnnotation, + ) + + image_properties_annotation = proto.Field( + proto.MESSAGE, number=8, message=ImageProperties, + ) + + crop_hints_annotation = proto.Field( + proto.MESSAGE, number=11, message=CropHintsAnnotation, + ) + + web_detection = proto.Field( + proto.MESSAGE, number=13, message=gcv_web_detection.WebDetection, + ) + + error = proto.Field(proto.MESSAGE, number=9, message=status.Status,) + + context = proto.Field(proto.MESSAGE, number=21, message=ImageAnnotationContext,) + + +class AnnotateFileResponse(proto.Message): + r"""Response to a single file annotation request. A file may + contain one or more images, which individually have their own + responses. + + Attributes: + input_config (~.image_annotator.InputConfig): + Information about the file for which this + response is generated. + responses (Sequence[~.image_annotator.AnnotateImageResponse]): + Individual responses to images found within + the file. + """ + + input_config = proto.Field(proto.MESSAGE, number=1, message="InputConfig",) + + responses = proto.RepeatedField( + proto.MESSAGE, number=2, message=AnnotateImageResponse, + ) + + +class BatchAnnotateImagesRequest(proto.Message): + r"""Multiple image annotation requests are batched into a single + service call. + + Attributes: + requests (Sequence[~.image_annotator.AnnotateImageRequest]): + Required. Individual image annotation + requests for this batch. + """ + + requests = proto.RepeatedField( + proto.MESSAGE, number=1, message=AnnotateImageRequest, + ) + + +class BatchAnnotateImagesResponse(proto.Message): + r"""Response to a batch image annotation request. + + Attributes: + responses (Sequence[~.image_annotator.AnnotateImageResponse]): + Individual responses to image annotation + requests within the batch. + """ + + responses = proto.RepeatedField( + proto.MESSAGE, number=1, message=AnnotateImageResponse, + ) + + +class AsyncAnnotateFileRequest(proto.Message): + r"""An offline file annotation request. + + Attributes: + input_config (~.image_annotator.InputConfig): + Required. Information about the input file. + features (Sequence[~.image_annotator.Feature]): + Required. Requested features. + image_context (~.image_annotator.ImageContext): + Additional context that may accompany the + image(s) in the file. + output_config (~.image_annotator.OutputConfig): + Required. The desired output location and + metadata (e.g. format). + """ + + input_config = proto.Field(proto.MESSAGE, number=1, message="InputConfig",) + + features = proto.RepeatedField(proto.MESSAGE, number=2, message=Feature,) + + image_context = proto.Field(proto.MESSAGE, number=3, message=ImageContext,) + + output_config = proto.Field(proto.MESSAGE, number=4, message="OutputConfig",) + + +class AsyncAnnotateFileResponse(proto.Message): + r"""The response for a single offline file annotation request. + + Attributes: + output_config (~.image_annotator.OutputConfig): + The output location and metadata from + AsyncAnnotateFileRequest. + """ + + output_config = proto.Field(proto.MESSAGE, number=1, message="OutputConfig",) + + +class AsyncBatchAnnotateFilesRequest(proto.Message): + r"""Multiple async file annotation requests are batched into a + single service call. + + Attributes: + requests (Sequence[~.image_annotator.AsyncAnnotateFileRequest]): + Required. Individual async file annotation + requests for this batch. + """ + + requests = proto.RepeatedField( + proto.MESSAGE, number=1, message=AsyncAnnotateFileRequest, + ) + + +class AsyncBatchAnnotateFilesResponse(proto.Message): + r"""Response to an async batch file annotation request. + + Attributes: + responses (Sequence[~.image_annotator.AsyncAnnotateFileResponse]): + The list of file annotation responses, one + for each request in + AsyncBatchAnnotateFilesRequest. + """ + + responses = proto.RepeatedField( + proto.MESSAGE, number=1, message=AsyncAnnotateFileResponse, + ) + + +class InputConfig(proto.Message): + r"""The desired input location and metadata. + + Attributes: + gcs_source (~.image_annotator.GcsSource): + The Google Cloud Storage location to read the + input from. + mime_type (str): + The type of the file. Currently only + "application/pdf" and "image/tiff" are + supported. Wildcards are not supported. + """ + + gcs_source = proto.Field(proto.MESSAGE, number=1, message="GcsSource",) + + mime_type = proto.Field(proto.STRING, number=2) + + +class OutputConfig(proto.Message): + r"""The desired output location and metadata. + + Attributes: + gcs_destination (~.image_annotator.GcsDestination): + The Google Cloud Storage location to write + the output(s) to. + batch_size (int): + The max number of response protos to put into each output + JSON file on GCS. The valid range is [1, 100]. If not + specified, the default value is 20. + + For example, for one pdf file with 100 pages, 100 response + protos will be generated. If ``batch_size`` = 20, then 5 + json files each containing 20 response protos will be + written under the prefix ``gcs_destination``.\ ``uri``. + + Currently, batch_size only applies to GcsDestination, with + potential future support for other output configurations. + """ + + gcs_destination = proto.Field(proto.MESSAGE, number=1, message="GcsDestination",) + + batch_size = proto.Field(proto.INT32, number=2) + + +class GcsSource(proto.Message): + r"""The Google Cloud Storage location where the input will be + read from. + + Attributes: + uri (str): + Google Cloud Storage URI for the input file. + This must only be a GCS object. Wildcards are + not currently supported. + """ + + uri = proto.Field(proto.STRING, number=1) + + +class GcsDestination(proto.Message): + r"""The Google Cloud Storage location where the output will be + written to. + + Attributes: + uri (str): + Google Cloud Storage URI where the results will be stored. + Results will be in JSON format and preceded by its + corresponding input URI. This field can either represent a + single file, or a prefix for multiple outputs. Prefixes must + end in a ``/``. + + Examples: + + - File: gs://bucket-name/filename.json + - Prefix: gs://bucket-name/prefix/here/ + - File: gs://bucket-name/prefix/here + + If multiple outputs, each response is still + AnnotateFileResponse, each of which contains some subset of + the full list of AnnotateImageResponse. Multiple outputs can + happen if, for example, the output JSON is too large and + overflows into multiple sharded files. + """ + + uri = proto.Field(proto.STRING, number=1) + + +class OperationMetadata(proto.Message): + r"""Contains metadata for the BatchAnnotateImages operation. + + Attributes: + state (~.image_annotator.OperationMetadata.State): + Current state of the batch operation. + create_time (~.timestamp.Timestamp): + The time when the batch request was received. + update_time (~.timestamp.Timestamp): + The time when the operation result was last + updated. + """ + + class State(proto.Enum): + r"""Batch operation states.""" + STATE_UNSPECIFIED = 0 + CREATED = 1 + RUNNING = 2 + DONE = 3 + CANCELLED = 4 + + state = proto.Field(proto.ENUM, number=1, enum=State,) + + create_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + + update_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p2beta1/types/text_annotation.py b/google/cloud/vision_v1p2beta1/types/text_annotation.py new file mode 100644 index 00000000..d7ca587b --- /dev/null +++ b/google/cloud/vision_v1p2beta1/types/text_annotation.py @@ -0,0 +1,320 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.vision_v1p2beta1.types import geometry + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p2beta1", + manifest={"TextAnnotation", "Page", "Block", "Paragraph", "Word", "Symbol",}, +) + + +class TextAnnotation(proto.Message): + r"""TextAnnotation contains a structured representation of OCR extracted + text. The hierarchy of an OCR extracted text structure is like this: + TextAnnotation -> Page -> Block -> Paragraph -> Word -> Symbol Each + structural component, starting from Page, may further have their own + properties. Properties describe detected languages, breaks etc.. + Please refer to the + [TextAnnotation.TextProperty][google.cloud.vision.v1p2beta1.TextAnnotation.TextProperty] + message definition below for more detail. + + Attributes: + pages (Sequence[~.text_annotation.Page]): + List of pages detected by OCR. + text (str): + UTF-8 text detected on the pages. + """ + + class DetectedLanguage(proto.Message): + r"""Detected language for a structural component. + + Attributes: + language_code (str): + The BCP-47 language code, such as "en-US" or "sr-Latn". For + more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + confidence (float): + Confidence of detected language. Range [0, 1]. + """ + + language_code = proto.Field(proto.STRING, number=1) + + confidence = proto.Field(proto.FLOAT, number=2) + + class DetectedBreak(proto.Message): + r"""Detected start or end of a structural component. + + Attributes: + type_ (~.text_annotation.TextAnnotation.DetectedBreak.BreakType): + Detected break type. + is_prefix (bool): + True if break prepends the element. + """ + + class BreakType(proto.Enum): + r"""Enum to denote the type of break found. New line, space etc.""" + UNKNOWN = 0 + SPACE = 1 + SURE_SPACE = 2 + EOL_SURE_SPACE = 3 + HYPHEN = 4 + LINE_BREAK = 5 + + type_ = proto.Field( + proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", + ) + + is_prefix = proto.Field(proto.BOOL, number=2) + + class TextProperty(proto.Message): + r"""Additional information detected on the structural component. + + Attributes: + detected_languages (Sequence[~.text_annotation.TextAnnotation.DetectedLanguage]): + A list of detected languages together with + confidence. + detected_break (~.text_annotation.TextAnnotation.DetectedBreak): + Detected start or end of a text segment. + """ + + detected_languages = proto.RepeatedField( + proto.MESSAGE, number=1, message="TextAnnotation.DetectedLanguage", + ) + + detected_break = proto.Field( + proto.MESSAGE, number=2, message="TextAnnotation.DetectedBreak", + ) + + pages = proto.RepeatedField(proto.MESSAGE, number=1, message="Page",) + + text = proto.Field(proto.STRING, number=2) + + +class Page(proto.Message): + r"""Detected page from OCR. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected on the page. + width (int): + Page width. For PDFs the unit is points. For + images (including TIFFs) the unit is pixels. + height (int): + Page height. For PDFs the unit is points. For + images (including TIFFs) the unit is pixels. + blocks (Sequence[~.text_annotation.Block]): + List of blocks of text, images etc on this + page. + confidence (float): + Confidence of the OCR results on the page. Range [0, 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + width = proto.Field(proto.INT32, number=2) + + height = proto.Field(proto.INT32, number=3) + + blocks = proto.RepeatedField(proto.MESSAGE, number=4, message="Block",) + + confidence = proto.Field(proto.FLOAT, number=5) + + +class Block(proto.Message): + r"""Logical element on the page. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the + block. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the block. The vertices are in the + order of top-left, top-right, bottom-right, bottom-left. + When a rotation of the bounding box is detected the rotation + is represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: + + :: + + 0----1 + | | + 3----2 + + - when it's rotated 180 degrees around the top-left corner + it becomes: + + :: + + 2----3 + | | + 1----0 + + and the vertice order will still be (0, 1, 2, 3). + paragraphs (Sequence[~.text_annotation.Paragraph]): + List of paragraphs in this block (if this + blocks is of type text). + block_type (~.text_annotation.Block.BlockType): + Detected block type (text, image etc) for + this block. + confidence (float): + Confidence of the OCR results on the block. Range [0, 1]. + """ + + class BlockType(proto.Enum): + r"""Type of a block (text, image etc) as identified by OCR.""" + UNKNOWN = 0 + TEXT = 1 + TABLE = 2 + PICTURE = 3 + RULER = 4 + BARCODE = 5 + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + paragraphs = proto.RepeatedField(proto.MESSAGE, number=3, message="Paragraph",) + + block_type = proto.Field(proto.ENUM, number=4, enum=BlockType,) + + confidence = proto.Field(proto.FLOAT, number=5) + + +class Paragraph(proto.Message): + r"""Structural unit of text representing a number of words in + certain order. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the + paragraph. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the paragraph. The vertices are in the + order of top-left, top-right, bottom-right, bottom-left. + When a rotation of the bounding box is detected the rotation + is represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). + words (Sequence[~.text_annotation.Word]): + List of words in this paragraph. + confidence (float): + Confidence of the OCR results for the paragraph. Range [0, + 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + words = proto.RepeatedField(proto.MESSAGE, number=3, message="Word",) + + confidence = proto.Field(proto.FLOAT, number=4) + + +class Word(proto.Message): + r"""A word representation. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the word. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the word. The vertices are in the order + of top-left, top-right, bottom-right, bottom-left. When a + rotation of the bounding box is detected the rotation is + represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). + symbols (Sequence[~.text_annotation.Symbol]): + List of symbols in the word. + The order of the symbols follows the natural + reading order. + confidence (float): + Confidence of the OCR results for the word. Range [0, 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + symbols = proto.RepeatedField(proto.MESSAGE, number=3, message="Symbol",) + + confidence = proto.Field(proto.FLOAT, number=4) + + +class Symbol(proto.Message): + r"""A single symbol representation. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the + symbol. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the symbol. The vertices are in the + order of top-left, top-right, bottom-right, bottom-left. + When a rotation of the bounding box is detected the rotation + is represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). + text (str): + The actual UTF-8 representation of the + symbol. + confidence (float): + Confidence of the OCR results for the symbol. Range [0, 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + text = proto.Field(proto.STRING, number=3) + + confidence = proto.Field(proto.FLOAT, number=4) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p2beta1/types/web_detection.py b/google/cloud/vision_v1p2beta1/types/web_detection.py new file mode 100644 index 00000000..1a4f954d --- /dev/null +++ b/google/cloud/vision_v1p2beta1/types/web_detection.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p2beta1", manifest={"WebDetection",}, +) + + +class WebDetection(proto.Message): + r"""Relevant information for the image from the Internet. + + Attributes: + web_entities (Sequence[~.web_detection.WebDetection.WebEntity]): + Deduced entities from similar images on the + Internet. + full_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Fully matching images from the Internet. + Can include resized copies of the query image. + partial_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Partial matching images from the Internet. + Those images are similar enough to share some + key-point features. For example an original + image will likely have partial matching for its + crops. + pages_with_matching_images (Sequence[~.web_detection.WebDetection.WebPage]): + Web pages containing the matching images from + the Internet. + visually_similar_images (Sequence[~.web_detection.WebDetection.WebImage]): + The visually similar image results. + best_guess_labels (Sequence[~.web_detection.WebDetection.WebLabel]): + Best guess text labels for the request image. + """ + + class WebEntity(proto.Message): + r"""Entity deduced from similar images on the Internet. + + Attributes: + entity_id (str): + Opaque entity ID. + score (float): + Overall relevancy score for the entity. + Not normalized and not comparable across + different image queries. + description (str): + Canonical description of the entity, in + English. + """ + + entity_id = proto.Field(proto.STRING, number=1) + + score = proto.Field(proto.FLOAT, number=2) + + description = proto.Field(proto.STRING, number=3) + + class WebImage(proto.Message): + r"""Metadata for online images. + + Attributes: + url (str): + The result image URL. + score (float): + (Deprecated) Overall relevancy score for the + image. + """ + + url = proto.Field(proto.STRING, number=1) + + score = proto.Field(proto.FLOAT, number=2) + + class WebPage(proto.Message): + r"""Metadata for web pages. + + Attributes: + url (str): + The result web page URL. + score (float): + (Deprecated) Overall relevancy score for the + web page. + page_title (str): + Title for the web page, may contain HTML + markups. + full_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Fully matching images on the page. + Can include resized copies of the query image. + partial_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Partial matching images on the page. + Those images are similar enough to share some + key-point features. For example an original + image will likely have partial matching for its + crops. + """ + + url = proto.Field(proto.STRING, number=1) + + score = proto.Field(proto.FLOAT, number=2) + + page_title = proto.Field(proto.STRING, number=3) + + full_matching_images = proto.RepeatedField( + proto.MESSAGE, number=4, message="WebDetection.WebImage", + ) + + partial_matching_images = proto.RepeatedField( + proto.MESSAGE, number=5, message="WebDetection.WebImage", + ) + + class WebLabel(proto.Message): + r"""Label to provide extra metadata for the web detection. + + Attributes: + label (str): + Label for extra metadata. + language_code (str): + The BCP-47 language code for ``label``, such as "en-US" or + "sr-Latn". For more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + """ + + label = proto.Field(proto.STRING, number=1) + + language_code = proto.Field(proto.STRING, number=2) + + web_entities = proto.RepeatedField(proto.MESSAGE, number=1, message=WebEntity,) + + full_matching_images = proto.RepeatedField( + proto.MESSAGE, number=2, message=WebImage, + ) + + partial_matching_images = proto.RepeatedField( + proto.MESSAGE, number=3, message=WebImage, + ) + + pages_with_matching_images = proto.RepeatedField( + proto.MESSAGE, number=4, message=WebPage, + ) + + visually_similar_images = proto.RepeatedField( + proto.MESSAGE, number=6, message=WebImage, + ) + + best_guess_labels = proto.RepeatedField(proto.MESSAGE, number=8, message=WebLabel,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p3beta1/__init__.py b/google/cloud/vision_v1p3beta1/__init__.py index 800aaf9a..c7ed337d 100644 --- a/google/cloud/vision_v1p3beta1/__init__.py +++ b/google/cloud/vision_v1p3beta1/__init__.py @@ -1,56 +1,192 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - - -from __future__ import absolute_import +# from google.cloud.vision_helpers.decorators import add_single_feature_methods from google.cloud.vision_helpers import VisionHelpers -import sys -import warnings - -from google.cloud.vision_v1p3beta1 import types -from google.cloud.vision_v1p3beta1.gapic import enums -from google.cloud.vision_v1p3beta1.gapic import image_annotator_client as iac -from google.cloud.vision_v1p3beta1.gapic import product_search_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - -class ProductSearchClient(product_search_client.ProductSearchClient): - __doc__ = product_search_client.ProductSearchClient.__doc__ - enums = enums +from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient +from .services.product_search import ProductSearchClient +from .types.geometry import BoundingPoly +from .types.geometry import NormalizedBoundingPoly +from .types.geometry import NormalizedVertex +from .types.geometry import Position +from .types.geometry import Vertex +from .types.image_annotator import AnnotateFileResponse +from .types.image_annotator import AnnotateImageRequest +from .types.image_annotator import AnnotateImageResponse +from .types.image_annotator import AsyncAnnotateFileRequest +from .types.image_annotator import AsyncAnnotateFileResponse +from .types.image_annotator import AsyncBatchAnnotateFilesRequest +from .types.image_annotator import AsyncBatchAnnotateFilesResponse +from .types.image_annotator import BatchAnnotateImagesRequest +from .types.image_annotator import BatchAnnotateImagesResponse +from .types.image_annotator import ColorInfo +from .types.image_annotator import CropHint +from .types.image_annotator import CropHintsAnnotation +from .types.image_annotator import CropHintsParams +from .types.image_annotator import DominantColorsAnnotation +from .types.image_annotator import EntityAnnotation +from .types.image_annotator import FaceAnnotation +from .types.image_annotator import Feature +from .types.image_annotator import GcsDestination +from .types.image_annotator import GcsSource +from .types.image_annotator import Image +from .types.image_annotator import ImageAnnotationContext +from .types.image_annotator import ImageContext +from .types.image_annotator import ImageProperties +from .types.image_annotator import ImageSource +from .types.image_annotator import InputConfig +from .types.image_annotator import LatLongRect +from .types.image_annotator import Likelihood +from .types.image_annotator import LocalizedObjectAnnotation +from .types.image_annotator import LocationInfo +from .types.image_annotator import OperationMetadata +from .types.image_annotator import OutputConfig +from .types.image_annotator import Property +from .types.image_annotator import SafeSearchAnnotation +from .types.image_annotator import WebDetectionParams +from .types.product_search import ProductSearchCategory +from .types.product_search import ProductSearchParams +from .types.product_search import ProductSearchResults +from .types.product_search import ProductSearchResultsView +from .types.product_search_service import AddProductToProductSetRequest +from .types.product_search_service import BatchOperationMetadata +from .types.product_search_service import CreateProductRequest +from .types.product_search_service import CreateProductSetRequest +from .types.product_search_service import CreateReferenceImageRequest +from .types.product_search_service import DeleteProductRequest +from .types.product_search_service import DeleteProductSetRequest +from .types.product_search_service import DeleteReferenceImageRequest +from .types.product_search_service import GetProductRequest +from .types.product_search_service import GetProductSetRequest +from .types.product_search_service import GetReferenceImageRequest +from .types.product_search_service import ImportProductSetsGcsSource +from .types.product_search_service import ImportProductSetsInputConfig +from .types.product_search_service import ImportProductSetsRequest +from .types.product_search_service import ImportProductSetsResponse +from .types.product_search_service import ListProductSetsRequest +from .types.product_search_service import ListProductSetsResponse +from .types.product_search_service import ListProductsInProductSetRequest +from .types.product_search_service import ListProductsInProductSetResponse +from .types.product_search_service import ListProductsRequest +from .types.product_search_service import ListProductsResponse +from .types.product_search_service import ListReferenceImagesRequest +from .types.product_search_service import ListReferenceImagesResponse +from .types.product_search_service import Product +from .types.product_search_service import ProductSet +from .types.product_search_service import ReferenceImage +from .types.product_search_service import RemoveProductFromProductSetRequest +from .types.product_search_service import UpdateProductRequest +from .types.product_search_service import UpdateProductSetRequest +from .types.text_annotation import Block +from .types.text_annotation import Page +from .types.text_annotation import Paragraph +from .types.text_annotation import Symbol +from .types.text_annotation import TextAnnotation +from .types.text_annotation import Word +from .types.web_detection import WebDetection @add_single_feature_methods -class ImageAnnotatorClient(VisionHelpers, iac.ImageAnnotatorClient): - __doc__ = iac.ImageAnnotatorClient.__doc__ - enums = enums +class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): + __doc__ = IacImageAnnotatorClient.__doc__ + Feature = Feature __all__ = ( - "enums", - "types", + "AddProductToProductSetRequest", + "AnnotateFileResponse", + "AnnotateImageRequest", + "AnnotateImageResponse", + "AsyncAnnotateFileRequest", + "AsyncAnnotateFileResponse", + "AsyncBatchAnnotateFilesRequest", + "AsyncBatchAnnotateFilesResponse", + "BatchAnnotateImagesRequest", + "BatchAnnotateImagesResponse", + "BatchOperationMetadata", + "Block", + "BoundingPoly", + "ColorInfo", + "CreateProductRequest", + "CreateProductSetRequest", + "CreateReferenceImageRequest", + "CropHint", + "CropHintsAnnotation", + "CropHintsParams", + "DeleteProductRequest", + "DeleteProductSetRequest", + "DeleteReferenceImageRequest", + "DominantColorsAnnotation", + "EntityAnnotation", + "FaceAnnotation", + "Feature", + "GcsDestination", + "GcsSource", + "GetProductRequest", + "GetProductSetRequest", + "GetReferenceImageRequest", + "Image", + "ImageAnnotationContext", + "ImageContext", + "ImageProperties", + "ImageSource", + "ImportProductSetsGcsSource", + "ImportProductSetsInputConfig", + "ImportProductSetsRequest", + "ImportProductSetsResponse", + "InputConfig", + "LatLongRect", + "Likelihood", + "ListProductSetsRequest", + "ListProductSetsResponse", + "ListProductsInProductSetRequest", + "ListProductsInProductSetResponse", + "ListProductsRequest", + "ListProductsResponse", + "ListReferenceImagesRequest", + "ListReferenceImagesResponse", + "LocalizedObjectAnnotation", + "LocationInfo", + "NormalizedBoundingPoly", + "NormalizedVertex", + "OperationMetadata", + "OutputConfig", + "Page", + "Paragraph", + "Position", + "Product", + "ProductSearchCategory", "ProductSearchClient", + "ProductSearchParams", + "ProductSearchResults", + "ProductSearchResultsView", + "ProductSet", + "Property", + "ReferenceImage", + "RemoveProductFromProductSetRequest", + "SafeSearchAnnotation", + "Symbol", + "TextAnnotation", + "UpdateProductRequest", + "UpdateProductSetRequest", + "Vertex", + "WebDetection", + "WebDetectionParams", + "Word", "ImageAnnotatorClient", ) diff --git a/google/cloud/vision_v1p3beta1/gapic/__init__.py b/google/cloud/vision_v1p3beta1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/vision_v1p3beta1/gapic/enums.py b/google/cloud/vision_v1p3beta1/gapic/enums.py deleted file mode 100644 index e62bb24b..00000000 --- a/google/cloud/vision_v1p3beta1/gapic/enums.py +++ /dev/null @@ -1,285 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class Likelihood(enum.IntEnum): - """ - A bucketized representation of likelihood, which is intended to give clients - highly stable results across model upgrades. - - Attributes: - UNKNOWN (int): Unknown likelihood. - VERY_UNLIKELY (int): It is very unlikely that the image belongs to the specified vertical. - UNLIKELY (int): It is unlikely that the image belongs to the specified vertical. - POSSIBLE (int): It is possible that the image belongs to the specified vertical. - LIKELY (int): It is likely that the image belongs to the specified vertical. - VERY_LIKELY (int): It is very likely that the image belongs to the specified vertical. - """ - - UNKNOWN = 0 - VERY_UNLIKELY = 1 - UNLIKELY = 2 - POSSIBLE = 3 - LIKELY = 4 - VERY_LIKELY = 5 - - -class ProductSearchCategory(enum.IntEnum): - """ - Supported product search categories. - - Attributes: - PRODUCT_SEARCH_CATEGORY_UNSPECIFIED (int): Default value used when a category is not specified. - SHOES (int): Shoes category. - BAGS (int): Bags category. - """ - - PRODUCT_SEARCH_CATEGORY_UNSPECIFIED = 0 - SHOES = 1 - BAGS = 2 - - -class ProductSearchResultsView(enum.IntEnum): - """ - Specifies the fields to include in product search results. - - Attributes: - BASIC (int): Product search results contain only ``product_category`` and - ``product_id``. Default value. - FULL (int): Product search results contain ``product_category``, ``product_id``, - ``image_uri``, and ``score``. - """ - - BASIC = 0 - FULL = 1 - - -class BatchOperationMetadata(object): - class State(enum.IntEnum): - """ - Enumerates the possible states that the batch request can be in. - - Attributes: - STATE_UNSPECIFIED (int): Invalid. - PROCESSING (int): Request is actively being processed. - SUCCESSFUL (int): The request is done and at least one item has been successfully - processed. - FAILED (int): The request is done and no item has been successfully processed. - CANCELLED (int): The request is done after the longrunning.Operations.CancelOperation has - been called by the user. Any records that were processed before the - cancel command are output as specified in the request. - """ - - STATE_UNSPECIFIED = 0 - PROCESSING = 1 - SUCCESSFUL = 2 - FAILED = 3 - CANCELLED = 4 - - -class Block(object): - class BlockType(enum.IntEnum): - """ - Type of a block (text, image etc) as identified by OCR. - - Attributes: - UNKNOWN (int): Unknown block type. - TEXT (int): Regular text block. - TABLE (int): Table block. - PICTURE (int): Image block. - RULER (int): Horizontal/vertical line box. - BARCODE (int): Barcode block. - """ - - UNKNOWN = 0 - TEXT = 1 - TABLE = 2 - PICTURE = 3 - RULER = 4 - BARCODE = 5 - - -class FaceAnnotation(object): - class Landmark(object): - class Type(enum.IntEnum): - """ - Face landmark (feature) type. Left and right are defined from the - vantage of the viewer of the image without considering mirror - projections typical of photos. So, ``LEFT_EYE``, typically, is the - person's right eye. - - Attributes: - UNKNOWN_LANDMARK (int): Unknown face landmark detected. Should not be filled. - LEFT_EYE (int): Left eye. - RIGHT_EYE (int): Right eye. - LEFT_OF_LEFT_EYEBROW (int): Left of left eyebrow. - RIGHT_OF_LEFT_EYEBROW (int): Right of left eyebrow. - LEFT_OF_RIGHT_EYEBROW (int): Left of right eyebrow. - RIGHT_OF_RIGHT_EYEBROW (int): Right of right eyebrow. - MIDPOINT_BETWEEN_EYES (int): Midpoint between eyes. - NOSE_TIP (int): Nose tip. - UPPER_LIP (int): Upper lip. - LOWER_LIP (int): Lower lip. - MOUTH_LEFT (int): Mouth left. - MOUTH_RIGHT (int): Mouth right. - MOUTH_CENTER (int): Mouth center. - NOSE_BOTTOM_RIGHT (int): Nose, bottom right. - NOSE_BOTTOM_LEFT (int): Nose, bottom left. - NOSE_BOTTOM_CENTER (int): Nose, bottom center. - LEFT_EYE_TOP_BOUNDARY (int): Left eye, top boundary. - LEFT_EYE_RIGHT_CORNER (int): Left eye, right corner. - LEFT_EYE_BOTTOM_BOUNDARY (int): Left eye, bottom boundary. - LEFT_EYE_LEFT_CORNER (int): Left eye, left corner. - RIGHT_EYE_TOP_BOUNDARY (int): Right eye, top boundary. - RIGHT_EYE_RIGHT_CORNER (int): Right eye, right corner. - RIGHT_EYE_BOTTOM_BOUNDARY (int): Right eye, bottom boundary. - RIGHT_EYE_LEFT_CORNER (int): Right eye, left corner. - LEFT_EYEBROW_UPPER_MIDPOINT (int): Left eyebrow, upper midpoint. - RIGHT_EYEBROW_UPPER_MIDPOINT (int): Right eyebrow, upper midpoint. - LEFT_EAR_TRAGION (int): Left ear tragion. - RIGHT_EAR_TRAGION (int): Right ear tragion. - LEFT_EYE_PUPIL (int): Left eye pupil. - RIGHT_EYE_PUPIL (int): Right eye pupil. - FOREHEAD_GLABELLA (int): Forehead glabella. - CHIN_GNATHION (int): Chin gnathion. - CHIN_LEFT_GONION (int): Chin left gonion. - CHIN_RIGHT_GONION (int): Chin right gonion. - """ - - UNKNOWN_LANDMARK = 0 - LEFT_EYE = 1 - RIGHT_EYE = 2 - LEFT_OF_LEFT_EYEBROW = 3 - RIGHT_OF_LEFT_EYEBROW = 4 - LEFT_OF_RIGHT_EYEBROW = 5 - RIGHT_OF_RIGHT_EYEBROW = 6 - MIDPOINT_BETWEEN_EYES = 7 - NOSE_TIP = 8 - UPPER_LIP = 9 - LOWER_LIP = 10 - MOUTH_LEFT = 11 - MOUTH_RIGHT = 12 - MOUTH_CENTER = 13 - NOSE_BOTTOM_RIGHT = 14 - NOSE_BOTTOM_LEFT = 15 - NOSE_BOTTOM_CENTER = 16 - LEFT_EYE_TOP_BOUNDARY = 17 - LEFT_EYE_RIGHT_CORNER = 18 - LEFT_EYE_BOTTOM_BOUNDARY = 19 - LEFT_EYE_LEFT_CORNER = 20 - RIGHT_EYE_TOP_BOUNDARY = 21 - RIGHT_EYE_RIGHT_CORNER = 22 - RIGHT_EYE_BOTTOM_BOUNDARY = 23 - RIGHT_EYE_LEFT_CORNER = 24 - LEFT_EYEBROW_UPPER_MIDPOINT = 25 - RIGHT_EYEBROW_UPPER_MIDPOINT = 26 - LEFT_EAR_TRAGION = 27 - RIGHT_EAR_TRAGION = 28 - LEFT_EYE_PUPIL = 29 - RIGHT_EYE_PUPIL = 30 - FOREHEAD_GLABELLA = 31 - CHIN_GNATHION = 32 - CHIN_LEFT_GONION = 33 - CHIN_RIGHT_GONION = 34 - - -class Feature(object): - class Type(enum.IntEnum): - """ - Type of Google Cloud Vision API feature to be extracted. - - Attributes: - TYPE_UNSPECIFIED (int): Unspecified feature type. - FACE_DETECTION (int): Run face detection. - LANDMARK_DETECTION (int): Run landmark detection. - LOGO_DETECTION (int): Run logo detection. - LABEL_DETECTION (int): Run label detection. - TEXT_DETECTION (int): Run text detection / optical character recognition (OCR). Text - detection is optimized for areas of text within a larger image; if the - image is a document, use ``DOCUMENT_TEXT_DETECTION`` instead. - DOCUMENT_TEXT_DETECTION (int): Run dense text document OCR. Takes precedence when both - ``DOCUMENT_TEXT_DETECTION`` and ``TEXT_DETECTION`` are present. - SAFE_SEARCH_DETECTION (int): Run Safe Search to detect potentially unsafe - or undesirable content. - IMAGE_PROPERTIES (int): Compute a set of image properties, such as the - image's dominant colors. - CROP_HINTS (int): Run crop hints. - WEB_DETECTION (int): Run web detection. - PRODUCT_SEARCH (int): Run Product Search. - OBJECT_LOCALIZATION (int): Run localizer for object detection. - """ - - TYPE_UNSPECIFIED = 0 - FACE_DETECTION = 1 - LANDMARK_DETECTION = 2 - LOGO_DETECTION = 3 - LABEL_DETECTION = 4 - TEXT_DETECTION = 5 - DOCUMENT_TEXT_DETECTION = 11 - SAFE_SEARCH_DETECTION = 6 - IMAGE_PROPERTIES = 7 - CROP_HINTS = 9 - WEB_DETECTION = 10 - PRODUCT_SEARCH = 12 - OBJECT_LOCALIZATION = 19 - - -class OperationMetadata(object): - class State(enum.IntEnum): - """ - Batch operation states. - - Attributes: - STATE_UNSPECIFIED (int): Invalid. - CREATED (int): Request is received. - RUNNING (int): Request is actively being processed. - DONE (int): The batch processing is done. - CANCELLED (int): The batch processing was cancelled. - """ - - STATE_UNSPECIFIED = 0 - CREATED = 1 - RUNNING = 2 - DONE = 3 - CANCELLED = 4 - - -class TextAnnotation(object): - class DetectedBreak(object): - class BreakType(enum.IntEnum): - """ - Enum to denote the type of break found. New line, space etc. - - Attributes: - UNKNOWN (int): Unknown break label type. - SPACE (int): Regular space. - SURE_SPACE (int): Sure space (very wide). - EOL_SURE_SPACE (int): Line-wrapping break. - HYPHEN (int): End-line hyphen that is not present in text; does not co-occur with - ``SPACE``, ``LEADER_SPACE``, or ``LINE_BREAK``. - LINE_BREAK (int): Line break that ends a paragraph. - """ - - UNKNOWN = 0 - SPACE = 1 - SURE_SPACE = 2 - EOL_SURE_SPACE = 3 - HYPHEN = 4 - LINE_BREAK = 5 diff --git a/google/cloud/vision_v1p3beta1/gapic/image_annotator_client.py b/google/cloud/vision_v1p3beta1/gapic/image_annotator_client.py deleted file mode 100644 index acaf6466..00000000 --- a/google/cloud/vision_v1p3beta1/gapic/image_annotator_client.py +++ /dev/null @@ -1,331 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.vision.v1p3beta1 ImageAnnotator API.""" - -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.grpc_helpers -import google.api_core.operation -from google.api_core import operations_v1 -import grpc - -from google.cloud.vision_v1p3beta1.gapic import enums -from google.cloud.vision_v1p3beta1.gapic import image_annotator_client_config -from google.cloud.vision_v1p3beta1.gapic.transports import ( - image_annotator_grpc_transport, -) -from google.cloud.vision_v1p3beta1.proto import image_annotator_pb2 -from google.cloud.vision_v1p3beta1.proto import image_annotator_pb2_grpc -from google.cloud.vision_v1p3beta1.proto import product_search_service_pb2 -from google.cloud.vision_v1p3beta1.proto import product_search_service_pb2_grpc -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-vision",).version - - -class ImageAnnotatorClient(object): - """ - Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - SERVICE_ADDRESS = "vision.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.vision.v1p3beta1.ImageAnnotator" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ImageAnnotatorClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.ImageAnnotatorGrpcTransport, - Callable[[~.Credentials, type], ~.ImageAnnotatorGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = image_annotator_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=image_annotator_grpc_transport.ImageAnnotatorGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = image_annotator_grpc_transport.ImageAnnotatorGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def batch_annotate_images( - self, - requests=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Run image detection and annotation for a batch of images. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ImageAnnotatorClient() - >>> - >>> response = client.batch_annotate_images() - - Args: - requests (list[Union[dict, ~google.cloud.vision_v1p3beta1.types.AnnotateImageRequest]]): Individual image annotation requests for this batch. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p3beta1.types.AnnotateImageRequest` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p3beta1.types.BatchAnnotateImagesResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "batch_annotate_images" not in self._inner_api_calls: - self._inner_api_calls[ - "batch_annotate_images" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.batch_annotate_images, - default_retry=self._method_configs["BatchAnnotateImages"].retry, - default_timeout=self._method_configs["BatchAnnotateImages"].timeout, - client_info=self._client_info, - ) - - request = image_annotator_pb2.BatchAnnotateImagesRequest(requests=requests,) - return self._inner_api_calls["batch_annotate_images"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def async_batch_annotate_files( - self, - requests, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Run asynchronous image detection and annotation for a list of - generic files, such as PDF files, which may contain multiple pages and - multiple images per page. Progress and results can be retrieved through - the ``google.longrunning.Operations`` interface. ``Operation.metadata`` - contains ``OperationMetadata`` (metadata). ``Operation.response`` - contains ``AsyncBatchAnnotateFilesResponse`` (results). - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ImageAnnotatorClient() - >>> - >>> # TODO: Initialize `requests`: - >>> requests = [] - >>> - >>> response = client.async_batch_annotate_files(requests) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - requests (list[Union[dict, ~google.cloud.vision_v1p3beta1.types.AsyncAnnotateFileRequest]]): Required. Individual async file annotation requests for this batch. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p3beta1.types.AsyncAnnotateFileRequest` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p3beta1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "async_batch_annotate_files" not in self._inner_api_calls: - self._inner_api_calls[ - "async_batch_annotate_files" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.async_batch_annotate_files, - default_retry=self._method_configs["AsyncBatchAnnotateFiles"].retry, - default_timeout=self._method_configs["AsyncBatchAnnotateFiles"].timeout, - client_info=self._client_info, - ) - - request = image_annotator_pb2.AsyncBatchAnnotateFilesRequest(requests=requests,) - operation = self._inner_api_calls["async_batch_annotate_files"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - image_annotator_pb2.AsyncBatchAnnotateFilesResponse, - metadata_type=image_annotator_pb2.OperationMetadata, - ) diff --git a/google/cloud/vision_v1p3beta1/gapic/image_annotator_client_config.py b/google/cloud/vision_v1p3beta1/gapic/image_annotator_client_config.py deleted file mode 100644 index 4032c73b..00000000 --- a/google/cloud/vision_v1p3beta1/gapic/image_annotator_client_config.py +++ /dev/null @@ -1,52 +0,0 @@ -config = { - "interfaces": { - "google.cloud.vision.v1p3beta1.ImageAnnotator": { - "retry_codes": { - "retry_policy_1_codes": [], - "retry_policy_4_codes": ["UNAVAILABLE", "DEADLINE_EXCEEDED"], - "no_retry_codes": [], - }, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 600000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 600000, - "total_timeout_millis": 600000, - }, - "retry_policy_4_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 600000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 600000, - "total_timeout_millis": 600000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - }, - "methods": { - "BatchAnnotateImages": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_4_codes", - "retry_params_name": "retry_policy_4_params", - }, - "AsyncBatchAnnotateFiles": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - }, - } - } -} diff --git a/google/cloud/vision_v1p3beta1/gapic/product_search_client.py b/google/cloud/vision_v1p3beta1/gapic/product_search_client.py deleted file mode 100644 index fdb89689..00000000 --- a/google/cloud/vision_v1p3beta1/gapic/product_search_client.py +++ /dev/null @@ -1,1908 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.vision.v1p3beta1 ProductSearch API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.operation -from google.api_core import operations_v1 -import google.api_core.page_iterator -import google.api_core.path_template -import grpc - -from google.cloud.vision_v1p3beta1.gapic import enums -from google.cloud.vision_v1p3beta1.gapic import product_search_client_config -from google.cloud.vision_v1p3beta1.gapic.transports import product_search_grpc_transport -from google.cloud.vision_v1p3beta1.proto import product_search_service_pb2 -from google.cloud.vision_v1p3beta1.proto import product_search_service_pb2_grpc -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-vision",).version - - -class ProductSearchClient(object): - """ - Manages Products and ProductSets of reference images for use in - product search. It uses the following resource model: - - - The API has a collection of ``ProductSet`` resources, named - ``projects/*/locations/*/productSets/*``, which acts as a way to put - different products into groups to limit identification. - - In parallel, - - - The API has a collection of ``Product`` resources, named - ``projects/*/locations/*/products/*`` - - - Each ``Product`` has a collection of ``ReferenceImage`` resources, - named ``projects/*/locations/*/products/*/referenceImages/*`` - """ - - SERVICE_ADDRESS = "vision.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.vision.v1p3beta1.ProductSearch" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProductSearchClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def location_path(cls, project, location): - """Return a fully-qualified location string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}", - project=project, - location=location, - ) - - @classmethod - def product_path(cls, project, location, product): - """Return a fully-qualified product string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/products/{product}", - project=project, - location=location, - product=product, - ) - - @classmethod - def product_set_path(cls, project, location, product_set): - """Return a fully-qualified product_set string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/productSets/{product_set}", - project=project, - location=location, - product_set=product_set, - ) - - @classmethod - def reference_image_path(cls, project, location, product, reference_image): - """Return a fully-qualified reference_image string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}", - project=project, - location=location, - product=product, - reference_image=reference_image, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.ProductSearchGrpcTransport, - Callable[[~.Credentials, type], ~.ProductSearchGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = product_search_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=product_search_grpc_transport.ProductSearchGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = product_search_grpc_transport.ProductSearchGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def import_product_sets( - self, - parent, - input_config, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Asynchronous API that imports a list of reference images to - specified product sets based on a list of image information. - - The ``google.longrunning.Operation`` API can be used to keep track of - the progress and results of the request. ``Operation.metadata`` contains - ``BatchOperationMetadata``. (progress) ``Operation.response`` contains - ``ImportProductSetsResponse``. (results) - - The input source of this method is a csv file on Google Cloud Storage. - For the format of the csv file please see - ``ImportProductSetsGcsSource.csv_file_uri``. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `input_config`: - >>> input_config = {} - >>> - >>> response = client.import_product_sets(parent, input_config) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - parent (str): Required. The project in which the ProductSets should be imported. - - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - input_config (Union[dict, ~google.cloud.vision_v1p3beta1.types.ImportProductSetsInputConfig]): Required. The input content for the list of requests. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p3beta1.types.ImportProductSetsInputConfig` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p3beta1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "import_product_sets" not in self._inner_api_calls: - self._inner_api_calls[ - "import_product_sets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.import_product_sets, - default_retry=self._method_configs["ImportProductSets"].retry, - default_timeout=self._method_configs["ImportProductSets"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.ImportProductSetsRequest( - parent=parent, input_config=input_config, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["import_product_sets"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - product_search_service_pb2.ImportProductSetsResponse, - metadata_type=product_search_service_pb2.BatchOperationMetadata, - ) - - def create_product_set( - self, - parent, - product_set, - product_set_id=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates and returns a new ProductSet resource. - - Possible errors: - - - Returns INVALID_ARGUMENT if display_name is missing, or is longer - than 4096 characters. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `product_set`: - >>> product_set = {} - >>> - >>> response = client.create_product_set(parent, product_set) - - Args: - parent (str): Required. The project in which the ProductSet should be created. - - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - product_set (Union[dict, ~google.cloud.vision_v1p3beta1.types.ProductSet]): Required. The ProductSet to create. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p3beta1.types.ProductSet` - product_set_id (str): A user-supplied resource id for this ProductSet. If set, the server - will attempt to use this value as the resource id. If it is already in - use, an error is returned with code ALREADY_EXISTS. Must be at most 128 - characters long. It cannot contain the character ``/``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p3beta1.types.ProductSet` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "create_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_product_set, - default_retry=self._method_configs["CreateProductSet"].retry, - default_timeout=self._method_configs["CreateProductSet"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.CreateProductSetRequest( - parent=parent, product_set=product_set, product_set_id=product_set_id, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_product_sets( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists ProductSets in an unspecified order. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100, or less - than 1. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_product_sets(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_product_sets(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The project from which ProductSets should be listed. - - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.vision_v1p3beta1.types.ProductSet` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_product_sets" not in self._inner_api_calls: - self._inner_api_calls[ - "list_product_sets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_product_sets, - default_retry=self._method_configs["ListProductSets"].retry, - default_timeout=self._method_configs["ListProductSets"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.ListProductSetsRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_product_sets"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="product_sets", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_product_set( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets information associated with a ProductSet. - - Possible errors: - - - Returns NOT_FOUND if the ProductSet does not exist. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> name = client.product_set_path('[PROJECT]', '[LOCATION]', '[PRODUCT_SET]') - >>> - >>> response = client.get_product_set(name) - - Args: - name (str): Required. Resource name of the ProductSet to get. - - Format is: - ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p3beta1.types.ProductSet` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "get_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_product_set, - default_retry=self._method_configs["GetProductSet"].retry, - default_timeout=self._method_configs["GetProductSet"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.GetProductSetRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_product_set( - self, - product_set, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Makes changes to a ProductSet resource. Only display_name can be - updated currently. - - Possible errors: - - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in update_mask - but missing from the request or longer than 4096 characters. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> # TODO: Initialize `product_set`: - >>> product_set = {} - >>> - >>> response = client.update_product_set(product_set) - - Args: - product_set (Union[dict, ~google.cloud.vision_v1p3beta1.types.ProductSet]): Required. The ProductSet resource which replaces the one on the server. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p3beta1.types.ProductSet` - update_mask (Union[dict, ~google.cloud.vision_v1p3beta1.types.FieldMask]): The ``FieldMask`` that specifies which fields to update. If - update_mask isn't specified, all mutable fields are to be updated. Valid - mask path is ``display_name``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p3beta1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p3beta1.types.ProductSet` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "update_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_product_set, - default_retry=self._method_configs["UpdateProductSet"].retry, - default_timeout=self._method_configs["UpdateProductSet"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.UpdateProductSetRequest( - product_set=product_set, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("product_set.name", product_set.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_product_set( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Permanently deletes a ProductSet. All Products and ReferenceImages - in the ProductSet will be deleted. - - The actual image files are not deleted from Google Cloud Storage. - - Possible errors: - - - Returns NOT_FOUND if the ProductSet does not exist. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> name = client.product_set_path('[PROJECT]', '[LOCATION]', '[PRODUCT_SET]') - >>> - >>> client.delete_product_set(name) - - Args: - name (str): Required. Resource name of the ProductSet to delete. - - Format is: - ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_product_set, - default_retry=self._method_configs["DeleteProductSet"].retry, - default_timeout=self._method_configs["DeleteProductSet"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.DeleteProductSetRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_product( - self, - parent, - product, - product_id=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates and returns a new product resource. - - Possible errors: - - - Returns INVALID_ARGUMENT if display_name is missing or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or invalid. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `product`: - >>> product = {} - >>> - >>> response = client.create_product(parent, product) - - Args: - parent (str): Required. The project in which the Product should be created. - - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - product (Union[dict, ~google.cloud.vision_v1p3beta1.types.Product]): Required. The product to create. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p3beta1.types.Product` - product_id (str): A user-supplied resource id for this Product. If set, the server - will attempt to use this value as the resource id. If it is already in - use, an error is returned with code ALREADY_EXISTS. Must be at most 128 - characters long. It cannot contain the character ``/``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p3beta1.types.Product` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_product" not in self._inner_api_calls: - self._inner_api_calls[ - "create_product" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_product, - default_retry=self._method_configs["CreateProduct"].retry, - default_timeout=self._method_configs["CreateProduct"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.CreateProductRequest( - parent=parent, product=product, product_id=product_id, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_product"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_products( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists products in an unspecified order. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100 or less - than 1. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_products(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_products(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The project OR ProductSet from which Products should be - listed. - - Format: ``projects/PROJECT_ID/locations/LOC_ID`` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.vision_v1p3beta1.types.Product` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_products" not in self._inner_api_calls: - self._inner_api_calls[ - "list_products" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_products, - default_retry=self._method_configs["ListProducts"].retry, - default_timeout=self._method_configs["ListProducts"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.ListProductsRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_products"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="products", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_product( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets information associated with a Product. - - Possible errors: - - - Returns NOT_FOUND if the Product does not exist. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> name = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> response = client.get_product(name) - - Args: - name (str): Required. Resource name of the Product to get. - - Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p3beta1.types.Product` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_product" not in self._inner_api_calls: - self._inner_api_calls[ - "get_product" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_product, - default_retry=self._method_configs["GetProduct"].retry, - default_timeout=self._method_configs["GetProduct"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.GetProductRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_product"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_product( - self, - product, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Makes changes to a Product resource. Only display_name, description - and labels can be updated right now. - - If labels are updated, the change will not be reflected in queries until - the next index time. - - Possible errors: - - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in update_mask - but is missing from the request or longer than 4096 characters. - - Returns INVALID_ARGUMENT if description is present in update_mask but - is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> # TODO: Initialize `product`: - >>> product = {} - >>> - >>> response = client.update_product(product) - - Args: - product (Union[dict, ~google.cloud.vision_v1p3beta1.types.Product]): Required. The Product resource which replaces the one on the server. - product.name is immutable. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p3beta1.types.Product` - update_mask (Union[dict, ~google.cloud.vision_v1p3beta1.types.FieldMask]): The ``FieldMask`` that specifies which fields to update. If - update_mask isn't specified, all mutable fields are to be updated. Valid - mask paths include ``product_labels``, ``display_name``, and - ``description``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p3beta1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p3beta1.types.Product` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_product" not in self._inner_api_calls: - self._inner_api_calls[ - "update_product" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_product, - default_retry=self._method_configs["UpdateProduct"].retry, - default_timeout=self._method_configs["UpdateProduct"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.UpdateProductRequest( - product=product, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("product.name", product.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_product"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_product( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Permanently deletes a product and its reference images. - - Metadata of the product and all its images will be deleted right away, - but search queries against ProductSets containing the product may still - work until all related caches are refreshed. - - Possible errors: - - - Returns NOT_FOUND if the product does not exist. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> name = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> client.delete_product(name) - - Args: - name (str): Required. Resource name of product to delete. - - Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_product" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_product" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_product, - default_retry=self._method_configs["DeleteProduct"].retry, - default_timeout=self._method_configs["DeleteProduct"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.DeleteProductRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_product"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_reference_image( - self, - parent, - reference_image, - reference_image_id=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates and returns a new ReferenceImage resource. - - The ``bounding_poly`` field is optional. If ``bounding_poly`` is not - specified, the system will try to detect regions of interest in the - image that are compatible with the product_category on the parent - product. If it is specified, detection is ALWAYS skipped. The system - converts polygons into non-rotated rectangles. - - Note that the pipeline will resize the image if the image resolution is - too large to process (above 50MP). - - Possible errors: - - - Returns INVALID_ARGUMENT if the image_uri is missing or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category is - detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than 10 - polygons. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> parent = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> # TODO: Initialize `reference_image`: - >>> reference_image = {} - >>> - >>> response = client.create_reference_image(parent, reference_image) - - Args: - parent (str): Required. Resource name of the product in which to create the - reference image. - - Format is ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. - reference_image (Union[dict, ~google.cloud.vision_v1p3beta1.types.ReferenceImage]): Required. The reference image to create. - If an image ID is specified, it is ignored. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p3beta1.types.ReferenceImage` - reference_image_id (str): A user-supplied resource id for the ReferenceImage to be added. If - set, the server will attempt to use this value as the resource id. If it - is already in use, an error is returned with code ALREADY_EXISTS. Must - be at most 128 characters long. It cannot contain the character ``/``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p3beta1.types.ReferenceImage` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_reference_image" not in self._inner_api_calls: - self._inner_api_calls[ - "create_reference_image" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_reference_image, - default_retry=self._method_configs["CreateReferenceImage"].retry, - default_timeout=self._method_configs["CreateReferenceImage"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.CreateReferenceImageRequest( - parent=parent, - reference_image=reference_image, - reference_image_id=reference_image_id, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_reference_image"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_reference_image( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Permanently deletes a reference image. - - The image metadata will be deleted right away, but search queries - against ProductSets containing the image may still work until all - related caches are refreshed. - - The actual image files are not deleted from Google Cloud Storage. - - Possible errors: - - - Returns NOT_FOUND if the reference image does not exist. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> name = client.reference_image_path('[PROJECT]', '[LOCATION]', '[PRODUCT]', '[REFERENCE_IMAGE]') - >>> - >>> client.delete_reference_image(name) - - Args: - name (str): Required. The resource name of the reference image to delete. - - Format is: - - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_reference_image" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_reference_image" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_reference_image, - default_retry=self._method_configs["DeleteReferenceImage"].retry, - default_timeout=self._method_configs["DeleteReferenceImage"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.DeleteReferenceImageRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_reference_image"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_reference_images( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists reference images. - - Possible errors: - - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, or - less than 1. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> parent = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> # Iterate over all results - >>> for element in client.list_reference_images(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_reference_images(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. Resource name of the product containing the reference - images. - - Format is ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.vision_v1p3beta1.types.ReferenceImage` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_reference_images" not in self._inner_api_calls: - self._inner_api_calls[ - "list_reference_images" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_reference_images, - default_retry=self._method_configs["ListReferenceImages"].retry, - default_timeout=self._method_configs["ListReferenceImages"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.ListReferenceImagesRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_reference_images"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="reference_images", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_reference_image( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets information associated with a ReferenceImage. - - Possible errors: - - - Returns NOT_FOUND if the specified image does not exist. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> name = client.reference_image_path('[PROJECT]', '[LOCATION]', '[PRODUCT]', '[REFERENCE_IMAGE]') - >>> - >>> response = client.get_reference_image(name) - - Args: - name (str): Required. The resource name of the ReferenceImage to get. - - Format is: - - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p3beta1.types.ReferenceImage` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_reference_image" not in self._inner_api_calls: - self._inner_api_calls[ - "get_reference_image" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_reference_image, - default_retry=self._method_configs["GetReferenceImage"].retry, - default_timeout=self._method_configs["GetReferenceImage"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.GetReferenceImageRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_reference_image"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def add_product_to_product_set( - self, - name, - product, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Adds a Product to the specified ProductSet. If the Product is - already present, no change is made. - - One Product can be added to at most 100 ProductSets. - - Possible errors: - - - Returns NOT_FOUND if the Product or the ProductSet doesn't exist. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> name = client.product_set_path('[PROJECT]', '[LOCATION]', '[PRODUCT_SET]') - >>> product = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> client.add_product_to_product_set(name, product) - - Args: - name (str): Required. The resource name for the ProductSet to modify. - - Format is: - ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` - product (str): Required. The resource name for the Product to be added to this - ProductSet. - - Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "add_product_to_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "add_product_to_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.add_product_to_product_set, - default_retry=self._method_configs["AddProductToProductSet"].retry, - default_timeout=self._method_configs["AddProductToProductSet"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.AddProductToProductSetRequest( - name=name, product=product, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["add_product_to_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def remove_product_from_product_set( - self, - name, - product, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Removes a Product from the specified ProductSet. - - Possible errors: - - - Returns NOT_FOUND If the Product is not found under the ProductSet. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> name = client.product_set_path('[PROJECT]', '[LOCATION]', '[PRODUCT_SET]') - >>> product = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> client.remove_product_from_product_set(name, product) - - Args: - name (str): Required. The resource name for the ProductSet to modify. - - Format is: - ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` - product (str): Required. The resource name for the Product to be removed from this - ProductSet. - - Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "remove_product_from_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "remove_product_from_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.remove_product_from_product_set, - default_retry=self._method_configs["RemoveProductFromProductSet"].retry, - default_timeout=self._method_configs[ - "RemoveProductFromProductSet" - ].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.RemoveProductFromProductSetRequest( - name=name, product=product, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["remove_product_from_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_products_in_product_set( - self, - name, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists the Products in a ProductSet, in an unspecified order. If the - ProductSet does not exist, the products field of the response will be - empty. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100 or less - than 1. - - Example: - >>> from google.cloud import vision_v1p3beta1 - >>> - >>> client = vision_v1p3beta1.ProductSearchClient() - >>> - >>> name = client.product_set_path('[PROJECT]', '[LOCATION]', '[PRODUCT_SET]') - >>> - >>> # Iterate over all results - >>> for element in client.list_products_in_product_set(name): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_products_in_product_set(name).pages: - ... for element in page: - ... # process element - ... pass - - Args: - name (str): Required. The ProductSet resource for which to retrieve Products. - - Format is: - ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.vision_v1p3beta1.types.Product` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_products_in_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "list_products_in_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_products_in_product_set, - default_retry=self._method_configs["ListProductsInProductSet"].retry, - default_timeout=self._method_configs[ - "ListProductsInProductSet" - ].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.ListProductsInProductSetRequest( - name=name, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_products_in_product_set"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="products", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator diff --git a/google/cloud/vision_v1p3beta1/gapic/product_search_client_config.py b/google/cloud/vision_v1p3beta1/gapic/product_search_client_config.py deleted file mode 100644 index 6a2241a5..00000000 --- a/google/cloud/vision_v1p3beta1/gapic/product_search_client_config.py +++ /dev/null @@ -1,132 +0,0 @@ -config = { - "interfaces": { - "google.cloud.vision.v1p3beta1.ProductSearch": { - "retry_codes": { - "no_retry_codes": [], - "retry_policy_3_codes": ["UNAVAILABLE", "DEADLINE_EXCEEDED"], - "retry_policy_2_codes": [], - }, - "retry_params": { - "retry_policy_3_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 600000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 600000, - "total_timeout_millis": 600000, - }, - "retry_policy_2_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 600000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 600000, - "total_timeout_millis": 600000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - }, - "methods": { - "ImportProductSets": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "CreateProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListProductSets": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "GetProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "UpdateProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "DeleteProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "CreateProduct": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListProducts": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "GetProduct": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "UpdateProduct": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "DeleteProduct": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "CreateReferenceImage": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "DeleteReferenceImage": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "ListReferenceImages": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "GetReferenceImage": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "AddProductToProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "RemoveProductFromProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListProductsInProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - }, - } - } -} diff --git a/google/cloud/vision_v1p3beta1/gapic/transports/__init__.py b/google/cloud/vision_v1p3beta1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/vision_v1p3beta1/gapic/transports/image_annotator_grpc_transport.py b/google/cloud/vision_v1p3beta1/gapic/transports/image_annotator_grpc_transport.py deleted file mode 100644 index 56addd09..00000000 --- a/google/cloud/vision_v1p3beta1/gapic/transports/image_annotator_grpc_transport.py +++ /dev/null @@ -1,152 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers -from google.api_core import operations_v1 - -from google.cloud.vision_v1p3beta1.proto import image_annotator_pb2_grpc - - -class ImageAnnotatorGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.vision.v1p3beta1 ImageAnnotator API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ) - - def __init__( - self, channel=None, credentials=None, address="vision.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "image_annotator_stub": image_annotator_pb2_grpc.ImageAnnotatorStub( - channel - ), - } - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="vision.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def batch_annotate_images(self): - """Return the gRPC stub for :meth:`ImageAnnotatorClient.batch_annotate_images`. - - Run image detection and annotation for a batch of images. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["image_annotator_stub"].BatchAnnotateImages - - @property - def async_batch_annotate_files(self): - """Return the gRPC stub for :meth:`ImageAnnotatorClient.async_batch_annotate_files`. - - Run asynchronous image detection and annotation for a list of - generic files, such as PDF files, which may contain multiple pages and - multiple images per page. Progress and results can be retrieved through - the ``google.longrunning.Operations`` interface. ``Operation.metadata`` - contains ``OperationMetadata`` (metadata). ``Operation.response`` - contains ``AsyncBatchAnnotateFilesResponse`` (results). - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["image_annotator_stub"].AsyncBatchAnnotateFiles diff --git a/google/cloud/vision_v1p3beta1/gapic/transports/product_search_grpc_transport.py b/google/cloud/vision_v1p3beta1/gapic/transports/product_search_grpc_transport.py deleted file mode 100644 index d3ddbc3d..00000000 --- a/google/cloud/vision_v1p3beta1/gapic/transports/product_search_grpc_transport.py +++ /dev/null @@ -1,490 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers -from google.api_core import operations_v1 - -from google.cloud.vision_v1p3beta1.proto import product_search_service_pb2_grpc - - -class ProductSearchGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.vision.v1p3beta1 ProductSearch API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ) - - def __init__( - self, channel=None, credentials=None, address="vision.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "product_search_stub": product_search_service_pb2_grpc.ProductSearchStub( - channel - ), - } - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="vision.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def import_product_sets(self): - """Return the gRPC stub for :meth:`ProductSearchClient.import_product_sets`. - - Asynchronous API that imports a list of reference images to - specified product sets based on a list of image information. - - The ``google.longrunning.Operation`` API can be used to keep track of - the progress and results of the request. ``Operation.metadata`` contains - ``BatchOperationMetadata``. (progress) ``Operation.response`` contains - ``ImportProductSetsResponse``. (results) - - The input source of this method is a csv file on Google Cloud Storage. - For the format of the csv file please see - ``ImportProductSetsGcsSource.csv_file_uri``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].ImportProductSets - - @property - def create_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.create_product_set`. - - Creates and returns a new ProductSet resource. - - Possible errors: - - - Returns INVALID_ARGUMENT if display_name is missing, or is longer - than 4096 characters. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].CreateProductSet - - @property - def list_product_sets(self): - """Return the gRPC stub for :meth:`ProductSearchClient.list_product_sets`. - - Lists ProductSets in an unspecified order. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100, or less - than 1. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].ListProductSets - - @property - def get_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.get_product_set`. - - Gets information associated with a ProductSet. - - Possible errors: - - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].GetProductSet - - @property - def update_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.update_product_set`. - - Makes changes to a ProductSet resource. Only display_name can be - updated currently. - - Possible errors: - - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in update_mask - but missing from the request or longer than 4096 characters. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].UpdateProductSet - - @property - def delete_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.delete_product_set`. - - Permanently deletes a ProductSet. All Products and ReferenceImages - in the ProductSet will be deleted. - - The actual image files are not deleted from Google Cloud Storage. - - Possible errors: - - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].DeleteProductSet - - @property - def create_product(self): - """Return the gRPC stub for :meth:`ProductSearchClient.create_product`. - - Creates and returns a new product resource. - - Possible errors: - - - Returns INVALID_ARGUMENT if display_name is missing or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or invalid. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].CreateProduct - - @property - def list_products(self): - """Return the gRPC stub for :meth:`ProductSearchClient.list_products`. - - Lists products in an unspecified order. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100 or less - than 1. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].ListProducts - - @property - def get_product(self): - """Return the gRPC stub for :meth:`ProductSearchClient.get_product`. - - Gets information associated with a Product. - - Possible errors: - - - Returns NOT_FOUND if the Product does not exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].GetProduct - - @property - def update_product(self): - """Return the gRPC stub for :meth:`ProductSearchClient.update_product`. - - Makes changes to a Product resource. Only display_name, description - and labels can be updated right now. - - If labels are updated, the change will not be reflected in queries until - the next index time. - - Possible errors: - - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in update_mask - but is missing from the request or longer than 4096 characters. - - Returns INVALID_ARGUMENT if description is present in update_mask but - is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].UpdateProduct - - @property - def delete_product(self): - """Return the gRPC stub for :meth:`ProductSearchClient.delete_product`. - - Permanently deletes a product and its reference images. - - Metadata of the product and all its images will be deleted right away, - but search queries against ProductSets containing the product may still - work until all related caches are refreshed. - - Possible errors: - - - Returns NOT_FOUND if the product does not exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].DeleteProduct - - @property - def create_reference_image(self): - """Return the gRPC stub for :meth:`ProductSearchClient.create_reference_image`. - - Creates and returns a new ReferenceImage resource. - - The ``bounding_poly`` field is optional. If ``bounding_poly`` is not - specified, the system will try to detect regions of interest in the - image that are compatible with the product_category on the parent - product. If it is specified, detection is ALWAYS skipped. The system - converts polygons into non-rotated rectangles. - - Note that the pipeline will resize the image if the image resolution is - too large to process (above 50MP). - - Possible errors: - - - Returns INVALID_ARGUMENT if the image_uri is missing or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category is - detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than 10 - polygons. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].CreateReferenceImage - - @property - def delete_reference_image(self): - """Return the gRPC stub for :meth:`ProductSearchClient.delete_reference_image`. - - Permanently deletes a reference image. - - The image metadata will be deleted right away, but search queries - against ProductSets containing the image may still work until all - related caches are refreshed. - - The actual image files are not deleted from Google Cloud Storage. - - Possible errors: - - - Returns NOT_FOUND if the reference image does not exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].DeleteReferenceImage - - @property - def list_reference_images(self): - """Return the gRPC stub for :meth:`ProductSearchClient.list_reference_images`. - - Lists reference images. - - Possible errors: - - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, or - less than 1. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].ListReferenceImages - - @property - def get_reference_image(self): - """Return the gRPC stub for :meth:`ProductSearchClient.get_reference_image`. - - Gets information associated with a ReferenceImage. - - Possible errors: - - - Returns NOT_FOUND if the specified image does not exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].GetReferenceImage - - @property - def add_product_to_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.add_product_to_product_set`. - - Adds a Product to the specified ProductSet. If the Product is - already present, no change is made. - - One Product can be added to at most 100 ProductSets. - - Possible errors: - - - Returns NOT_FOUND if the Product or the ProductSet doesn't exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].AddProductToProductSet - - @property - def remove_product_from_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.remove_product_from_product_set`. - - Removes a Product from the specified ProductSet. - - Possible errors: - - - Returns NOT_FOUND If the Product is not found under the ProductSet. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].RemoveProductFromProductSet - - @property - def list_products_in_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.list_products_in_product_set`. - - Lists the Products in a ProductSet, in an unspecified order. If the - ProductSet does not exist, the products field of the response will be - empty. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100 or less - than 1. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].ListProductsInProductSet diff --git a/google/cloud/vision_v1p3beta1/proto/__init__.py b/google/cloud/vision_v1p3beta1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/vision_v1p3beta1/proto/geometry_pb2.py b/google/cloud/vision_v1p3beta1/proto/geometry_pb2.py deleted file mode 100644 index cfd56f4d..00000000 --- a/google/cloud/vision_v1p3beta1/proto/geometry_pb2.py +++ /dev/null @@ -1,433 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p3beta1/proto/geometry.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p3beta1/proto/geometry.proto", - package="google.cloud.vision.v1p3beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p3beta1B\rGeometryProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p3beta1;vision\370\001\001", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n2google/cloud/vision_v1p3beta1/proto/geometry.proto\x12\x1dgoogle.cloud.vision.v1p3beta1\x1a\x1cgoogle/api/annotations.proto"\x1e\n\x06Vertex\x12\t\n\x01x\x18\x01 \x01(\x05\x12\t\n\x01y\x18\x02 \x01(\x05"(\n\x10NormalizedVertex\x12\t\n\x01x\x18\x01 \x01(\x02\x12\t\n\x01y\x18\x02 \x01(\x02"\x95\x01\n\x0c\x42oundingPoly\x12\x37\n\x08vertices\x18\x01 \x03(\x0b\x32%.google.cloud.vision.v1p3beta1.Vertex\x12L\n\x13normalized_vertices\x18\x02 \x03(\x0b\x32/.google.cloud.vision.v1p3beta1.NormalizedVertex"[\n\x16NormalizedBoundingPoly\x12\x41\n\x08vertices\x18\x01 \x03(\x0b\x32/.google.cloud.vision.v1p3beta1.NormalizedVertex"+\n\x08Position\x12\t\n\x01x\x18\x01 \x01(\x02\x12\t\n\x01y\x18\x02 \x01(\x02\x12\t\n\x01z\x18\x03 \x01(\x02\x42|\n!com.google.cloud.vision.v1p3beta1B\rGeometryProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p3beta1;vision\xf8\x01\x01\x62\x06proto3', - dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,], -) - - -_VERTEX = _descriptor.Descriptor( - name="Vertex", - full_name="google.cloud.vision.v1p3beta1.Vertex", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="x", - full_name="google.cloud.vision.v1p3beta1.Vertex.x", - index=0, - number=1, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="y", - full_name="google.cloud.vision.v1p3beta1.Vertex.y", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=115, - serialized_end=145, -) - - -_NORMALIZEDVERTEX = _descriptor.Descriptor( - name="NormalizedVertex", - full_name="google.cloud.vision.v1p3beta1.NormalizedVertex", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="x", - full_name="google.cloud.vision.v1p3beta1.NormalizedVertex.x", - index=0, - number=1, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="y", - full_name="google.cloud.vision.v1p3beta1.NormalizedVertex.y", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=147, - serialized_end=187, -) - - -_BOUNDINGPOLY = _descriptor.Descriptor( - name="BoundingPoly", - full_name="google.cloud.vision.v1p3beta1.BoundingPoly", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="vertices", - full_name="google.cloud.vision.v1p3beta1.BoundingPoly.vertices", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="normalized_vertices", - full_name="google.cloud.vision.v1p3beta1.BoundingPoly.normalized_vertices", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=190, - serialized_end=339, -) - - -_NORMALIZEDBOUNDINGPOLY = _descriptor.Descriptor( - name="NormalizedBoundingPoly", - full_name="google.cloud.vision.v1p3beta1.NormalizedBoundingPoly", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="vertices", - full_name="google.cloud.vision.v1p3beta1.NormalizedBoundingPoly.vertices", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=341, - serialized_end=432, -) - - -_POSITION = _descriptor.Descriptor( - name="Position", - full_name="google.cloud.vision.v1p3beta1.Position", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="x", - full_name="google.cloud.vision.v1p3beta1.Position.x", - index=0, - number=1, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="y", - full_name="google.cloud.vision.v1p3beta1.Position.y", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="z", - full_name="google.cloud.vision.v1p3beta1.Position.z", - index=2, - number=3, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=434, - serialized_end=477, -) - -_BOUNDINGPOLY.fields_by_name["vertices"].message_type = _VERTEX -_BOUNDINGPOLY.fields_by_name["normalized_vertices"].message_type = _NORMALIZEDVERTEX -_NORMALIZEDBOUNDINGPOLY.fields_by_name["vertices"].message_type = _NORMALIZEDVERTEX -DESCRIPTOR.message_types_by_name["Vertex"] = _VERTEX -DESCRIPTOR.message_types_by_name["NormalizedVertex"] = _NORMALIZEDVERTEX -DESCRIPTOR.message_types_by_name["BoundingPoly"] = _BOUNDINGPOLY -DESCRIPTOR.message_types_by_name["NormalizedBoundingPoly"] = _NORMALIZEDBOUNDINGPOLY -DESCRIPTOR.message_types_by_name["Position"] = _POSITION -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Vertex = _reflection.GeneratedProtocolMessageType( - "Vertex", - (_message.Message,), - { - "DESCRIPTOR": _VERTEX, - "__module__": "google.cloud.vision_v1p3beta1.proto.geometry_pb2", - "__doc__": """X coordinate. - - Attributes: - y: - Y coordinate. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.Vertex) - }, -) -_sym_db.RegisterMessage(Vertex) - -NormalizedVertex = _reflection.GeneratedProtocolMessageType( - "NormalizedVertex", - (_message.Message,), - { - "DESCRIPTOR": _NORMALIZEDVERTEX, - "__module__": "google.cloud.vision_v1p3beta1.proto.geometry_pb2", - "__doc__": """X coordinate. - - Attributes: - y: - Y coordinate. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.NormalizedVertex) - }, -) -_sym_db.RegisterMessage(NormalizedVertex) - -BoundingPoly = _reflection.GeneratedProtocolMessageType( - "BoundingPoly", - (_message.Message,), - { - "DESCRIPTOR": _BOUNDINGPOLY, - "__module__": "google.cloud.vision_v1p3beta1.proto.geometry_pb2", - "__doc__": """A bounding polygon for the detected image annotation. - - Attributes: - vertices: - The bounding polygon vertices. - normalized_vertices: - The bounding polygon normalized vertices. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.BoundingPoly) - }, -) -_sym_db.RegisterMessage(BoundingPoly) - -NormalizedBoundingPoly = _reflection.GeneratedProtocolMessageType( - "NormalizedBoundingPoly", - (_message.Message,), - { - "DESCRIPTOR": _NORMALIZEDBOUNDINGPOLY, - "__module__": "google.cloud.vision_v1p3beta1.proto.geometry_pb2", - "__doc__": """A normalized bounding polygon around a portion of an image. - - Attributes: - vertices: - Normalized vertices of the bounding polygon. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.NormalizedBoundingPoly) - }, -) -_sym_db.RegisterMessage(NormalizedBoundingPoly) - -Position = _reflection.GeneratedProtocolMessageType( - "Position", - (_message.Message,), - { - "DESCRIPTOR": _POSITION, - "__module__": "google.cloud.vision_v1p3beta1.proto.geometry_pb2", - "__doc__": """A 3D position in the image, used primarily for Face detection - landmarks. A valid Position must have both x and y coordinates. The - position coordinates are in the same scale as the original image. - - Attributes: - x: - X coordinate. - y: - Y coordinate. - z: - Z coordinate (or depth). - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.Position) - }, -) -_sym_db.RegisterMessage(Position) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p3beta1/proto/geometry_pb2_grpc.py b/google/cloud/vision_v1p3beta1/proto/geometry_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/vision_v1p3beta1/proto/geometry_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/vision_v1p3beta1/proto/image_annotator_pb2.py b/google/cloud/vision_v1p3beta1/proto/image_annotator_pb2.py deleted file mode 100644 index f6793295..00000000 --- a/google/cloud/vision_v1p3beta1/proto/image_annotator_pb2.py +++ /dev/null @@ -1,4426 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p3beta1/proto/image_annotator.proto -"""Generated protocol buffer code.""" -from google.protobuf.internal import enum_type_wrapper -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.cloud.vision_v1p3beta1.proto import ( - geometry_pb2 as google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2, -) -from google.cloud.vision_v1p3beta1.proto import ( - product_search_pb2 as google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__pb2, -) -from google.cloud.vision_v1p3beta1.proto import ( - text_annotation_pb2 as google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_text__annotation__pb2, -) -from google.cloud.vision_v1p3beta1.proto import ( - web_detection_pb2 as google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_web__detection__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2 -from google.type import color_pb2 as google_dot_type_dot_color__pb2 -from google.type import latlng_pb2 as google_dot_type_dot_latlng__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p3beta1/proto/image_annotator.proto", - package="google.cloud.vision.v1p3beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p3beta1B\023ImageAnnotatorProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p3beta1;vision\370\001\001", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n9google/cloud/vision_v1p3beta1/proto/image_annotator.proto\x12\x1dgoogle.cloud.vision.v1p3beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x32google/cloud/vision_v1p3beta1/proto/geometry.proto\x1a\x38google/cloud/vision_v1p3beta1/proto/product_search.proto\x1a\x39google/cloud/vision_v1p3beta1/proto/text_annotation.proto\x1a\x37google/cloud/vision_v1p3beta1/proto/web_detection.proto\x1a#google/longrunning/operations.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x17google/rpc/status.proto\x1a\x17google/type/color.proto\x1a\x18google/type/latlng.proto"\x8e\x03\n\x07\x46\x65\x61ture\x12\x39\n\x04type\x18\x01 \x01(\x0e\x32+.google.cloud.vision.v1p3beta1.Feature.Type\x12\x13\n\x0bmax_results\x18\x02 \x01(\x05\x12\r\n\x05model\x18\x03 \x01(\t"\xa3\x02\n\x04Type\x12\x14\n\x10TYPE_UNSPECIFIED\x10\x00\x12\x12\n\x0e\x46\x41\x43\x45_DETECTION\x10\x01\x12\x16\n\x12LANDMARK_DETECTION\x10\x02\x12\x12\n\x0eLOGO_DETECTION\x10\x03\x12\x13\n\x0fLABEL_DETECTION\x10\x04\x12\x12\n\x0eTEXT_DETECTION\x10\x05\x12\x1b\n\x17\x44OCUMENT_TEXT_DETECTION\x10\x0b\x12\x19\n\x15SAFE_SEARCH_DETECTION\x10\x06\x12\x14\n\x10IMAGE_PROPERTIES\x10\x07\x12\x0e\n\nCROP_HINTS\x10\t\x12\x11\n\rWEB_DETECTION\x10\n\x12\x12\n\x0ePRODUCT_SEARCH\x10\x0c\x12\x17\n\x13OBJECT_LOCALIZATION\x10\x13"7\n\x0bImageSource\x12\x15\n\rgcs_image_uri\x18\x01 \x01(\t\x12\x11\n\timage_uri\x18\x02 \x01(\t"T\n\x05Image\x12\x0f\n\x07\x63ontent\x18\x01 \x01(\x0c\x12:\n\x06source\x18\x02 \x01(\x0b\x32*.google.cloud.vision.v1p3beta1.ImageSource"\x9b\x0e\n\x0e\x46\x61\x63\x65\x41nnotation\x12\x42\n\rbounding_poly\x18\x01 \x01(\x0b\x32+.google.cloud.vision.v1p3beta1.BoundingPoly\x12\x45\n\x10\x66\x64_bounding_poly\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p3beta1.BoundingPoly\x12I\n\tlandmarks\x18\x03 \x03(\x0b\x32\x36.google.cloud.vision.v1p3beta1.FaceAnnotation.Landmark\x12\x12\n\nroll_angle\x18\x04 \x01(\x02\x12\x11\n\tpan_angle\x18\x05 \x01(\x02\x12\x12\n\ntilt_angle\x18\x06 \x01(\x02\x12\x1c\n\x14\x64\x65tection_confidence\x18\x07 \x01(\x02\x12\x1e\n\x16landmarking_confidence\x18\x08 \x01(\x02\x12\x41\n\x0ejoy_likelihood\x18\t \x01(\x0e\x32).google.cloud.vision.v1p3beta1.Likelihood\x12\x44\n\x11sorrow_likelihood\x18\n \x01(\x0e\x32).google.cloud.vision.v1p3beta1.Likelihood\x12\x43\n\x10\x61nger_likelihood\x18\x0b \x01(\x0e\x32).google.cloud.vision.v1p3beta1.Likelihood\x12\x46\n\x13surprise_likelihood\x18\x0c \x01(\x0e\x32).google.cloud.vision.v1p3beta1.Likelihood\x12K\n\x18under_exposed_likelihood\x18\r \x01(\x0e\x32).google.cloud.vision.v1p3beta1.Likelihood\x12\x45\n\x12\x62lurred_likelihood\x18\x0e \x01(\x0e\x32).google.cloud.vision.v1p3beta1.Likelihood\x12\x46\n\x13headwear_likelihood\x18\x0f \x01(\x0e\x32).google.cloud.vision.v1p3beta1.Likelihood\x1a\xc7\x07\n\x08Landmark\x12I\n\x04type\x18\x03 \x01(\x0e\x32;.google.cloud.vision.v1p3beta1.FaceAnnotation.Landmark.Type\x12\x39\n\x08position\x18\x04 \x01(\x0b\x32\'.google.cloud.vision.v1p3beta1.Position"\xb4\x06\n\x04Type\x12\x14\n\x10UNKNOWN_LANDMARK\x10\x00\x12\x0c\n\x08LEFT_EYE\x10\x01\x12\r\n\tRIGHT_EYE\x10\x02\x12\x18\n\x14LEFT_OF_LEFT_EYEBROW\x10\x03\x12\x19\n\x15RIGHT_OF_LEFT_EYEBROW\x10\x04\x12\x19\n\x15LEFT_OF_RIGHT_EYEBROW\x10\x05\x12\x1a\n\x16RIGHT_OF_RIGHT_EYEBROW\x10\x06\x12\x19\n\x15MIDPOINT_BETWEEN_EYES\x10\x07\x12\x0c\n\x08NOSE_TIP\x10\x08\x12\r\n\tUPPER_LIP\x10\t\x12\r\n\tLOWER_LIP\x10\n\x12\x0e\n\nMOUTH_LEFT\x10\x0b\x12\x0f\n\x0bMOUTH_RIGHT\x10\x0c\x12\x10\n\x0cMOUTH_CENTER\x10\r\x12\x15\n\x11NOSE_BOTTOM_RIGHT\x10\x0e\x12\x14\n\x10NOSE_BOTTOM_LEFT\x10\x0f\x12\x16\n\x12NOSE_BOTTOM_CENTER\x10\x10\x12\x19\n\x15LEFT_EYE_TOP_BOUNDARY\x10\x11\x12\x19\n\x15LEFT_EYE_RIGHT_CORNER\x10\x12\x12\x1c\n\x18LEFT_EYE_BOTTOM_BOUNDARY\x10\x13\x12\x18\n\x14LEFT_EYE_LEFT_CORNER\x10\x14\x12\x1a\n\x16RIGHT_EYE_TOP_BOUNDARY\x10\x15\x12\x1a\n\x16RIGHT_EYE_RIGHT_CORNER\x10\x16\x12\x1d\n\x19RIGHT_EYE_BOTTOM_BOUNDARY\x10\x17\x12\x19\n\x15RIGHT_EYE_LEFT_CORNER\x10\x18\x12\x1f\n\x1bLEFT_EYEBROW_UPPER_MIDPOINT\x10\x19\x12 \n\x1cRIGHT_EYEBROW_UPPER_MIDPOINT\x10\x1a\x12\x14\n\x10LEFT_EAR_TRAGION\x10\x1b\x12\x15\n\x11RIGHT_EAR_TRAGION\x10\x1c\x12\x12\n\x0eLEFT_EYE_PUPIL\x10\x1d\x12\x13\n\x0fRIGHT_EYE_PUPIL\x10\x1e\x12\x15\n\x11\x46OREHEAD_GLABELLA\x10\x1f\x12\x11\n\rCHIN_GNATHION\x10 \x12\x14\n\x10\x43HIN_LEFT_GONION\x10!\x12\x15\n\x11\x43HIN_RIGHT_GONION\x10""4\n\x0cLocationInfo\x12$\n\x07lat_lng\x18\x01 \x01(\x0b\x32\x13.google.type.LatLng"=\n\x08Property\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t\x12\x14\n\x0cuint64_value\x18\x03 \x01(\x04"\xbc\x02\n\x10\x45ntityAnnotation\x12\x0b\n\x03mid\x18\x01 \x01(\t\x12\x0e\n\x06locale\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\x12\r\n\x05score\x18\x04 \x01(\x02\x12\x12\n\nconfidence\x18\x05 \x01(\x02\x12\x12\n\ntopicality\x18\x06 \x01(\x02\x12\x42\n\rbounding_poly\x18\x07 \x01(\x0b\x32+.google.cloud.vision.v1p3beta1.BoundingPoly\x12>\n\tlocations\x18\x08 \x03(\x0b\x32+.google.cloud.vision.v1p3beta1.LocationInfo\x12;\n\nproperties\x18\t \x03(\x0b\x32\'.google.cloud.vision.v1p3beta1.Property"\xa0\x01\n\x19LocalizedObjectAnnotation\x12\x0b\n\x03mid\x18\x01 \x01(\t\x12\x15\n\rlanguage_code\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\r\n\x05score\x18\x04 \x01(\x02\x12\x42\n\rbounding_poly\x18\x05 \x01(\x0b\x32+.google.cloud.vision.v1p3beta1.BoundingPoly"\xbc\x02\n\x14SafeSearchAnnotation\x12\x38\n\x05\x61\x64ult\x18\x01 \x01(\x0e\x32).google.cloud.vision.v1p3beta1.Likelihood\x12\x38\n\x05spoof\x18\x02 \x01(\x0e\x32).google.cloud.vision.v1p3beta1.Likelihood\x12:\n\x07medical\x18\x03 \x01(\x0e\x32).google.cloud.vision.v1p3beta1.Likelihood\x12;\n\x08violence\x18\x04 \x01(\x0e\x32).google.cloud.vision.v1p3beta1.Likelihood\x12\x37\n\x04racy\x18\t \x01(\x0e\x32).google.cloud.vision.v1p3beta1.Likelihood"a\n\x0bLatLongRect\x12(\n\x0bmin_lat_lng\x18\x01 \x01(\x0b\x32\x13.google.type.LatLng\x12(\n\x0bmax_lat_lng\x18\x02 \x01(\x0b\x32\x13.google.type.LatLng"U\n\tColorInfo\x12!\n\x05\x63olor\x18\x01 \x01(\x0b\x32\x12.google.type.Color\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x16\n\x0epixel_fraction\x18\x03 \x01(\x02"T\n\x18\x44ominantColorsAnnotation\x12\x38\n\x06\x63olors\x18\x01 \x03(\x0b\x32(.google.cloud.vision.v1p3beta1.ColorInfo"c\n\x0fImageProperties\x12P\n\x0f\x64ominant_colors\x18\x01 \x01(\x0b\x32\x37.google.cloud.vision.v1p3beta1.DominantColorsAnnotation"\x7f\n\x08\x43ropHint\x12\x42\n\rbounding_poly\x18\x01 \x01(\x0b\x32+.google.cloud.vision.v1p3beta1.BoundingPoly\x12\x12\n\nconfidence\x18\x02 \x01(\x02\x12\x1b\n\x13importance_fraction\x18\x03 \x01(\x02"R\n\x13\x43ropHintsAnnotation\x12;\n\ncrop_hints\x18\x01 \x03(\x0b\x32\'.google.cloud.vision.v1p3beta1.CropHint"(\n\x0f\x43ropHintsParams\x12\x15\n\raspect_ratios\x18\x01 \x03(\x02"1\n\x12WebDetectionParams\x12\x1b\n\x13include_geo_results\x18\x02 \x01(\x08"\xd8\x02\n\x0cImageContext\x12\x41\n\rlat_long_rect\x18\x01 \x01(\x0b\x32*.google.cloud.vision.v1p3beta1.LatLongRect\x12\x16\n\x0elanguage_hints\x18\x02 \x03(\t\x12I\n\x11\x63rop_hints_params\x18\x04 \x01(\x0b\x32..google.cloud.vision.v1p3beta1.CropHintsParams\x12Q\n\x15product_search_params\x18\x05 \x01(\x0b\x32\x32.google.cloud.vision.v1p3beta1.ProductSearchParams\x12O\n\x14web_detection_params\x18\x06 \x01(\x0b\x32\x31.google.cloud.vision.v1p3beta1.WebDetectionParams"\xc9\x01\n\x14\x41nnotateImageRequest\x12\x33\n\x05image\x18\x01 \x01(\x0b\x32$.google.cloud.vision.v1p3beta1.Image\x12\x38\n\x08\x66\x65\x61tures\x18\x02 \x03(\x0b\x32&.google.cloud.vision.v1p3beta1.Feature\x12\x42\n\rimage_context\x18\x03 \x01(\x0b\x32+.google.cloud.vision.v1p3beta1.ImageContext":\n\x16ImageAnnotationContext\x12\x0b\n\x03uri\x18\x01 \x01(\t\x12\x13\n\x0bpage_number\x18\x02 \x01(\x05"\xbf\x08\n\x15\x41nnotateImageResponse\x12G\n\x10\x66\x61\x63\x65_annotations\x18\x01 \x03(\x0b\x32-.google.cloud.vision.v1p3beta1.FaceAnnotation\x12M\n\x14landmark_annotations\x18\x02 \x03(\x0b\x32/.google.cloud.vision.v1p3beta1.EntityAnnotation\x12I\n\x10logo_annotations\x18\x03 \x03(\x0b\x32/.google.cloud.vision.v1p3beta1.EntityAnnotation\x12J\n\x11label_annotations\x18\x04 \x03(\x0b\x32/.google.cloud.vision.v1p3beta1.EntityAnnotation\x12^\n\x1clocalized_object_annotations\x18\x16 \x03(\x0b\x32\x38.google.cloud.vision.v1p3beta1.LocalizedObjectAnnotation\x12I\n\x10text_annotations\x18\x05 \x03(\x0b\x32/.google.cloud.vision.v1p3beta1.EntityAnnotation\x12K\n\x14\x66ull_text_annotation\x18\x0c \x01(\x0b\x32-.google.cloud.vision.v1p3beta1.TextAnnotation\x12S\n\x16safe_search_annotation\x18\x06 \x01(\x0b\x32\x33.google.cloud.vision.v1p3beta1.SafeSearchAnnotation\x12S\n\x1bimage_properties_annotation\x18\x08 \x01(\x0b\x32..google.cloud.vision.v1p3beta1.ImageProperties\x12Q\n\x15\x63rop_hints_annotation\x18\x0b \x01(\x0b\x32\x32.google.cloud.vision.v1p3beta1.CropHintsAnnotation\x12\x42\n\rweb_detection\x18\r \x01(\x0b\x32+.google.cloud.vision.v1p3beta1.WebDetection\x12S\n\x16product_search_results\x18\x0e \x01(\x0b\x32\x33.google.cloud.vision.v1p3beta1.ProductSearchResults\x12!\n\x05\x65rror\x18\t \x01(\x0b\x32\x12.google.rpc.Status\x12\x46\n\x07\x63ontext\x18\x15 \x01(\x0b\x32\x35.google.cloud.vision.v1p3beta1.ImageAnnotationContext"\xa1\x01\n\x14\x41nnotateFileResponse\x12@\n\x0cinput_config\x18\x01 \x01(\x0b\x32*.google.cloud.vision.v1p3beta1.InputConfig\x12G\n\tresponses\x18\x02 \x03(\x0b\x32\x34.google.cloud.vision.v1p3beta1.AnnotateImageResponse"c\n\x1a\x42\x61tchAnnotateImagesRequest\x12\x45\n\x08requests\x18\x01 \x03(\x0b\x32\x33.google.cloud.vision.v1p3beta1.AnnotateImageRequest"f\n\x1b\x42\x61tchAnnotateImagesResponse\x12G\n\tresponses\x18\x01 \x03(\x0b\x32\x34.google.cloud.vision.v1p3beta1.AnnotateImageResponse"\x9e\x02\n\x18\x41syncAnnotateFileRequest\x12@\n\x0cinput_config\x18\x01 \x01(\x0b\x32*.google.cloud.vision.v1p3beta1.InputConfig\x12\x38\n\x08\x66\x65\x61tures\x18\x02 \x03(\x0b\x32&.google.cloud.vision.v1p3beta1.Feature\x12\x42\n\rimage_context\x18\x03 \x01(\x0b\x32+.google.cloud.vision.v1p3beta1.ImageContext\x12\x42\n\routput_config\x18\x04 \x01(\x0b\x32+.google.cloud.vision.v1p3beta1.OutputConfig"_\n\x19\x41syncAnnotateFileResponse\x12\x42\n\routput_config\x18\x01 \x01(\x0b\x32+.google.cloud.vision.v1p3beta1.OutputConfig"p\n\x1e\x41syncBatchAnnotateFilesRequest\x12N\n\x08requests\x18\x01 \x03(\x0b\x32\x37.google.cloud.vision.v1p3beta1.AsyncAnnotateFileRequestB\x03\xe0\x41\x02"n\n\x1f\x41syncBatchAnnotateFilesResponse\x12K\n\tresponses\x18\x01 \x03(\x0b\x32\x38.google.cloud.vision.v1p3beta1.AsyncAnnotateFileResponse"^\n\x0bInputConfig\x12<\n\ngcs_source\x18\x01 \x01(\x0b\x32(.google.cloud.vision.v1p3beta1.GcsSource\x12\x11\n\tmime_type\x18\x02 \x01(\t"j\n\x0cOutputConfig\x12\x46\n\x0fgcs_destination\x18\x01 \x01(\x0b\x32-.google.cloud.vision.v1p3beta1.GcsDestination\x12\x12\n\nbatch_size\x18\x02 \x01(\x05"\x18\n\tGcsSource\x12\x0b\n\x03uri\x18\x01 \x01(\t"\x1d\n\x0eGcsDestination\x12\x0b\n\x03uri\x18\x01 \x01(\t"\x8f\x02\n\x11OperationMetadata\x12\x45\n\x05state\x18\x01 \x01(\x0e\x32\x36.google.cloud.vision.v1p3beta1.OperationMetadata.State\x12/\n\x0b\x63reate_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"Q\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0b\n\x07\x43REATED\x10\x01\x12\x0b\n\x07RUNNING\x10\x02\x12\x08\n\x04\x44ONE\x10\x03\x12\r\n\tCANCELLED\x10\x04*e\n\nLikelihood\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x11\n\rVERY_UNLIKELY\x10\x01\x12\x0c\n\x08UNLIKELY\x10\x02\x12\x0c\n\x08POSSIBLE\x10\x03\x12\n\n\x06LIKELY\x10\x04\x12\x0f\n\x0bVERY_LIKELY\x10\x05\x32\xb5\x04\n\x0eImageAnnotator\x12\xbe\x01\n\x13\x42\x61tchAnnotateImages\x12\x39.google.cloud.vision.v1p3beta1.BatchAnnotateImagesRequest\x1a:.google.cloud.vision.v1p3beta1.BatchAnnotateImagesResponse"0\x82\xd3\xe4\x93\x02\x1f"\x1a/v1p3beta1/images:annotate:\x01*\xda\x41\x08requests\x12\xe9\x01\n\x17\x41syncBatchAnnotateFiles\x12=.google.cloud.vision.v1p3beta1.AsyncBatchAnnotateFilesRequest\x1a\x1d.google.longrunning.Operation"p\x82\xd3\xe4\x93\x02("#/v1p3beta1/files:asyncBatchAnnotate:\x01*\xda\x41\x08requests\xca\x41\x34\n\x1f\x41syncBatchAnnotateFilesResponse\x12\x11OperationMetadata\x1av\xca\x41\x15vision.googleapis.com\xd2\x41[https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-visionB\x82\x01\n!com.google.cloud.vision.v1p3beta1B\x13ImageAnnotatorProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p3beta1;vision\xf8\x01\x01\x62\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_text__annotation__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_web__detection__pb2.DESCRIPTOR, - google_dot_longrunning_dot_operations__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_rpc_dot_status__pb2.DESCRIPTOR, - google_dot_type_dot_color__pb2.DESCRIPTOR, - google_dot_type_dot_latlng__pb2.DESCRIPTOR, - ], -) - -_LIKELIHOOD = _descriptor.EnumDescriptor( - name="Likelihood", - full_name="google.cloud.vision.v1p3beta1.Likelihood", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNKNOWN", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="VERY_UNLIKELY", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="UNLIKELY", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="POSSIBLE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LIKELY", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="VERY_LIKELY", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=7732, - serialized_end=7833, -) -_sym_db.RegisterEnumDescriptor(_LIKELIHOOD) - -Likelihood = enum_type_wrapper.EnumTypeWrapper(_LIKELIHOOD) -UNKNOWN = 0 -VERY_UNLIKELY = 1 -UNLIKELY = 2 -POSSIBLE = 3 -LIKELY = 4 -VERY_LIKELY = 5 - - -_FEATURE_TYPE = _descriptor.EnumDescriptor( - name="Type", - full_name="google.cloud.vision.v1p3beta1.Feature.Type", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="TYPE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FACE_DETECTION", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LANDMARK_DETECTION", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LOGO_DETECTION", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LABEL_DETECTION", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="TEXT_DETECTION", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DOCUMENT_TEXT_DETECTION", - index=6, - number=11, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SAFE_SEARCH_DETECTION", - index=7, - number=6, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="IMAGE_PROPERTIES", - index=8, - number=7, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CROP_HINTS", - index=9, - number=9, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="WEB_DETECTION", - index=10, - number=10, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="PRODUCT_SEARCH", - index=11, - number=12, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="OBJECT_LOCALIZATION", - index=12, - number=19, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=660, - serialized_end=951, -) -_sym_db.RegisterEnumDescriptor(_FEATURE_TYPE) - -_FACEANNOTATION_LANDMARK_TYPE = _descriptor.EnumDescriptor( - name="Type", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.Landmark.Type", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNKNOWN_LANDMARK", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_OF_LEFT_EYEBROW", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_OF_LEFT_EYEBROW", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_OF_RIGHT_EYEBROW", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_OF_RIGHT_EYEBROW", - index=6, - number=6, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MIDPOINT_BETWEEN_EYES", - index=7, - number=7, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NOSE_TIP", - index=8, - number=8, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="UPPER_LIP", - index=9, - number=9, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LOWER_LIP", - index=10, - number=10, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MOUTH_LEFT", - index=11, - number=11, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MOUTH_RIGHT", - index=12, - number=12, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MOUTH_CENTER", - index=13, - number=13, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NOSE_BOTTOM_RIGHT", - index=14, - number=14, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NOSE_BOTTOM_LEFT", - index=15, - number=15, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NOSE_BOTTOM_CENTER", - index=16, - number=16, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_TOP_BOUNDARY", - index=17, - number=17, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_RIGHT_CORNER", - index=18, - number=18, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_BOTTOM_BOUNDARY", - index=19, - number=19, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_LEFT_CORNER", - index=20, - number=20, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_TOP_BOUNDARY", - index=21, - number=21, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_RIGHT_CORNER", - index=22, - number=22, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_BOTTOM_BOUNDARY", - index=23, - number=23, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_LEFT_CORNER", - index=24, - number=24, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYEBROW_UPPER_MIDPOINT", - index=25, - number=25, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYEBROW_UPPER_MIDPOINT", - index=26, - number=26, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EAR_TRAGION", - index=27, - number=27, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EAR_TRAGION", - index=28, - number=28, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_PUPIL", - index=29, - number=29, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_PUPIL", - index=30, - number=30, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FOREHEAD_GLABELLA", - index=31, - number=31, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CHIN_GNATHION", - index=32, - number=32, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CHIN_LEFT_GONION", - index=33, - number=33, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CHIN_RIGHT_GONION", - index=34, - number=34, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=2096, - serialized_end=2916, -) -_sym_db.RegisterEnumDescriptor(_FACEANNOTATION_LANDMARK_TYPE) - -_OPERATIONMETADATA_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.vision.v1p3beta1.OperationMetadata.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CREATED", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RUNNING", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DONE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLED", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=7649, - serialized_end=7730, -) -_sym_db.RegisterEnumDescriptor(_OPERATIONMETADATA_STATE) - - -_FEATURE = _descriptor.Descriptor( - name="Feature", - full_name="google.cloud.vision.v1p3beta1.Feature", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="type", - full_name="google.cloud.vision.v1p3beta1.Feature.type", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="max_results", - full_name="google.cloud.vision.v1p3beta1.Feature.max_results", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="model", - full_name="google.cloud.vision.v1p3beta1.Feature.model", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_FEATURE_TYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=553, - serialized_end=951, -) - - -_IMAGESOURCE = _descriptor.Descriptor( - name="ImageSource", - full_name="google.cloud.vision.v1p3beta1.ImageSource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_image_uri", - full_name="google.cloud.vision.v1p3beta1.ImageSource.gcs_image_uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_uri", - full_name="google.cloud.vision.v1p3beta1.ImageSource.image_uri", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=953, - serialized_end=1008, -) - - -_IMAGE = _descriptor.Descriptor( - name="Image", - full_name="google.cloud.vision.v1p3beta1.Image", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="content", - full_name="google.cloud.vision.v1p3beta1.Image.content", - index=0, - number=1, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"", - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source", - full_name="google.cloud.vision.v1p3beta1.Image.source", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1010, - serialized_end=1094, -) - - -_FACEANNOTATION_LANDMARK = _descriptor.Descriptor( - name="Landmark", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.Landmark", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="type", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.Landmark.type", - index=0, - number=3, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="position", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.Landmark.position", - index=1, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_FACEANNOTATION_LANDMARK_TYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1949, - serialized_end=2916, -) - -_FACEANNOTATION = _descriptor.Descriptor( - name="FaceAnnotation", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.bounding_poly", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="fd_bounding_poly", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.fd_bounding_poly", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="landmarks", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.landmarks", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="roll_angle", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.roll_angle", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="pan_angle", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.pan_angle", - index=4, - number=5, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="tilt_angle", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.tilt_angle", - index=5, - number=6, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="detection_confidence", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.detection_confidence", - index=6, - number=7, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="landmarking_confidence", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.landmarking_confidence", - index=7, - number=8, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="joy_likelihood", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.joy_likelihood", - index=8, - number=9, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="sorrow_likelihood", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.sorrow_likelihood", - index=9, - number=10, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="anger_likelihood", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.anger_likelihood", - index=10, - number=11, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="surprise_likelihood", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.surprise_likelihood", - index=11, - number=12, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="under_exposed_likelihood", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.under_exposed_likelihood", - index=12, - number=13, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="blurred_likelihood", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.blurred_likelihood", - index=13, - number=14, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="headwear_likelihood", - full_name="google.cloud.vision.v1p3beta1.FaceAnnotation.headwear_likelihood", - index=14, - number=15, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_FACEANNOTATION_LANDMARK,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1097, - serialized_end=2916, -) - - -_LOCATIONINFO = _descriptor.Descriptor( - name="LocationInfo", - full_name="google.cloud.vision.v1p3beta1.LocationInfo", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="lat_lng", - full_name="google.cloud.vision.v1p3beta1.LocationInfo.lat_lng", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2918, - serialized_end=2970, -) - - -_PROPERTY = _descriptor.Descriptor( - name="Property", - full_name="google.cloud.vision.v1p3beta1.Property", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p3beta1.Property.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.vision.v1p3beta1.Property.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="uint64_value", - full_name="google.cloud.vision.v1p3beta1.Property.uint64_value", - index=2, - number=3, - type=4, - cpp_type=4, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2972, - serialized_end=3033, -) - - -_ENTITYANNOTATION = _descriptor.Descriptor( - name="EntityAnnotation", - full_name="google.cloud.vision.v1p3beta1.EntityAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="mid", - full_name="google.cloud.vision.v1p3beta1.EntityAnnotation.mid", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="locale", - full_name="google.cloud.vision.v1p3beta1.EntityAnnotation.locale", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.vision.v1p3beta1.EntityAnnotation.description", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p3beta1.EntityAnnotation.score", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p3beta1.EntityAnnotation.confidence", - index=4, - number=5, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="topicality", - full_name="google.cloud.vision.v1p3beta1.EntityAnnotation.topicality", - index=5, - number=6, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p3beta1.EntityAnnotation.bounding_poly", - index=6, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="locations", - full_name="google.cloud.vision.v1p3beta1.EntityAnnotation.locations", - index=7, - number=8, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="properties", - full_name="google.cloud.vision.v1p3beta1.EntityAnnotation.properties", - index=8, - number=9, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3036, - serialized_end=3352, -) - - -_LOCALIZEDOBJECTANNOTATION = _descriptor.Descriptor( - name="LocalizedObjectAnnotation", - full_name="google.cloud.vision.v1p3beta1.LocalizedObjectAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="mid", - full_name="google.cloud.vision.v1p3beta1.LocalizedObjectAnnotation.mid", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="language_code", - full_name="google.cloud.vision.v1p3beta1.LocalizedObjectAnnotation.language_code", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p3beta1.LocalizedObjectAnnotation.name", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p3beta1.LocalizedObjectAnnotation.score", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p3beta1.LocalizedObjectAnnotation.bounding_poly", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3355, - serialized_end=3515, -) - - -_SAFESEARCHANNOTATION = _descriptor.Descriptor( - name="SafeSearchAnnotation", - full_name="google.cloud.vision.v1p3beta1.SafeSearchAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="adult", - full_name="google.cloud.vision.v1p3beta1.SafeSearchAnnotation.adult", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="spoof", - full_name="google.cloud.vision.v1p3beta1.SafeSearchAnnotation.spoof", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="medical", - full_name="google.cloud.vision.v1p3beta1.SafeSearchAnnotation.medical", - index=2, - number=3, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="violence", - full_name="google.cloud.vision.v1p3beta1.SafeSearchAnnotation.violence", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="racy", - full_name="google.cloud.vision.v1p3beta1.SafeSearchAnnotation.racy", - index=4, - number=9, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3518, - serialized_end=3834, -) - - -_LATLONGRECT = _descriptor.Descriptor( - name="LatLongRect", - full_name="google.cloud.vision.v1p3beta1.LatLongRect", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="min_lat_lng", - full_name="google.cloud.vision.v1p3beta1.LatLongRect.min_lat_lng", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="max_lat_lng", - full_name="google.cloud.vision.v1p3beta1.LatLongRect.max_lat_lng", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3836, - serialized_end=3933, -) - - -_COLORINFO = _descriptor.Descriptor( - name="ColorInfo", - full_name="google.cloud.vision.v1p3beta1.ColorInfo", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="color", - full_name="google.cloud.vision.v1p3beta1.ColorInfo.color", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p3beta1.ColorInfo.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="pixel_fraction", - full_name="google.cloud.vision.v1p3beta1.ColorInfo.pixel_fraction", - index=2, - number=3, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3935, - serialized_end=4020, -) - - -_DOMINANTCOLORSANNOTATION = _descriptor.Descriptor( - name="DominantColorsAnnotation", - full_name="google.cloud.vision.v1p3beta1.DominantColorsAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="colors", - full_name="google.cloud.vision.v1p3beta1.DominantColorsAnnotation.colors", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4022, - serialized_end=4106, -) - - -_IMAGEPROPERTIES = _descriptor.Descriptor( - name="ImageProperties", - full_name="google.cloud.vision.v1p3beta1.ImageProperties", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="dominant_colors", - full_name="google.cloud.vision.v1p3beta1.ImageProperties.dominant_colors", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4108, - serialized_end=4207, -) - - -_CROPHINT = _descriptor.Descriptor( - name="CropHint", - full_name="google.cloud.vision.v1p3beta1.CropHint", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p3beta1.CropHint.bounding_poly", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p3beta1.CropHint.confidence", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="importance_fraction", - full_name="google.cloud.vision.v1p3beta1.CropHint.importance_fraction", - index=2, - number=3, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4209, - serialized_end=4336, -) - - -_CROPHINTSANNOTATION = _descriptor.Descriptor( - name="CropHintsAnnotation", - full_name="google.cloud.vision.v1p3beta1.CropHintsAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="crop_hints", - full_name="google.cloud.vision.v1p3beta1.CropHintsAnnotation.crop_hints", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4338, - serialized_end=4420, -) - - -_CROPHINTSPARAMS = _descriptor.Descriptor( - name="CropHintsParams", - full_name="google.cloud.vision.v1p3beta1.CropHintsParams", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="aspect_ratios", - full_name="google.cloud.vision.v1p3beta1.CropHintsParams.aspect_ratios", - index=0, - number=1, - type=2, - cpp_type=6, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4422, - serialized_end=4462, -) - - -_WEBDETECTIONPARAMS = _descriptor.Descriptor( - name="WebDetectionParams", - full_name="google.cloud.vision.v1p3beta1.WebDetectionParams", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="include_geo_results", - full_name="google.cloud.vision.v1p3beta1.WebDetectionParams.include_geo_results", - index=0, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4464, - serialized_end=4513, -) - - -_IMAGECONTEXT = _descriptor.Descriptor( - name="ImageContext", - full_name="google.cloud.vision.v1p3beta1.ImageContext", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="lat_long_rect", - full_name="google.cloud.vision.v1p3beta1.ImageContext.lat_long_rect", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="language_hints", - full_name="google.cloud.vision.v1p3beta1.ImageContext.language_hints", - index=1, - number=2, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="crop_hints_params", - full_name="google.cloud.vision.v1p3beta1.ImageContext.crop_hints_params", - index=2, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_search_params", - full_name="google.cloud.vision.v1p3beta1.ImageContext.product_search_params", - index=3, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="web_detection_params", - full_name="google.cloud.vision.v1p3beta1.ImageContext.web_detection_params", - index=4, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4516, - serialized_end=4860, -) - - -_ANNOTATEIMAGEREQUEST = _descriptor.Descriptor( - name="AnnotateImageRequest", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="image", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageRequest.image", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="features", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageRequest.features", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_context", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageRequest.image_context", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4863, - serialized_end=5064, -) - - -_IMAGEANNOTATIONCONTEXT = _descriptor.Descriptor( - name="ImageAnnotationContext", - full_name="google.cloud.vision.v1p3beta1.ImageAnnotationContext", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="uri", - full_name="google.cloud.vision.v1p3beta1.ImageAnnotationContext.uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_number", - full_name="google.cloud.vision.v1p3beta1.ImageAnnotationContext.page_number", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5066, - serialized_end=5124, -) - - -_ANNOTATEIMAGERESPONSE = _descriptor.Descriptor( - name="AnnotateImageResponse", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="face_annotations", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageResponse.face_annotations", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="landmark_annotations", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageResponse.landmark_annotations", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="logo_annotations", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageResponse.logo_annotations", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="label_annotations", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageResponse.label_annotations", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="localized_object_annotations", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageResponse.localized_object_annotations", - index=4, - number=22, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="text_annotations", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageResponse.text_annotations", - index=5, - number=5, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="full_text_annotation", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageResponse.full_text_annotation", - index=6, - number=12, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="safe_search_annotation", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageResponse.safe_search_annotation", - index=7, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_properties_annotation", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageResponse.image_properties_annotation", - index=8, - number=8, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="crop_hints_annotation", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageResponse.crop_hints_annotation", - index=9, - number=11, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="web_detection", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageResponse.web_detection", - index=10, - number=13, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_search_results", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageResponse.product_search_results", - index=11, - number=14, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="error", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageResponse.error", - index=12, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="context", - full_name="google.cloud.vision.v1p3beta1.AnnotateImageResponse.context", - index=13, - number=21, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5127, - serialized_end=6214, -) - - -_ANNOTATEFILERESPONSE = _descriptor.Descriptor( - name="AnnotateFileResponse", - full_name="google.cloud.vision.v1p3beta1.AnnotateFileResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="input_config", - full_name="google.cloud.vision.v1p3beta1.AnnotateFileResponse.input_config", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="responses", - full_name="google.cloud.vision.v1p3beta1.AnnotateFileResponse.responses", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6217, - serialized_end=6378, -) - - -_BATCHANNOTATEIMAGESREQUEST = _descriptor.Descriptor( - name="BatchAnnotateImagesRequest", - full_name="google.cloud.vision.v1p3beta1.BatchAnnotateImagesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="requests", - full_name="google.cloud.vision.v1p3beta1.BatchAnnotateImagesRequest.requests", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6380, - serialized_end=6479, -) - - -_BATCHANNOTATEIMAGESRESPONSE = _descriptor.Descriptor( - name="BatchAnnotateImagesResponse", - full_name="google.cloud.vision.v1p3beta1.BatchAnnotateImagesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="responses", - full_name="google.cloud.vision.v1p3beta1.BatchAnnotateImagesResponse.responses", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6481, - serialized_end=6583, -) - - -_ASYNCANNOTATEFILEREQUEST = _descriptor.Descriptor( - name="AsyncAnnotateFileRequest", - full_name="google.cloud.vision.v1p3beta1.AsyncAnnotateFileRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="input_config", - full_name="google.cloud.vision.v1p3beta1.AsyncAnnotateFileRequest.input_config", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="features", - full_name="google.cloud.vision.v1p3beta1.AsyncAnnotateFileRequest.features", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_context", - full_name="google.cloud.vision.v1p3beta1.AsyncAnnotateFileRequest.image_context", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="output_config", - full_name="google.cloud.vision.v1p3beta1.AsyncAnnotateFileRequest.output_config", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6586, - serialized_end=6872, -) - - -_ASYNCANNOTATEFILERESPONSE = _descriptor.Descriptor( - name="AsyncAnnotateFileResponse", - full_name="google.cloud.vision.v1p3beta1.AsyncAnnotateFileResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="output_config", - full_name="google.cloud.vision.v1p3beta1.AsyncAnnotateFileResponse.output_config", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6874, - serialized_end=6969, -) - - -_ASYNCBATCHANNOTATEFILESREQUEST = _descriptor.Descriptor( - name="AsyncBatchAnnotateFilesRequest", - full_name="google.cloud.vision.v1p3beta1.AsyncBatchAnnotateFilesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="requests", - full_name="google.cloud.vision.v1p3beta1.AsyncBatchAnnotateFilesRequest.requests", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6971, - serialized_end=7083, -) - - -_ASYNCBATCHANNOTATEFILESRESPONSE = _descriptor.Descriptor( - name="AsyncBatchAnnotateFilesResponse", - full_name="google.cloud.vision.v1p3beta1.AsyncBatchAnnotateFilesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="responses", - full_name="google.cloud.vision.v1p3beta1.AsyncBatchAnnotateFilesResponse.responses", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=7085, - serialized_end=7195, -) - - -_INPUTCONFIG = _descriptor.Descriptor( - name="InputConfig", - full_name="google.cloud.vision.v1p3beta1.InputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_source", - full_name="google.cloud.vision.v1p3beta1.InputConfig.gcs_source", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="mime_type", - full_name="google.cloud.vision.v1p3beta1.InputConfig.mime_type", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=7197, - serialized_end=7291, -) - - -_OUTPUTCONFIG = _descriptor.Descriptor( - name="OutputConfig", - full_name="google.cloud.vision.v1p3beta1.OutputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_destination", - full_name="google.cloud.vision.v1p3beta1.OutputConfig.gcs_destination", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="batch_size", - full_name="google.cloud.vision.v1p3beta1.OutputConfig.batch_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=7293, - serialized_end=7399, -) - - -_GCSSOURCE = _descriptor.Descriptor( - name="GcsSource", - full_name="google.cloud.vision.v1p3beta1.GcsSource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="uri", - full_name="google.cloud.vision.v1p3beta1.GcsSource.uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=7401, - serialized_end=7425, -) - - -_GCSDESTINATION = _descriptor.Descriptor( - name="GcsDestination", - full_name="google.cloud.vision.v1p3beta1.GcsDestination", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="uri", - full_name="google.cloud.vision.v1p3beta1.GcsDestination.uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=7427, - serialized_end=7456, -) - - -_OPERATIONMETADATA = _descriptor.Descriptor( - name="OperationMetadata", - full_name="google.cloud.vision.v1p3beta1.OperationMetadata", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.vision.v1p3beta1.OperationMetadata.state", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="create_time", - full_name="google.cloud.vision.v1p3beta1.OperationMetadata.create_time", - index=1, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_time", - full_name="google.cloud.vision.v1p3beta1.OperationMetadata.update_time", - index=2, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_OPERATIONMETADATA_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=7459, - serialized_end=7730, -) - -_FEATURE.fields_by_name["type"].enum_type = _FEATURE_TYPE -_FEATURE_TYPE.containing_type = _FEATURE -_IMAGE.fields_by_name["source"].message_type = _IMAGESOURCE -_FACEANNOTATION_LANDMARK.fields_by_name[ - "type" -].enum_type = _FACEANNOTATION_LANDMARK_TYPE -_FACEANNOTATION_LANDMARK.fields_by_name[ - "position" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2._POSITION -) -_FACEANNOTATION_LANDMARK.containing_type = _FACEANNOTATION -_FACEANNOTATION_LANDMARK_TYPE.containing_type = _FACEANNOTATION_LANDMARK -_FACEANNOTATION.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_FACEANNOTATION.fields_by_name[ - "fd_bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_FACEANNOTATION.fields_by_name["landmarks"].message_type = _FACEANNOTATION_LANDMARK -_FACEANNOTATION.fields_by_name["joy_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["sorrow_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["anger_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["surprise_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["under_exposed_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["blurred_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["headwear_likelihood"].enum_type = _LIKELIHOOD -_LOCATIONINFO.fields_by_name[ - "lat_lng" -].message_type = google_dot_type_dot_latlng__pb2._LATLNG -_ENTITYANNOTATION.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_ENTITYANNOTATION.fields_by_name["locations"].message_type = _LOCATIONINFO -_ENTITYANNOTATION.fields_by_name["properties"].message_type = _PROPERTY -_LOCALIZEDOBJECTANNOTATION.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_SAFESEARCHANNOTATION.fields_by_name["adult"].enum_type = _LIKELIHOOD -_SAFESEARCHANNOTATION.fields_by_name["spoof"].enum_type = _LIKELIHOOD -_SAFESEARCHANNOTATION.fields_by_name["medical"].enum_type = _LIKELIHOOD -_SAFESEARCHANNOTATION.fields_by_name["violence"].enum_type = _LIKELIHOOD -_SAFESEARCHANNOTATION.fields_by_name["racy"].enum_type = _LIKELIHOOD -_LATLONGRECT.fields_by_name[ - "min_lat_lng" -].message_type = google_dot_type_dot_latlng__pb2._LATLNG -_LATLONGRECT.fields_by_name[ - "max_lat_lng" -].message_type = google_dot_type_dot_latlng__pb2._LATLNG -_COLORINFO.fields_by_name["color"].message_type = google_dot_type_dot_color__pb2._COLOR -_DOMINANTCOLORSANNOTATION.fields_by_name["colors"].message_type = _COLORINFO -_IMAGEPROPERTIES.fields_by_name[ - "dominant_colors" -].message_type = _DOMINANTCOLORSANNOTATION -_CROPHINT.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_CROPHINTSANNOTATION.fields_by_name["crop_hints"].message_type = _CROPHINT -_IMAGECONTEXT.fields_by_name["lat_long_rect"].message_type = _LATLONGRECT -_IMAGECONTEXT.fields_by_name["crop_hints_params"].message_type = _CROPHINTSPARAMS -_IMAGECONTEXT.fields_by_name[ - "product_search_params" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__pb2._PRODUCTSEARCHPARAMS -) -_IMAGECONTEXT.fields_by_name["web_detection_params"].message_type = _WEBDETECTIONPARAMS -_ANNOTATEIMAGEREQUEST.fields_by_name["image"].message_type = _IMAGE -_ANNOTATEIMAGEREQUEST.fields_by_name["features"].message_type = _FEATURE -_ANNOTATEIMAGEREQUEST.fields_by_name["image_context"].message_type = _IMAGECONTEXT -_ANNOTATEIMAGERESPONSE.fields_by_name["face_annotations"].message_type = _FACEANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "landmark_annotations" -].message_type = _ENTITYANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "logo_annotations" -].message_type = _ENTITYANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "label_annotations" -].message_type = _ENTITYANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "localized_object_annotations" -].message_type = _LOCALIZEDOBJECTANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "text_annotations" -].message_type = _ENTITYANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "full_text_annotation" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_text__annotation__pb2._TEXTANNOTATION -) -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "safe_search_annotation" -].message_type = _SAFESEARCHANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "image_properties_annotation" -].message_type = _IMAGEPROPERTIES -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "crop_hints_annotation" -].message_type = _CROPHINTSANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "web_detection" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_web__detection__pb2._WEBDETECTION -) -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "product_search_results" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__pb2._PRODUCTSEARCHRESULTS -) -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "error" -].message_type = google_dot_rpc_dot_status__pb2._STATUS -_ANNOTATEIMAGERESPONSE.fields_by_name["context"].message_type = _IMAGEANNOTATIONCONTEXT -_ANNOTATEFILERESPONSE.fields_by_name["input_config"].message_type = _INPUTCONFIG -_ANNOTATEFILERESPONSE.fields_by_name["responses"].message_type = _ANNOTATEIMAGERESPONSE -_BATCHANNOTATEIMAGESREQUEST.fields_by_name[ - "requests" -].message_type = _ANNOTATEIMAGEREQUEST -_BATCHANNOTATEIMAGESRESPONSE.fields_by_name[ - "responses" -].message_type = _ANNOTATEIMAGERESPONSE -_ASYNCANNOTATEFILEREQUEST.fields_by_name["input_config"].message_type = _INPUTCONFIG -_ASYNCANNOTATEFILEREQUEST.fields_by_name["features"].message_type = _FEATURE -_ASYNCANNOTATEFILEREQUEST.fields_by_name["image_context"].message_type = _IMAGECONTEXT -_ASYNCANNOTATEFILEREQUEST.fields_by_name["output_config"].message_type = _OUTPUTCONFIG -_ASYNCANNOTATEFILERESPONSE.fields_by_name["output_config"].message_type = _OUTPUTCONFIG -_ASYNCBATCHANNOTATEFILESREQUEST.fields_by_name[ - "requests" -].message_type = _ASYNCANNOTATEFILEREQUEST -_ASYNCBATCHANNOTATEFILESRESPONSE.fields_by_name[ - "responses" -].message_type = _ASYNCANNOTATEFILERESPONSE -_INPUTCONFIG.fields_by_name["gcs_source"].message_type = _GCSSOURCE -_OUTPUTCONFIG.fields_by_name["gcs_destination"].message_type = _GCSDESTINATION -_OPERATIONMETADATA.fields_by_name["state"].enum_type = _OPERATIONMETADATA_STATE -_OPERATIONMETADATA.fields_by_name[ - "create_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_OPERATIONMETADATA.fields_by_name[ - "update_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_OPERATIONMETADATA_STATE.containing_type = _OPERATIONMETADATA -DESCRIPTOR.message_types_by_name["Feature"] = _FEATURE -DESCRIPTOR.message_types_by_name["ImageSource"] = _IMAGESOURCE -DESCRIPTOR.message_types_by_name["Image"] = _IMAGE -DESCRIPTOR.message_types_by_name["FaceAnnotation"] = _FACEANNOTATION -DESCRIPTOR.message_types_by_name["LocationInfo"] = _LOCATIONINFO -DESCRIPTOR.message_types_by_name["Property"] = _PROPERTY -DESCRIPTOR.message_types_by_name["EntityAnnotation"] = _ENTITYANNOTATION -DESCRIPTOR.message_types_by_name[ - "LocalizedObjectAnnotation" -] = _LOCALIZEDOBJECTANNOTATION -DESCRIPTOR.message_types_by_name["SafeSearchAnnotation"] = _SAFESEARCHANNOTATION -DESCRIPTOR.message_types_by_name["LatLongRect"] = _LATLONGRECT -DESCRIPTOR.message_types_by_name["ColorInfo"] = _COLORINFO -DESCRIPTOR.message_types_by_name["DominantColorsAnnotation"] = _DOMINANTCOLORSANNOTATION -DESCRIPTOR.message_types_by_name["ImageProperties"] = _IMAGEPROPERTIES -DESCRIPTOR.message_types_by_name["CropHint"] = _CROPHINT -DESCRIPTOR.message_types_by_name["CropHintsAnnotation"] = _CROPHINTSANNOTATION -DESCRIPTOR.message_types_by_name["CropHintsParams"] = _CROPHINTSPARAMS -DESCRIPTOR.message_types_by_name["WebDetectionParams"] = _WEBDETECTIONPARAMS -DESCRIPTOR.message_types_by_name["ImageContext"] = _IMAGECONTEXT -DESCRIPTOR.message_types_by_name["AnnotateImageRequest"] = _ANNOTATEIMAGEREQUEST -DESCRIPTOR.message_types_by_name["ImageAnnotationContext"] = _IMAGEANNOTATIONCONTEXT -DESCRIPTOR.message_types_by_name["AnnotateImageResponse"] = _ANNOTATEIMAGERESPONSE -DESCRIPTOR.message_types_by_name["AnnotateFileResponse"] = _ANNOTATEFILERESPONSE -DESCRIPTOR.message_types_by_name[ - "BatchAnnotateImagesRequest" -] = _BATCHANNOTATEIMAGESREQUEST -DESCRIPTOR.message_types_by_name[ - "BatchAnnotateImagesResponse" -] = _BATCHANNOTATEIMAGESRESPONSE -DESCRIPTOR.message_types_by_name["AsyncAnnotateFileRequest"] = _ASYNCANNOTATEFILEREQUEST -DESCRIPTOR.message_types_by_name[ - "AsyncAnnotateFileResponse" -] = _ASYNCANNOTATEFILERESPONSE -DESCRIPTOR.message_types_by_name[ - "AsyncBatchAnnotateFilesRequest" -] = _ASYNCBATCHANNOTATEFILESREQUEST -DESCRIPTOR.message_types_by_name[ - "AsyncBatchAnnotateFilesResponse" -] = _ASYNCBATCHANNOTATEFILESRESPONSE -DESCRIPTOR.message_types_by_name["InputConfig"] = _INPUTCONFIG -DESCRIPTOR.message_types_by_name["OutputConfig"] = _OUTPUTCONFIG -DESCRIPTOR.message_types_by_name["GcsSource"] = _GCSSOURCE -DESCRIPTOR.message_types_by_name["GcsDestination"] = _GCSDESTINATION -DESCRIPTOR.message_types_by_name["OperationMetadata"] = _OPERATIONMETADATA -DESCRIPTOR.enum_types_by_name["Likelihood"] = _LIKELIHOOD -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Feature = _reflection.GeneratedProtocolMessageType( - "Feature", - (_message.Message,), - { - "DESCRIPTOR": _FEATURE, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """The type of Google Cloud Vision API detection to perform, and the - maximum number of results to return for that type. Multiple - ``Feature`` objects can be specified in the ``features`` list. - - Attributes: - type: - The feature type. - max_results: - Maximum number of results of this type. Does not apply to - ``TEXT_DETECTION``, ``DOCUMENT_TEXT_DETECTION``, or - ``CROP_HINTS``. - model: - Model to use for the feature. Supported values: - “builtin/stable” (the default if unset) and “builtin/latest”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.Feature) - }, -) -_sym_db.RegisterMessage(Feature) - -ImageSource = _reflection.GeneratedProtocolMessageType( - "ImageSource", - (_message.Message,), - { - "DESCRIPTOR": _IMAGESOURCE, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """External image source (Google Cloud Storage or web URL image - location). - - Attributes: - gcs_image_uri: - \ **Use ``image_uri`` instead.** The Google Cloud Storage URI - of the form ``gs://bucket_name/object_name``. Object - versioning is not supported. See `Google Cloud Storage Request - URIs `__ - for more info. - image_uri: - The URI of the source image. Can be either: 1. A Google Cloud - Storage URI of the form ``gs://bucket_name/object_name``. - Object versioning is not supported. See `Google Cloud - Storage Request URIs - `__ for - more info. 2. A publicly-accessible image HTTP/HTTPS URL. - When fetching images from HTTP/HTTPS URLs, Google cannot - guarantee that the request will be completed. Your request - may fail if the specified host denies the request (e.g. due - to request throttling or DOS prevention), or if Google - throttles requests to the site for abuse prevention. You - should not depend on externally-hosted images for production - applications. When both ``gcs_image_uri`` and ``image_uri`` - are specified, ``image_uri`` takes precedence. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ImageSource) - }, -) -_sym_db.RegisterMessage(ImageSource) - -Image = _reflection.GeneratedProtocolMessageType( - "Image", - (_message.Message,), - { - "DESCRIPTOR": _IMAGE, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Client image to perform Google Cloud Vision API tasks over. - - Attributes: - content: - Image content, represented as a stream of bytes. Note: As with - all ``bytes`` fields, protobuffers use a pure binary - representation, whereas JSON representations use base64. - source: - Google Cloud Storage image location, or publicly-accessible - image URL. If both ``content`` and ``source`` are provided for - an image, ``content`` takes precedence and is used to perform - the image annotation request. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.Image) - }, -) -_sym_db.RegisterMessage(Image) - -FaceAnnotation = _reflection.GeneratedProtocolMessageType( - "FaceAnnotation", - (_message.Message,), - { - "Landmark": _reflection.GeneratedProtocolMessageType( - "Landmark", - (_message.Message,), - { - "DESCRIPTOR": _FACEANNOTATION_LANDMARK, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """A face-specific landmark (for example, a face feature). - - Attributes: - type: - Face landmark type. - position: - Face landmark position. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.FaceAnnotation.Landmark) - }, - ), - "DESCRIPTOR": _FACEANNOTATION, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """A face annotation object contains the results of face detection. - - Attributes: - bounding_poly: - The bounding polygon around the face. The coordinates of the - bounding box are in the original image’s scale, as returned in - ``ImageParams``. The bounding box is computed to “frame” the - face in accordance with human expectations. It is based on the - landmarker results. Note that one or more x and/or y - coordinates may not be generated in the ``BoundingPoly`` (the - polygon will be unbounded) if only a partial face appears in - the image to be annotated. - fd_bounding_poly: - The ``fd_bounding_poly`` bounding polygon is tighter than the - ``boundingPoly``, and encloses only the skin part of the face. - Typically, it is used to eliminate the face from any image - analysis that detects the “amount of skin” visible in an - image. It is not based on the landmarker results, only on the - initial face detection, hence the fd (face detection) prefix. - landmarks: - Detected face landmarks. - roll_angle: - Roll angle, which indicates the amount of clockwise/anti- - clockwise rotation of the face relative to the image vertical - about the axis perpendicular to the face. Range [-180,180]. - pan_angle: - Yaw angle, which indicates the leftward/rightward angle that - the face is pointing relative to the vertical plane - perpendicular to the image. Range [-180,180]. - tilt_angle: - Pitch angle, which indicates the upwards/downwards angle that - the face is pointing relative to the image’s horizontal plane. - Range [-180,180]. - detection_confidence: - Detection confidence. Range [0, 1]. - landmarking_confidence: - Face landmarking confidence. Range [0, 1]. - joy_likelihood: - Joy likelihood. - sorrow_likelihood: - Sorrow likelihood. - anger_likelihood: - Anger likelihood. - surprise_likelihood: - Surprise likelihood. - under_exposed_likelihood: - Under-exposed likelihood. - blurred_likelihood: - Blurred likelihood. - headwear_likelihood: - Headwear likelihood. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.FaceAnnotation) - }, -) -_sym_db.RegisterMessage(FaceAnnotation) -_sym_db.RegisterMessage(FaceAnnotation.Landmark) - -LocationInfo = _reflection.GeneratedProtocolMessageType( - "LocationInfo", - (_message.Message,), - { - "DESCRIPTOR": _LOCATIONINFO, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Detected entity location information. - - Attributes: - lat_lng: - lat/long location coordinates. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.LocationInfo) - }, -) -_sym_db.RegisterMessage(LocationInfo) - -Property = _reflection.GeneratedProtocolMessageType( - "Property", - (_message.Message,), - { - "DESCRIPTOR": _PROPERTY, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """A ``Property`` consists of a user-supplied name/value pair. - - Attributes: - name: - Name of the property. - value: - Value of the property. - uint64_value: - Value of numeric properties. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.Property) - }, -) -_sym_db.RegisterMessage(Property) - -EntityAnnotation = _reflection.GeneratedProtocolMessageType( - "EntityAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _ENTITYANNOTATION, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Set of detected entity features. - - Attributes: - mid: - Opaque entity ID. Some IDs may be available in `Google - Knowledge Graph Search API - `__. - locale: - The language code for the locale in which the entity textual - ``description`` is expressed. - description: - Entity textual description, expressed in its ``locale`` - language. - score: - Overall score of the result. Range [0, 1]. - confidence: - \ **Deprecated. Use ``score`` instead.** The accuracy of the - entity detection in an image. For example, for an image in - which the “Eiffel Tower” entity is detected, this field - represents the confidence that there is a tower in the query - image. Range [0, 1]. - topicality: - The relevancy of the ICA (Image Content Annotation) label to - the image. For example, the relevancy of “tower” is likely - higher to an image containing the detected “Eiffel Tower” than - to an image containing a detected distant towering building, - even though the confidence that there is a tower in each image - may be the same. Range [0, 1]. - bounding_poly: - Image region to which this entity belongs. Not produced for - ``LABEL_DETECTION`` features. - locations: - The location information for the detected entity. Multiple - ``LocationInfo`` elements can be present because one location - may indicate the location of the scene in the image, and - another location may indicate the location of the place where - the image was taken. Location information is usually present - for landmarks. - properties: - Some entities may have optional user-supplied ``Property`` - (name/value) fields, such a score or string that qualifies the - entity. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.EntityAnnotation) - }, -) -_sym_db.RegisterMessage(EntityAnnotation) - -LocalizedObjectAnnotation = _reflection.GeneratedProtocolMessageType( - "LocalizedObjectAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _LOCALIZEDOBJECTANNOTATION, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Set of detected objects with bounding boxes. - - Attributes: - mid: - Object ID that should align with EntityAnnotation mid. - language_code: - The BCP-47 language code, such as “en-US” or “sr-Latn”. For - more information, see http://www.unicode.org/reports/tr35/#Uni - code_locale_identifier. - name: - Object name, expressed in its ``language_code`` language. - score: - Score of the result. Range [0, 1]. - bounding_poly: - Image region to which this object belongs. This must be - populated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.LocalizedObjectAnnotation) - }, -) -_sym_db.RegisterMessage(LocalizedObjectAnnotation) - -SafeSearchAnnotation = _reflection.GeneratedProtocolMessageType( - "SafeSearchAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _SAFESEARCHANNOTATION, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Set of features pertaining to the image, computed by computer vision - methods over safe-search verticals (for example, adult, spoof, - medical, violence). - - Attributes: - adult: - Represents the adult content likelihood for the image. Adult - content may contain elements such as nudity, pornographic - images or cartoons, or sexual activities. - spoof: - Spoof likelihood. The likelihood that an modification was made - to the image’s canonical version to make it appear funny or - offensive. - medical: - Likelihood that this is a medical image. - violence: - Likelihood that this image contains violent content. - racy: - Likelihood that the request image contains racy content. Racy - content may include (but is not limited to) skimpy or sheer - clothing, strategically covered nudity, lewd or provocative - poses, or close-ups of sensitive body areas. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.SafeSearchAnnotation) - }, -) -_sym_db.RegisterMessage(SafeSearchAnnotation) - -LatLongRect = _reflection.GeneratedProtocolMessageType( - "LatLongRect", - (_message.Message,), - { - "DESCRIPTOR": _LATLONGRECT, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Rectangle determined by min and max ``LatLng`` pairs. - - Attributes: - min_lat_lng: - Min lat/long pair. - max_lat_lng: - Max lat/long pair. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.LatLongRect) - }, -) -_sym_db.RegisterMessage(LatLongRect) - -ColorInfo = _reflection.GeneratedProtocolMessageType( - "ColorInfo", - (_message.Message,), - { - "DESCRIPTOR": _COLORINFO, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Color information consists of RGB channels, score, and the fraction of - the image that the color occupies in the image. - - Attributes: - color: - RGB components of the color. - score: - Image-specific score for this color. Value in range [0, 1]. - pixel_fraction: - The fraction of pixels the color occupies in the image. Value - in range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ColorInfo) - }, -) -_sym_db.RegisterMessage(ColorInfo) - -DominantColorsAnnotation = _reflection.GeneratedProtocolMessageType( - "DominantColorsAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _DOMINANTCOLORSANNOTATION, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Set of dominant colors and their corresponding scores. - - Attributes: - colors: - RGB color values with their score and pixel fraction. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.DominantColorsAnnotation) - }, -) -_sym_db.RegisterMessage(DominantColorsAnnotation) - -ImageProperties = _reflection.GeneratedProtocolMessageType( - "ImageProperties", - (_message.Message,), - { - "DESCRIPTOR": _IMAGEPROPERTIES, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Stores image properties, such as dominant colors. - - Attributes: - dominant_colors: - If present, dominant colors completed successfully. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ImageProperties) - }, -) -_sym_db.RegisterMessage(ImageProperties) - -CropHint = _reflection.GeneratedProtocolMessageType( - "CropHint", - (_message.Message,), - { - "DESCRIPTOR": _CROPHINT, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Single crop hint that is used to generate a new crop when serving an - image. - - Attributes: - bounding_poly: - The bounding polygon for the crop region. The coordinates of - the bounding box are in the original image’s scale, as - returned in ``ImageParams``. - confidence: - Confidence of this being a salient region. Range [0, 1]. - importance_fraction: - Fraction of importance of this salient region with respect to - the original image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.CropHint) - }, -) -_sym_db.RegisterMessage(CropHint) - -CropHintsAnnotation = _reflection.GeneratedProtocolMessageType( - "CropHintsAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _CROPHINTSANNOTATION, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Set of crop hints that are used to generate new crops when serving - images. - - Attributes: - crop_hints: - Crop hint results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.CropHintsAnnotation) - }, -) -_sym_db.RegisterMessage(CropHintsAnnotation) - -CropHintsParams = _reflection.GeneratedProtocolMessageType( - "CropHintsParams", - (_message.Message,), - { - "DESCRIPTOR": _CROPHINTSPARAMS, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Parameters for crop hints annotation request. - - Attributes: - aspect_ratios: - Aspect ratios in floats, representing the ratio of the width - to the height of the image. For example, if the desired aspect - ratio is 4/3, the corresponding float value should be 1.33333. - If not specified, the best possible crop is returned. The - number of provided aspect ratios is limited to a maximum of - 16; any aspect ratios provided after the 16th are ignored. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.CropHintsParams) - }, -) -_sym_db.RegisterMessage(CropHintsParams) - -WebDetectionParams = _reflection.GeneratedProtocolMessageType( - "WebDetectionParams", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTIONPARAMS, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Parameters for web detection request. - - Attributes: - include_geo_results: - Whether to include results derived from the geo information in - the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.WebDetectionParams) - }, -) -_sym_db.RegisterMessage(WebDetectionParams) - -ImageContext = _reflection.GeneratedProtocolMessageType( - "ImageContext", - (_message.Message,), - { - "DESCRIPTOR": _IMAGECONTEXT, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Image context and/or feature-specific parameters. - - Attributes: - lat_long_rect: - Not used. - language_hints: - List of languages to use for TEXT_DETECTION. In most cases, an - empty value yields the best results since it enables automatic - language detection. For languages based on the Latin alphabet, - setting ``language_hints`` is not needed. In rare cases, when - the language of the text in the image is known, setting a hint - will help get better results (although it will be a - significant hindrance if the hint is wrong). Text detection - returns an error if one or more of the specified languages is - not one of the `supported languages - `__. - crop_hints_params: - Parameters for crop hints annotation request. - product_search_params: - Parameters for product search. - web_detection_params: - Parameters for web detection. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ImageContext) - }, -) -_sym_db.RegisterMessage(ImageContext) - -AnnotateImageRequest = _reflection.GeneratedProtocolMessageType( - "AnnotateImageRequest", - (_message.Message,), - { - "DESCRIPTOR": _ANNOTATEIMAGEREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Request for performing Google Cloud Vision API tasks over a user- - provided image, with user-requested features. - - Attributes: - image: - The image to be processed. - features: - Requested features. - image_context: - Additional context that may accompany the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.AnnotateImageRequest) - }, -) -_sym_db.RegisterMessage(AnnotateImageRequest) - -ImageAnnotationContext = _reflection.GeneratedProtocolMessageType( - "ImageAnnotationContext", - (_message.Message,), - { - "DESCRIPTOR": _IMAGEANNOTATIONCONTEXT, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """If an image was produced from a file (e.g. a PDF), this message gives - information about the source of that image. - - Attributes: - uri: - The URI of the file used to produce the image. - page_number: - If the file was a PDF or TIFF, this field gives the page - number within the file used to produce the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ImageAnnotationContext) - }, -) -_sym_db.RegisterMessage(ImageAnnotationContext) - -AnnotateImageResponse = _reflection.GeneratedProtocolMessageType( - "AnnotateImageResponse", - (_message.Message,), - { - "DESCRIPTOR": _ANNOTATEIMAGERESPONSE, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Response to an image annotation request. - - Attributes: - face_annotations: - If present, face detection has completed successfully. - landmark_annotations: - If present, landmark detection has completed successfully. - logo_annotations: - If present, logo detection has completed successfully. - label_annotations: - If present, label detection has completed successfully. - localized_object_annotations: - If present, localized object detection has completed - successfully. This will be sorted descending by confidence - score. - text_annotations: - If present, text (OCR) detection has completed successfully. - full_text_annotation: - If present, text (OCR) detection or document (OCR) text - detection has completed successfully. This annotation provides - the structural hierarchy for the OCR detected text. - safe_search_annotation: - If present, safe-search annotation has completed successfully. - image_properties_annotation: - If present, image properties were extracted successfully. - crop_hints_annotation: - If present, crop hints have completed successfully. - web_detection: - If present, web detection has completed successfully. - product_search_results: - If present, product search has completed successfully. - error: - If set, represents the error message for the operation. Note - that filled-in image annotations are guaranteed to be correct, - even when ``error`` is set. - context: - If present, contextual information is needed to understand - where this image comes from. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.AnnotateImageResponse) - }, -) -_sym_db.RegisterMessage(AnnotateImageResponse) - -AnnotateFileResponse = _reflection.GeneratedProtocolMessageType( - "AnnotateFileResponse", - (_message.Message,), - { - "DESCRIPTOR": _ANNOTATEFILERESPONSE, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Response to a single file annotation request. A file may contain one - or more images, which individually have their own responses. - - Attributes: - input_config: - Information about the file for which this response is - generated. - responses: - Individual responses to images found within the file. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.AnnotateFileResponse) - }, -) -_sym_db.RegisterMessage(AnnotateFileResponse) - -BatchAnnotateImagesRequest = _reflection.GeneratedProtocolMessageType( - "BatchAnnotateImagesRequest", - (_message.Message,), - { - "DESCRIPTOR": _BATCHANNOTATEIMAGESREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Multiple image annotation requests are batched into a single service - call. - - Attributes: - requests: - Individual image annotation requests for this batch. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.BatchAnnotateImagesRequest) - }, -) -_sym_db.RegisterMessage(BatchAnnotateImagesRequest) - -BatchAnnotateImagesResponse = _reflection.GeneratedProtocolMessageType( - "BatchAnnotateImagesResponse", - (_message.Message,), - { - "DESCRIPTOR": _BATCHANNOTATEIMAGESRESPONSE, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Response to a batch image annotation request. - - Attributes: - responses: - Individual responses to image annotation requests within the - batch. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.BatchAnnotateImagesResponse) - }, -) -_sym_db.RegisterMessage(BatchAnnotateImagesResponse) - -AsyncAnnotateFileRequest = _reflection.GeneratedProtocolMessageType( - "AsyncAnnotateFileRequest", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCANNOTATEFILEREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """An offline file annotation request. - - Attributes: - input_config: - Required. Information about the input file. - features: - Required. Requested features. - image_context: - Additional context that may accompany the image(s) in the - file. - output_config: - Required. The desired output location and metadata - (e.g. format). - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.AsyncAnnotateFileRequest) - }, -) -_sym_db.RegisterMessage(AsyncAnnotateFileRequest) - -AsyncAnnotateFileResponse = _reflection.GeneratedProtocolMessageType( - "AsyncAnnotateFileResponse", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCANNOTATEFILERESPONSE, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """The response for a single offline file annotation request. - - Attributes: - output_config: - The output location and metadata from - AsyncAnnotateFileRequest. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.AsyncAnnotateFileResponse) - }, -) -_sym_db.RegisterMessage(AsyncAnnotateFileResponse) - -AsyncBatchAnnotateFilesRequest = _reflection.GeneratedProtocolMessageType( - "AsyncBatchAnnotateFilesRequest", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCBATCHANNOTATEFILESREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Multiple async file annotation requests are batched into a single - service call. - - Attributes: - requests: - Required. Individual async file annotation requests for this - batch. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.AsyncBatchAnnotateFilesRequest) - }, -) -_sym_db.RegisterMessage(AsyncBatchAnnotateFilesRequest) - -AsyncBatchAnnotateFilesResponse = _reflection.GeneratedProtocolMessageType( - "AsyncBatchAnnotateFilesResponse", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCBATCHANNOTATEFILESRESPONSE, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Response to an async batch file annotation request. - - Attributes: - responses: - The list of file annotation responses, one for each request in - AsyncBatchAnnotateFilesRequest. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.AsyncBatchAnnotateFilesResponse) - }, -) -_sym_db.RegisterMessage(AsyncBatchAnnotateFilesResponse) - -InputConfig = _reflection.GeneratedProtocolMessageType( - "InputConfig", - (_message.Message,), - { - "DESCRIPTOR": _INPUTCONFIG, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """The desired input location and metadata. - - Attributes: - gcs_source: - The Google Cloud Storage location to read the input from. - mime_type: - The type of the file. Currently only “application/pdf” and - “image/tiff” are supported. Wildcards are not supported. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.InputConfig) - }, -) -_sym_db.RegisterMessage(InputConfig) - -OutputConfig = _reflection.GeneratedProtocolMessageType( - "OutputConfig", - (_message.Message,), - { - "DESCRIPTOR": _OUTPUTCONFIG, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """The desired output location and metadata. - - Attributes: - gcs_destination: - The Google Cloud Storage location to write the output(s) to. - batch_size: - The max number of response protos to put into each output JSON - file on Google Cloud Storage. The valid range is [1, 100]. If - not specified, the default value is 20. For example, for one - pdf file with 100 pages, 100 response protos will be - generated. If ``batch_size`` = 20, then 5 json files each - containing 20 response protos will be written under the prefix - ``gcs_destination``.\ ``uri``. Currently, batch_size only - applies to GcsDestination, with potential future support for - other output configurations. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.OutputConfig) - }, -) -_sym_db.RegisterMessage(OutputConfig) - -GcsSource = _reflection.GeneratedProtocolMessageType( - "GcsSource", - (_message.Message,), - { - "DESCRIPTOR": _GCSSOURCE, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """The Google Cloud Storage location where the input will be read from. - - Attributes: - uri: - Google Cloud Storage URI for the input file. This must only be - a Google Cloud Storage object. Wildcards are not currently - supported. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.GcsSource) - }, -) -_sym_db.RegisterMessage(GcsSource) - -GcsDestination = _reflection.GeneratedProtocolMessageType( - "GcsDestination", - (_message.Message,), - { - "DESCRIPTOR": _GCSDESTINATION, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """The Google Cloud Storage location where the output will be written to. - - Attributes: - uri: - Google Cloud Storage URI where the results will be stored. - Results will be in JSON format and preceded by its - corresponding input URI. This field can either represent a - single file, or a prefix for multiple outputs. Prefixes must - end in a ``/``. Examples: - File: gs://bucket- - name/filename.json - Prefix: gs://bucket-name/prefix/here/ - - File: gs://bucket-name/prefix/here If multiple outputs, each - response is still AnnotateFileResponse, each of which contains - some subset of the full list of AnnotateImageResponse. - Multiple outputs can happen if, for example, the output JSON - is too large and overflows into multiple sharded files. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.GcsDestination) - }, -) -_sym_db.RegisterMessage(GcsDestination) - -OperationMetadata = _reflection.GeneratedProtocolMessageType( - "OperationMetadata", - (_message.Message,), - { - "DESCRIPTOR": _OPERATIONMETADATA, - "__module__": "google.cloud.vision_v1p3beta1.proto.image_annotator_pb2", - "__doc__": """Contains metadata for the BatchAnnotateImages operation. - - Attributes: - state: - Current state of the batch operation. - create_time: - The time when the batch request was received. - update_time: - The time when the operation result was last updated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.OperationMetadata) - }, -) -_sym_db.RegisterMessage(OperationMetadata) - - -DESCRIPTOR._options = None -_ASYNCBATCHANNOTATEFILESREQUEST.fields_by_name["requests"]._options = None - -_IMAGEANNOTATOR = _descriptor.ServiceDescriptor( - name="ImageAnnotator", - full_name="google.cloud.vision.v1p3beta1.ImageAnnotator", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\025vision.googleapis.com\322A[https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-vision", - create_key=_descriptor._internal_create_key, - serialized_start=7836, - serialized_end=8401, - methods=[ - _descriptor.MethodDescriptor( - name="BatchAnnotateImages", - full_name="google.cloud.vision.v1p3beta1.ImageAnnotator.BatchAnnotateImages", - index=0, - containing_service=None, - input_type=_BATCHANNOTATEIMAGESREQUEST, - output_type=_BATCHANNOTATEIMAGESRESPONSE, - serialized_options=b'\202\323\344\223\002\037"\032/v1p3beta1/images:annotate:\001*\332A\010requests', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="AsyncBatchAnnotateFiles", - full_name="google.cloud.vision.v1p3beta1.ImageAnnotator.AsyncBatchAnnotateFiles", - index=1, - containing_service=None, - input_type=_ASYNCBATCHANNOTATEFILESREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002("#/v1p3beta1/files:asyncBatchAnnotate:\001*\332A\010requests\312A4\n\037AsyncBatchAnnotateFilesResponse\022\021OperationMetadata', - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_IMAGEANNOTATOR) - -DESCRIPTOR.services_by_name["ImageAnnotator"] = _IMAGEANNOTATOR - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p3beta1/proto/image_annotator_pb2_grpc.py b/google/cloud/vision_v1p3beta1/proto/image_annotator_pb2_grpc.py deleted file mode 100644 index be9a511b..00000000 --- a/google/cloud/vision_v1p3beta1/proto/image_annotator_pb2_grpc.py +++ /dev/null @@ -1,141 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.vision_v1p3beta1.proto import ( - image_annotator_pb2 as google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_image__annotator__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) - - -class ImageAnnotatorStub(object): - """Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.BatchAnnotateImages = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ImageAnnotator/BatchAnnotateImages", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesResponse.FromString, - ) - self.AsyncBatchAnnotateFiles = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ImageAnnotator/AsyncBatchAnnotateFiles", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_image__annotator__pb2.AsyncBatchAnnotateFilesRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - - -class ImageAnnotatorServicer(object): - """Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - def BatchAnnotateImages(self, request, context): - """Run image detection and annotation for a batch of images. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def AsyncBatchAnnotateFiles(self, request, context): - """Run asynchronous image detection and annotation for a list of generic - files, such as PDF files, which may contain multiple pages and multiple - images per page. Progress and results can be retrieved through the - `google.longrunning.Operations` interface. - `Operation.metadata` contains `OperationMetadata` (metadata). - `Operation.response` contains `AsyncBatchAnnotateFilesResponse` (results). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_ImageAnnotatorServicer_to_server(servicer, server): - rpc_method_handlers = { - "BatchAnnotateImages": grpc.unary_unary_rpc_method_handler( - servicer.BatchAnnotateImages, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesResponse.SerializeToString, - ), - "AsyncBatchAnnotateFiles": grpc.unary_unary_rpc_method_handler( - servicer.AsyncBatchAnnotateFiles, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_image__annotator__pb2.AsyncBatchAnnotateFilesRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.vision.v1p3beta1.ImageAnnotator", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class ImageAnnotator(object): - """Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - @staticmethod - def BatchAnnotateImages( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ImageAnnotator/BatchAnnotateImages", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def AsyncBatchAnnotateFiles( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ImageAnnotator/AsyncBatchAnnotateFiles", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_image__annotator__pb2.AsyncBatchAnnotateFilesRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/vision_v1p3beta1/proto/product_search_pb2.py b/google/cloud/vision_v1p3beta1/proto/product_search_pb2.py deleted file mode 100644 index bcd2f545..00000000 --- a/google/cloud/vision_v1p3beta1/proto/product_search_pb2.py +++ /dev/null @@ -1,753 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p3beta1/proto/product_search.proto -"""Generated protocol buffer code.""" -from google.protobuf.internal import enum_type_wrapper -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.vision_v1p3beta1.proto import ( - geometry_pb2 as google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2, -) -from google.cloud.vision_v1p3beta1.proto import ( - product_search_service_pb2 as google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2, -) -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p3beta1/proto/product_search.proto", - package="google.cloud.vision.v1p3beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p3beta1B\022ProductSearchProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p3beta1;vision\370\001\001", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n8google/cloud/vision_v1p3beta1/proto/product_search.proto\x12\x1dgoogle.cloud.vision.v1p3beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x19google/api/resource.proto\x1a\x32google/cloud/vision_v1p3beta1/proto/geometry.proto\x1a@google/cloud/vision_v1p3beta1/proto/product_search_service.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xd9\x03\n\x13ProductSearchParams\x12\x14\n\x0c\x63\x61talog_name\x18\x01 \x01(\t\x12\x46\n\x08\x63\x61tegory\x18\x02 \x01(\x0e\x32\x34.google.cloud.vision.v1p3beta1.ProductSearchCategory\x12\x18\n\x10product_category\x18\x05 \x01(\t\x12W\n\x18normalized_bounding_poly\x18\x03 \x01(\x0b\x32\x35.google.cloud.vision.v1p3beta1.NormalizedBoundingPoly\x12\x42\n\rbounding_poly\x18\t \x01(\x0b\x32+.google.cloud.vision.v1p3beta1.BoundingPoly\x12\x45\n\x04view\x18\x04 \x01(\x0e\x32\x37.google.cloud.vision.v1p3beta1.ProductSearchResultsView\x12:\n\x0bproduct_set\x18\x06 \x01(\tB%\xfa\x41"\n vision.googleapis.com/ProductSet\x12\x1a\n\x12product_categories\x18\x07 \x03(\t\x12\x0e\n\x06\x66ilter\x18\x08 \x01(\t"\xee\x03\n\x14ProductSearchResults\x12\x46\n\x08\x63\x61tegory\x18\x01 \x01(\x0e\x32\x34.google.cloud.vision.v1p3beta1.ProductSearchCategory\x12\x18\n\x10product_category\x18\x04 \x01(\t\x12.\n\nindex_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12Q\n\x08products\x18\x03 \x03(\x0b\x32?.google.cloud.vision.v1p3beta1.ProductSearchResults.ProductInfo\x12K\n\x07results\x18\x05 \x03(\x0b\x32:.google.cloud.vision.v1p3beta1.ProductSearchResults.Result\x1a\x43\n\x0bProductInfo\x12\x12\n\nproduct_id\x18\x01 \x01(\t\x12\x11\n\timage_uri\x18\x02 \x01(\t\x12\r\n\x05score\x18\x03 \x01(\x02\x1a_\n\x06Result\x12\x37\n\x07product\x18\x01 \x01(\x0b\x32&.google.cloud.vision.v1p3beta1.Product\x12\r\n\x05score\x18\x02 \x01(\x02\x12\r\n\x05image\x18\x03 \x01(\t*U\n\x15ProductSearchCategory\x12\'\n#PRODUCT_SEARCH_CATEGORY_UNSPECIFIED\x10\x00\x12\t\n\x05SHOES\x10\x01\x12\x08\n\x04\x42\x41GS\x10\x02*/\n\x18ProductSearchResultsView\x12\t\n\x05\x42\x41SIC\x10\x00\x12\x08\n\x04\x46ULL\x10\x01\x42\x81\x01\n!com.google.cloud.vision.v1p3beta1B\x12ProductSearchProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p3beta1;vision\xf8\x01\x01\x62\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - -_PRODUCTSEARCHCATEGORY = _descriptor.EnumDescriptor( - name="ProductSearchCategory", - full_name="google.cloud.vision.v1p3beta1.ProductSearchCategory", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="PRODUCT_SEARCH_CATEGORY_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SHOES", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="BAGS", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=1272, - serialized_end=1357, -) -_sym_db.RegisterEnumDescriptor(_PRODUCTSEARCHCATEGORY) - -ProductSearchCategory = enum_type_wrapper.EnumTypeWrapper(_PRODUCTSEARCHCATEGORY) -_PRODUCTSEARCHRESULTSVIEW = _descriptor.EnumDescriptor( - name="ProductSearchResultsView", - full_name="google.cloud.vision.v1p3beta1.ProductSearchResultsView", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="BASIC", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FULL", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=1359, - serialized_end=1406, -) -_sym_db.RegisterEnumDescriptor(_PRODUCTSEARCHRESULTSVIEW) - -ProductSearchResultsView = enum_type_wrapper.EnumTypeWrapper(_PRODUCTSEARCHRESULTSVIEW) -PRODUCT_SEARCH_CATEGORY_UNSPECIFIED = 0 -SHOES = 1 -BAGS = 2 -BASIC = 0 -FULL = 1 - - -_PRODUCTSEARCHPARAMS = _descriptor.Descriptor( - name="ProductSearchParams", - full_name="google.cloud.vision.v1p3beta1.ProductSearchParams", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="catalog_name", - full_name="google.cloud.vision.v1p3beta1.ProductSearchParams.catalog_name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="category", - full_name="google.cloud.vision.v1p3beta1.ProductSearchParams.category", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_category", - full_name="google.cloud.vision.v1p3beta1.ProductSearchParams.product_category", - index=2, - number=5, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="normalized_bounding_poly", - full_name="google.cloud.vision.v1p3beta1.ProductSearchParams.normalized_bounding_poly", - index=3, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p3beta1.ProductSearchParams.bounding_poly", - index=4, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="view", - full_name="google.cloud.vision.v1p3beta1.ProductSearchParams.view", - index=5, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_set", - full_name="google.cloud.vision.v1p3beta1.ProductSearchParams.product_set", - index=6, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\372A"\n vision.googleapis.com/ProductSet', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_categories", - full_name="google.cloud.vision.v1p3beta1.ProductSearchParams.product_categories", - index=7, - number=7, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.vision.v1p3beta1.ProductSearchParams.filter", - index=8, - number=8, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=300, - serialized_end=773, -) - - -_PRODUCTSEARCHRESULTS_PRODUCTINFO = _descriptor.Descriptor( - name="ProductInfo", - full_name="google.cloud.vision.v1p3beta1.ProductSearchResults.ProductInfo", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="product_id", - full_name="google.cloud.vision.v1p3beta1.ProductSearchResults.ProductInfo.product_id", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_uri", - full_name="google.cloud.vision.v1p3beta1.ProductSearchResults.ProductInfo.image_uri", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p3beta1.ProductSearchResults.ProductInfo.score", - index=2, - number=3, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1106, - serialized_end=1173, -) - -_PRODUCTSEARCHRESULTS_RESULT = _descriptor.Descriptor( - name="Result", - full_name="google.cloud.vision.v1p3beta1.ProductSearchResults.Result", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="product", - full_name="google.cloud.vision.v1p3beta1.ProductSearchResults.Result.product", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p3beta1.ProductSearchResults.Result.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image", - full_name="google.cloud.vision.v1p3beta1.ProductSearchResults.Result.image", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1175, - serialized_end=1270, -) - -_PRODUCTSEARCHRESULTS = _descriptor.Descriptor( - name="ProductSearchResults", - full_name="google.cloud.vision.v1p3beta1.ProductSearchResults", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="category", - full_name="google.cloud.vision.v1p3beta1.ProductSearchResults.category", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_category", - full_name="google.cloud.vision.v1p3beta1.ProductSearchResults.product_category", - index=1, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="index_time", - full_name="google.cloud.vision.v1p3beta1.ProductSearchResults.index_time", - index=2, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="products", - full_name="google.cloud.vision.v1p3beta1.ProductSearchResults.products", - index=3, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="results", - full_name="google.cloud.vision.v1p3beta1.ProductSearchResults.results", - index=4, - number=5, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_PRODUCTSEARCHRESULTS_PRODUCTINFO, _PRODUCTSEARCHRESULTS_RESULT,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=776, - serialized_end=1270, -) - -_PRODUCTSEARCHPARAMS.fields_by_name["category"].enum_type = _PRODUCTSEARCHCATEGORY -_PRODUCTSEARCHPARAMS.fields_by_name[ - "normalized_bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2._NORMALIZEDBOUNDINGPOLY -) -_PRODUCTSEARCHPARAMS.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_PRODUCTSEARCHPARAMS.fields_by_name["view"].enum_type = _PRODUCTSEARCHRESULTSVIEW -_PRODUCTSEARCHRESULTS_PRODUCTINFO.containing_type = _PRODUCTSEARCHRESULTS -_PRODUCTSEARCHRESULTS_RESULT.fields_by_name[ - "product" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2._PRODUCT -) -_PRODUCTSEARCHRESULTS_RESULT.containing_type = _PRODUCTSEARCHRESULTS -_PRODUCTSEARCHRESULTS.fields_by_name["category"].enum_type = _PRODUCTSEARCHCATEGORY -_PRODUCTSEARCHRESULTS.fields_by_name[ - "index_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_PRODUCTSEARCHRESULTS.fields_by_name[ - "products" -].message_type = _PRODUCTSEARCHRESULTS_PRODUCTINFO -_PRODUCTSEARCHRESULTS.fields_by_name[ - "results" -].message_type = _PRODUCTSEARCHRESULTS_RESULT -DESCRIPTOR.message_types_by_name["ProductSearchParams"] = _PRODUCTSEARCHPARAMS -DESCRIPTOR.message_types_by_name["ProductSearchResults"] = _PRODUCTSEARCHRESULTS -DESCRIPTOR.enum_types_by_name["ProductSearchCategory"] = _PRODUCTSEARCHCATEGORY -DESCRIPTOR.enum_types_by_name["ProductSearchResultsView"] = _PRODUCTSEARCHRESULTSVIEW -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -ProductSearchParams = _reflection.GeneratedProtocolMessageType( - "ProductSearchParams", - (_message.Message,), - { - "DESCRIPTOR": _PRODUCTSEARCHPARAMS, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_pb2", - "__doc__": """Parameters for a product search request. - - Attributes: - catalog_name: - The resource name of the catalog to search. Format is: - ``productSearch/catalogs/CATALOG_NAME``. - category: - The category to search in. Optional. It is inferred by the - system if it is not specified. [Deprecated] Use - ``product_category``. - product_category: - The product category to search in. Optional. It is inferred by - the system if it is not specified. Supported values are - ``bag``, ``shoe``, ``sunglasses``, ``dress``, ``outerwear``, - ``skirt``, ``top``, ``shorts``, and ``pants``. - normalized_bounding_poly: - The bounding polygon around the area of interest in the image. - Optional. If it is not specified, system discretion will be - applied. [Deprecated] Use ``bounding_poly``. - bounding_poly: - The bounding polygon around the area of interest in the image. - Optional. If it is not specified, system discretion will be - applied. - view: - Specifies the verbosity of the product search results. - Optional. Defaults to ``BASIC``. - product_set: - The resource name of a - [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] to be - searched for similar images. Format is: ``projects/PROJECT_ID - /locations/LOC_ID/productSets/PRODUCT_SET_ID``. - product_categories: - The list of product categories to search in. Currently, we - only consider the first category, and either “homegoods” or - “apparel” should be specified. - filter: - The filtering expression. This can be used to restrict search - results based on Product labels. We currently support an AND - of OR of key-value expressions, where each expression within - an OR must have the same key. For example, “(color = red OR - color = blue) AND brand = Google” is acceptable, but not - “(color = red OR brand = Google)” or “color: red”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ProductSearchParams) - }, -) -_sym_db.RegisterMessage(ProductSearchParams) - -ProductSearchResults = _reflection.GeneratedProtocolMessageType( - "ProductSearchResults", - (_message.Message,), - { - "ProductInfo": _reflection.GeneratedProtocolMessageType( - "ProductInfo", - (_message.Message,), - { - "DESCRIPTOR": _PRODUCTSEARCHRESULTS_PRODUCTINFO, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_pb2", - "__doc__": """Information about a product. - - Attributes: - product_id: - Product ID. - image_uri: - The URI of the image which matched the query image. This - field is returned only if ``view`` is set to ``FULL`` in the - request. - score: - A confidence level on the match, ranging from 0 (no - confidence) to 1 (full confidence). This field is returned - only if ``view`` is set to ``FULL`` in the request. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ProductSearchResults.ProductInfo) - }, - ), - "Result": _reflection.GeneratedProtocolMessageType( - "Result", - (_message.Message,), - { - "DESCRIPTOR": _PRODUCTSEARCHRESULTS_RESULT, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_pb2", - "__doc__": """Information about a product. - - Attributes: - product: - The Product. - score: - A confidence level on the match, ranging from 0 (no - confidence) to 1 (full confidence). This field is returned - only if ``view`` is set to ``FULL`` in the request. - image: - The resource name of the image from the product that is the - closest match to the query. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ProductSearchResults.Result) - }, - ), - "DESCRIPTOR": _PRODUCTSEARCHRESULTS, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_pb2", - "__doc__": """Results for a product search request. - - Attributes: - category: - Product category. [Deprecated] Use ``product_category``. - product_category: - Product category. Supported values are ``bag`` and ``shoe``. - [Deprecated] ``product_category`` is provided in each Product. - index_time: - Timestamp of the index which provided these results. Changes - made after this time are not reflected in the current results. - products: - List of detected products. - results: - List of results, one for each product match. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ProductSearchResults) - }, -) -_sym_db.RegisterMessage(ProductSearchResults) -_sym_db.RegisterMessage(ProductSearchResults.ProductInfo) -_sym_db.RegisterMessage(ProductSearchResults.Result) - - -DESCRIPTOR._options = None -_PRODUCTSEARCHPARAMS.fields_by_name["product_set"]._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p3beta1/proto/product_search_pb2_grpc.py b/google/cloud/vision_v1p3beta1/proto/product_search_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/vision_v1p3beta1/proto/product_search_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/vision_v1p3beta1/proto/product_search_service_pb2.py b/google/cloud/vision_v1p3beta1/proto/product_search_service_pb2.py deleted file mode 100644 index a8bedab7..00000000 --- a/google/cloud/vision_v1p3beta1/proto/product_search_service_pb2.py +++ /dev/null @@ -1,3133 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p3beta1/proto/product_search_service.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.vision_v1p3beta1.proto import ( - geometry_pb2 as google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 -from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p3beta1/proto/product_search_service.proto", - package="google.cloud.vision.v1p3beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p3beta1B\031ProductSearchServiceProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p3beta1;vision\370\001\001", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n@google/cloud/vision_v1p3beta1/proto/product_search_service.proto\x12\x1dgoogle.cloud.vision.v1p3beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x32google/cloud/vision_v1p3beta1/proto/geometry.proto\x1a#google/longrunning/operations.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x17google/rpc/status.proto"\xb2\x02\n\x07Product\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\x12\x1d\n\x10product_category\x18\x04 \x01(\tB\x03\xe0\x41\x05\x12G\n\x0eproduct_labels\x18\x05 \x03(\x0b\x32/.google.cloud.vision.v1p3beta1.Product.KeyValue\x1a&\n\x08KeyValue\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:^\xea\x41[\n\x1dvision.googleapis.com/Product\x12:projects/{project}/locations/{location}/products/{product}"\xfd\x01\n\nProductSet\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x02 \x01(\t\x12\x33\n\nindex_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x03\x12,\n\x0bindex_error\x18\x04 \x01(\x0b\x32\x12.google.rpc.StatusB\x03\xe0\x41\x03:h\xea\x41\x65\n vision.googleapis.com/ProductSet\x12\x41projects/{project}/locations/{location}/productSets/{product_set}"\x85\x02\n\x0eReferenceImage\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x10\n\x03uri\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12H\n\x0e\x62ounding_polys\x18\x03 \x03(\x0b\x32+.google.cloud.vision.v1p3beta1.BoundingPolyB\x03\xe0\x41\x01:\x88\x01\xea\x41\x84\x01\n$vision.googleapis.com/ReferenceImage\x12\\projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}"\xa3\x01\n\x14\x43reateProductRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12<\n\x07product\x18\x02 \x01(\x0b\x32&.google.cloud.vision.v1p3beta1.ProductB\x03\xe0\x41\x02\x12\x12\n\nproduct_id\x18\x03 \x01(\t"w\n\x13ListProductsRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t"i\n\x14ListProductsResponse\x12\x38\n\x08products\x18\x01 \x03(\x0b\x32&.google.cloud.vision.v1p3beta1.Product\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"H\n\x11GetProductRequest\x12\x33\n\x04name\x18\x01 \x01(\tB%\xe0\x41\x02\xfa\x41\x1f\n\x1dvision.googleapis.com/Product"\x85\x01\n\x14UpdateProductRequest\x12<\n\x07product\x18\x01 \x01(\x0b\x32&.google.cloud.vision.v1p3beta1.ProductB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"K\n\x14\x44\x65leteProductRequest\x12\x33\n\x04name\x18\x01 \x01(\tB%\xe0\x41\x02\xfa\x41\x1f\n\x1dvision.googleapis.com/Product"\xb1\x01\n\x17\x43reateProductSetRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12\x43\n\x0bproduct_set\x18\x02 \x01(\x0b\x32).google.cloud.vision.v1p3beta1.ProductSetB\x03\xe0\x41\x02\x12\x16\n\x0eproduct_set_id\x18\x03 \x01(\t"z\n\x16ListProductSetsRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t"s\n\x17ListProductSetsResponse\x12?\n\x0cproduct_sets\x18\x01 \x03(\x0b\x32).google.cloud.vision.v1p3beta1.ProductSet\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"N\n\x14GetProductSetRequest\x12\x36\n\x04name\x18\x01 \x01(\tB(\xe0\x41\x02\xfa\x41"\n vision.googleapis.com/ProductSet"\x8f\x01\n\x17UpdateProductSetRequest\x12\x43\n\x0bproduct_set\x18\x01 \x01(\x0b\x32).google.cloud.vision.v1p3beta1.ProductSetB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"Q\n\x17\x44\x65leteProductSetRequest\x12\x36\n\x04name\x18\x01 \x01(\tB(\xe0\x41\x02\xfa\x41"\n vision.googleapis.com/ProductSet"\xbd\x01\n\x1b\x43reateReferenceImageRequest\x12\x35\n\x06parent\x18\x01 \x01(\tB%\xe0\x41\x02\xfa\x41\x1f\n\x1dvision.googleapis.com/Product\x12K\n\x0freference_image\x18\x02 \x01(\x0b\x32-.google.cloud.vision.v1p3beta1.ReferenceImageB\x03\xe0\x41\x02\x12\x1a\n\x12reference_image_id\x18\x03 \x01(\t"z\n\x1aListReferenceImagesRequest\x12\x35\n\x06parent\x18\x01 \x01(\tB%\xe0\x41\x02\xfa\x41\x1f\n\x1dvision.googleapis.com/Product\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t"\x92\x01\n\x1bListReferenceImagesResponse\x12G\n\x10reference_images\x18\x01 \x03(\x0b\x32-.google.cloud.vision.v1p3beta1.ReferenceImage\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t"V\n\x18GetReferenceImageRequest\x12:\n\x04name\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$vision.googleapis.com/ReferenceImage"Y\n\x1b\x44\x65leteReferenceImageRequest\x12:\n\x04name\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$vision.googleapis.com/ReferenceImage"\x8f\x01\n\x1d\x41\x64\x64ProductToProductSetRequest\x12\x36\n\x04name\x18\x01 \x01(\tB(\xe0\x41\x02\xfa\x41"\n vision.googleapis.com/ProductSet\x12\x36\n\x07product\x18\x02 \x01(\tB%\xe0\x41\x02\xfa\x41\x1f\n\x1dvision.googleapis.com/Product"\x94\x01\n"RemoveProductFromProductSetRequest\x12\x36\n\x04name\x18\x01 \x01(\tB(\xe0\x41\x02\xfa\x41"\n vision.googleapis.com/ProductSet\x12\x36\n\x07product\x18\x02 \x01(\tB%\xe0\x41\x02\xfa\x41\x1f\n\x1dvision.googleapis.com/Product"\x80\x01\n\x1fListProductsInProductSetRequest\x12\x36\n\x04name\x18\x01 \x01(\tB(\xe0\x41\x02\xfa\x41"\n vision.googleapis.com/ProductSet\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t"u\n ListProductsInProductSetResponse\x12\x38\n\x08products\x18\x01 \x03(\x0b\x32&.google.cloud.vision.v1p3beta1.Product\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"2\n\x1aImportProductSetsGcsSource\x12\x14\n\x0c\x63sv_file_uri\x18\x01 \x01(\t"y\n\x1cImportProductSetsInputConfig\x12O\n\ngcs_source\x18\x01 \x01(\x0b\x32\x39.google.cloud.vision.v1p3beta1.ImportProductSetsGcsSourceH\x00\x42\x08\n\x06source"\xad\x01\n\x18ImportProductSetsRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12V\n\x0cinput_config\x18\x02 \x01(\x0b\x32;.google.cloud.vision.v1p3beta1.ImportProductSetsInputConfigB\x03\xe0\x41\x02"\x8a\x01\n\x19ImportProductSetsResponse\x12G\n\x10reference_images\x18\x01 \x03(\x0b\x32-.google.cloud.vision.v1p3beta1.ReferenceImage\x12$\n\x08statuses\x18\x02 \x03(\x0b\x32\x12.google.rpc.Status"\x9e\x02\n\x16\x42\x61tchOperationMetadata\x12J\n\x05state\x18\x01 \x01(\x0e\x32;.google.cloud.vision.v1p3beta1.BatchOperationMetadata.State\x12/\n\x0bsubmit_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x08\x65nd_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"Y\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0e\n\nPROCESSING\x10\x01\x12\x0e\n\nSUCCESSFUL\x10\x02\x12\n\n\x06\x46\x41ILED\x10\x03\x12\r\n\tCANCELLED\x10\x04\x32\xeb\x1e\n\rProductSearch\x12\xe6\x01\n\x10\x43reateProductSet\x12\x36.google.cloud.vision.v1p3beta1.CreateProductSetRequest\x1a).google.cloud.vision.v1p3beta1.ProductSet"o\x82\xd3\xe4\x93\x02\x45"6/v1p3beta1/{parent=projects/*/locations/*}/productSets:\x0bproduct_set\xda\x41!parent,product_set,product_set_id\x12\xc9\x01\n\x0fListProductSets\x12\x35.google.cloud.vision.v1p3beta1.ListProductSetsRequest\x1a\x36.google.cloud.vision.v1p3beta1.ListProductSetsResponse"G\x82\xd3\xe4\x93\x02\x38\x12\x36/v1p3beta1/{parent=projects/*/locations/*}/productSets\xda\x41\x06parent\x12\xb6\x01\n\rGetProductSet\x12\x33.google.cloud.vision.v1p3beta1.GetProductSetRequest\x1a).google.cloud.vision.v1p3beta1.ProductSet"E\x82\xd3\xe4\x93\x02\x38\x12\x36/v1p3beta1/{name=projects/*/locations/*/productSets/*}\xda\x41\x04name\x12\xe8\x01\n\x10UpdateProductSet\x12\x36.google.cloud.vision.v1p3beta1.UpdateProductSetRequest\x1a).google.cloud.vision.v1p3beta1.ProductSet"q\x82\xd3\xe4\x93\x02Q2B/v1p3beta1/{product_set.name=projects/*/locations/*/productSets/*}:\x0bproduct_set\xda\x41\x17product_set,update_mask\x12\xa9\x01\n\x10\x44\x65leteProductSet\x12\x36.google.cloud.vision.v1p3beta1.DeleteProductSetRequest\x1a\x16.google.protobuf.Empty"E\x82\xd3\xe4\x93\x02\x38*6/v1p3beta1/{name=projects/*/locations/*/productSets/*}\xda\x41\x04name\x12\xce\x01\n\rCreateProduct\x12\x33.google.cloud.vision.v1p3beta1.CreateProductRequest\x1a&.google.cloud.vision.v1p3beta1.Product"`\x82\xd3\xe4\x93\x02>"3/v1p3beta1/{parent=projects/*/locations/*}/products:\x07product\xda\x41\x19parent,product,product_id\x12\xbd\x01\n\x0cListProducts\x12\x32.google.cloud.vision.v1p3beta1.ListProductsRequest\x1a\x33.google.cloud.vision.v1p3beta1.ListProductsResponse"D\x82\xd3\xe4\x93\x02\x35\x12\x33/v1p3beta1/{parent=projects/*/locations/*}/products\xda\x41\x06parent\x12\xaa\x01\n\nGetProduct\x12\x30.google.cloud.vision.v1p3beta1.GetProductRequest\x1a&.google.cloud.vision.v1p3beta1.Product"B\x82\xd3\xe4\x93\x02\x35\x12\x33/v1p3beta1/{name=projects/*/locations/*/products/*}\xda\x41\x04name\x12\xd0\x01\n\rUpdateProduct\x12\x33.google.cloud.vision.v1p3beta1.UpdateProductRequest\x1a&.google.cloud.vision.v1p3beta1.Product"b\x82\xd3\xe4\x93\x02\x46\x32;/v1p3beta1/{product.name=projects/*/locations/*/products/*}:\x07product\xda\x41\x13product,update_mask\x12\xa0\x01\n\rDeleteProduct\x12\x33.google.cloud.vision.v1p3beta1.DeleteProductRequest\x1a\x16.google.protobuf.Empty"B\x82\xd3\xe4\x93\x02\x35*3/v1p3beta1/{name=projects/*/locations/*/products/*}\xda\x41\x04name\x12\x8e\x02\n\x14\x43reateReferenceImage\x12:.google.cloud.vision.v1p3beta1.CreateReferenceImageRequest\x1a-.google.cloud.vision.v1p3beta1.ReferenceImage"\x8a\x01\x82\xd3\xe4\x93\x02X"E/v1p3beta1/{parent=projects/*/locations/*/products/*}/referenceImages:\x0freference_image\xda\x41)parent,reference_image,reference_image_id\x12\xc0\x01\n\x14\x44\x65leteReferenceImage\x12:.google.cloud.vision.v1p3beta1.DeleteReferenceImageRequest\x1a\x16.google.protobuf.Empty"T\x82\xd3\xe4\x93\x02G*E/v1p3beta1/{name=projects/*/locations/*/products/*/referenceImages/*}\xda\x41\x04name\x12\xe4\x01\n\x13ListReferenceImages\x12\x39.google.cloud.vision.v1p3beta1.ListReferenceImagesRequest\x1a:.google.cloud.vision.v1p3beta1.ListReferenceImagesResponse"V\x82\xd3\xe4\x93\x02G\x12\x45/v1p3beta1/{parent=projects/*/locations/*/products/*}/referenceImages\xda\x41\x06parent\x12\xd1\x01\n\x11GetReferenceImage\x12\x37.google.cloud.vision.v1p3beta1.GetReferenceImageRequest\x1a-.google.cloud.vision.v1p3beta1.ReferenceImage"T\x82\xd3\xe4\x93\x02G\x12\x45/v1p3beta1/{name=projects/*/locations/*/products/*/referenceImages/*}\xda\x41\x04name\x12\xcb\x01\n\x16\x41\x64\x64ProductToProductSet\x12<.google.cloud.vision.v1p3beta1.AddProductToProductSetRequest\x1a\x16.google.protobuf.Empty"[\x82\xd3\xe4\x93\x02\x46"A/v1p3beta1/{name=projects/*/locations/*/productSets/*}:addProduct:\x01*\xda\x41\x0cname,product\x12\xd8\x01\n\x1bRemoveProductFromProductSet\x12\x41.google.cloud.vision.v1p3beta1.RemoveProductFromProductSetRequest\x1a\x16.google.protobuf.Empty"^\x82\xd3\xe4\x93\x02I"D/v1p3beta1/{name=projects/*/locations/*/productSets/*}:removeProduct:\x01*\xda\x41\x0cname,product\x12\xeb\x01\n\x18ListProductsInProductSet\x12>.google.cloud.vision.v1p3beta1.ListProductsInProductSetRequest\x1a?.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse"N\x82\xd3\xe4\x93\x02\x41\x12?/v1p3beta1/{name=projects/*/locations/*/productSets/*}/products\xda\x41\x04name\x12\x82\x02\n\x11ImportProductSets\x12\x37.google.cloud.vision.v1p3beta1.ImportProductSetsRequest\x1a\x1d.google.longrunning.Operation"\x94\x01\x82\xd3\xe4\x93\x02\x42"=/v1p3beta1/{parent=projects/*/locations/*}/productSets:import:\x01*\xda\x41\x13parent,input_config\xca\x41\x33\n\x19ImportProductSetsResponse\x12\x16\x42\x61tchOperationMetadata\x1av\xca\x41\x15vision.googleapis.com\xd2\x41[https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-visionB\x88\x01\n!com.google.cloud.vision.v1p3beta1B\x19ProductSearchServiceProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p3beta1;vision\xf8\x01\x01\x62\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2.DESCRIPTOR, - google_dot_longrunning_dot_operations__pb2.DESCRIPTOR, - google_dot_protobuf_dot_empty__pb2.DESCRIPTOR, - google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_rpc_dot_status__pb2.DESCRIPTOR, - ], -) - - -_BATCHOPERATIONMETADATA_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.vision.v1p3beta1.BatchOperationMetadata.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="PROCESSING", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SUCCESSFUL", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FAILED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLED", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=4545, - serialized_end=4634, -) -_sym_db.RegisterEnumDescriptor(_BATCHOPERATIONMETADATA_STATE) - - -_PRODUCT_KEYVALUE = _descriptor.Descriptor( - name="KeyValue", - full_name="google.cloud.vision.v1p3beta1.Product.KeyValue", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.vision.v1p3beta1.Product.KeyValue.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.vision.v1p3beta1.Product.KeyValue.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=597, - serialized_end=635, -) - -_PRODUCT = _descriptor.Descriptor( - name="Product", - full_name="google.cloud.vision.v1p3beta1.Product", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p3beta1.Product.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="display_name", - full_name="google.cloud.vision.v1p3beta1.Product.display_name", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.vision.v1p3beta1.Product.description", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_category", - full_name="google.cloud.vision.v1p3beta1.Product.product_category", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\005", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_labels", - full_name="google.cloud.vision.v1p3beta1.Product.product_labels", - index=4, - number=5, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_PRODUCT_KEYVALUE,], - enum_types=[], - serialized_options=b"\352A[\n\035vision.googleapis.com/Product\022:projects/{project}/locations/{location}/products/{product}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=425, - serialized_end=731, -) - - -_PRODUCTSET = _descriptor.Descriptor( - name="ProductSet", - full_name="google.cloud.vision.v1p3beta1.ProductSet", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p3beta1.ProductSet.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="display_name", - full_name="google.cloud.vision.v1p3beta1.ProductSet.display_name", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="index_time", - full_name="google.cloud.vision.v1p3beta1.ProductSet.index_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="index_error", - full_name="google.cloud.vision.v1p3beta1.ProductSet.index_error", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"\352Ae\n vision.googleapis.com/ProductSet\022Aprojects/{project}/locations/{location}/productSets/{product_set}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=734, - serialized_end=987, -) - - -_REFERENCEIMAGE = _descriptor.Descriptor( - name="ReferenceImage", - full_name="google.cloud.vision.v1p3beta1.ReferenceImage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p3beta1.ReferenceImage.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="uri", - full_name="google.cloud.vision.v1p3beta1.ReferenceImage.uri", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_polys", - full_name="google.cloud.vision.v1p3beta1.ReferenceImage.bounding_polys", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"\352A\204\001\n$vision.googleapis.com/ReferenceImage\022\\projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=990, - serialized_end=1251, -) - - -_CREATEPRODUCTREQUEST = _descriptor.Descriptor( - name="CreateProductRequest", - full_name="google.cloud.vision.v1p3beta1.CreateProductRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.vision.v1p3beta1.CreateProductRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product", - full_name="google.cloud.vision.v1p3beta1.CreateProductRequest.product", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_id", - full_name="google.cloud.vision.v1p3beta1.CreateProductRequest.product_id", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1254, - serialized_end=1417, -) - - -_LISTPRODUCTSREQUEST = _descriptor.Descriptor( - name="ListProductsRequest", - full_name="google.cloud.vision.v1p3beta1.ListProductsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.vision.v1p3beta1.ListProductsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.vision.v1p3beta1.ListProductsRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.vision.v1p3beta1.ListProductsRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1419, - serialized_end=1538, -) - - -_LISTPRODUCTSRESPONSE = _descriptor.Descriptor( - name="ListProductsResponse", - full_name="google.cloud.vision.v1p3beta1.ListProductsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="products", - full_name="google.cloud.vision.v1p3beta1.ListProductsResponse.products", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.vision.v1p3beta1.ListProductsResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1540, - serialized_end=1645, -) - - -_GETPRODUCTREQUEST = _descriptor.Descriptor( - name="GetProductRequest", - full_name="google.cloud.vision.v1p3beta1.GetProductRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p3beta1.GetProductRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A\037\n\035vision.googleapis.com/Product", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1647, - serialized_end=1719, -) - - -_UPDATEPRODUCTREQUEST = _descriptor.Descriptor( - name="UpdateProductRequest", - full_name="google.cloud.vision.v1p3beta1.UpdateProductRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="product", - full_name="google.cloud.vision.v1p3beta1.UpdateProductRequest.product", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.vision.v1p3beta1.UpdateProductRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1722, - serialized_end=1855, -) - - -_DELETEPRODUCTREQUEST = _descriptor.Descriptor( - name="DeleteProductRequest", - full_name="google.cloud.vision.v1p3beta1.DeleteProductRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p3beta1.DeleteProductRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A\037\n\035vision.googleapis.com/Product", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1857, - serialized_end=1932, -) - - -_CREATEPRODUCTSETREQUEST = _descriptor.Descriptor( - name="CreateProductSetRequest", - full_name="google.cloud.vision.v1p3beta1.CreateProductSetRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.vision.v1p3beta1.CreateProductSetRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_set", - full_name="google.cloud.vision.v1p3beta1.CreateProductSetRequest.product_set", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_set_id", - full_name="google.cloud.vision.v1p3beta1.CreateProductSetRequest.product_set_id", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1935, - serialized_end=2112, -) - - -_LISTPRODUCTSETSREQUEST = _descriptor.Descriptor( - name="ListProductSetsRequest", - full_name="google.cloud.vision.v1p3beta1.ListProductSetsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.vision.v1p3beta1.ListProductSetsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.vision.v1p3beta1.ListProductSetsRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.vision.v1p3beta1.ListProductSetsRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2114, - serialized_end=2236, -) - - -_LISTPRODUCTSETSRESPONSE = _descriptor.Descriptor( - name="ListProductSetsResponse", - full_name="google.cloud.vision.v1p3beta1.ListProductSetsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="product_sets", - full_name="google.cloud.vision.v1p3beta1.ListProductSetsResponse.product_sets", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.vision.v1p3beta1.ListProductSetsResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2238, - serialized_end=2353, -) - - -_GETPRODUCTSETREQUEST = _descriptor.Descriptor( - name="GetProductSetRequest", - full_name="google.cloud.vision.v1p3beta1.GetProductSetRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p3beta1.GetProductSetRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A"\n vision.googleapis.com/ProductSet', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2355, - serialized_end=2433, -) - - -_UPDATEPRODUCTSETREQUEST = _descriptor.Descriptor( - name="UpdateProductSetRequest", - full_name="google.cloud.vision.v1p3beta1.UpdateProductSetRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="product_set", - full_name="google.cloud.vision.v1p3beta1.UpdateProductSetRequest.product_set", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.vision.v1p3beta1.UpdateProductSetRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2436, - serialized_end=2579, -) - - -_DELETEPRODUCTSETREQUEST = _descriptor.Descriptor( - name="DeleteProductSetRequest", - full_name="google.cloud.vision.v1p3beta1.DeleteProductSetRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p3beta1.DeleteProductSetRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A"\n vision.googleapis.com/ProductSet', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2581, - serialized_end=2662, -) - - -_CREATEREFERENCEIMAGEREQUEST = _descriptor.Descriptor( - name="CreateReferenceImageRequest", - full_name="google.cloud.vision.v1p3beta1.CreateReferenceImageRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.vision.v1p3beta1.CreateReferenceImageRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A\037\n\035vision.googleapis.com/Product", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="reference_image", - full_name="google.cloud.vision.v1p3beta1.CreateReferenceImageRequest.reference_image", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="reference_image_id", - full_name="google.cloud.vision.v1p3beta1.CreateReferenceImageRequest.reference_image_id", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2665, - serialized_end=2854, -) - - -_LISTREFERENCEIMAGESREQUEST = _descriptor.Descriptor( - name="ListReferenceImagesRequest", - full_name="google.cloud.vision.v1p3beta1.ListReferenceImagesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.vision.v1p3beta1.ListReferenceImagesRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A\037\n\035vision.googleapis.com/Product", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.vision.v1p3beta1.ListReferenceImagesRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.vision.v1p3beta1.ListReferenceImagesRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2856, - serialized_end=2978, -) - - -_LISTREFERENCEIMAGESRESPONSE = _descriptor.Descriptor( - name="ListReferenceImagesResponse", - full_name="google.cloud.vision.v1p3beta1.ListReferenceImagesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="reference_images", - full_name="google.cloud.vision.v1p3beta1.ListReferenceImagesResponse.reference_images", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.vision.v1p3beta1.ListReferenceImagesResponse.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.vision.v1p3beta1.ListReferenceImagesResponse.next_page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2981, - serialized_end=3127, -) - - -_GETREFERENCEIMAGEREQUEST = _descriptor.Descriptor( - name="GetReferenceImageRequest", - full_name="google.cloud.vision.v1p3beta1.GetReferenceImageRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p3beta1.GetReferenceImageRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A&\n$vision.googleapis.com/ReferenceImage", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3129, - serialized_end=3215, -) - - -_DELETEREFERENCEIMAGEREQUEST = _descriptor.Descriptor( - name="DeleteReferenceImageRequest", - full_name="google.cloud.vision.v1p3beta1.DeleteReferenceImageRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p3beta1.DeleteReferenceImageRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A&\n$vision.googleapis.com/ReferenceImage", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3217, - serialized_end=3306, -) - - -_ADDPRODUCTTOPRODUCTSETREQUEST = _descriptor.Descriptor( - name="AddProductToProductSetRequest", - full_name="google.cloud.vision.v1p3beta1.AddProductToProductSetRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p3beta1.AddProductToProductSetRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A"\n vision.googleapis.com/ProductSet', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product", - full_name="google.cloud.vision.v1p3beta1.AddProductToProductSetRequest.product", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A\037\n\035vision.googleapis.com/Product", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3309, - serialized_end=3452, -) - - -_REMOVEPRODUCTFROMPRODUCTSETREQUEST = _descriptor.Descriptor( - name="RemoveProductFromProductSetRequest", - full_name="google.cloud.vision.v1p3beta1.RemoveProductFromProductSetRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p3beta1.RemoveProductFromProductSetRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A"\n vision.googleapis.com/ProductSet', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product", - full_name="google.cloud.vision.v1p3beta1.RemoveProductFromProductSetRequest.product", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A\037\n\035vision.googleapis.com/Product", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3455, - serialized_end=3603, -) - - -_LISTPRODUCTSINPRODUCTSETREQUEST = _descriptor.Descriptor( - name="ListProductsInProductSetRequest", - full_name="google.cloud.vision.v1p3beta1.ListProductsInProductSetRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p3beta1.ListProductsInProductSetRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A"\n vision.googleapis.com/ProductSet', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.vision.v1p3beta1.ListProductsInProductSetRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.vision.v1p3beta1.ListProductsInProductSetRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3606, - serialized_end=3734, -) - - -_LISTPRODUCTSINPRODUCTSETRESPONSE = _descriptor.Descriptor( - name="ListProductsInProductSetResponse", - full_name="google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="products", - full_name="google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse.products", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3736, - serialized_end=3853, -) - - -_IMPORTPRODUCTSETSGCSSOURCE = _descriptor.Descriptor( - name="ImportProductSetsGcsSource", - full_name="google.cloud.vision.v1p3beta1.ImportProductSetsGcsSource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="csv_file_uri", - full_name="google.cloud.vision.v1p3beta1.ImportProductSetsGcsSource.csv_file_uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3855, - serialized_end=3905, -) - - -_IMPORTPRODUCTSETSINPUTCONFIG = _descriptor.Descriptor( - name="ImportProductSetsInputConfig", - full_name="google.cloud.vision.v1p3beta1.ImportProductSetsInputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_source", - full_name="google.cloud.vision.v1p3beta1.ImportProductSetsInputConfig.gcs_source", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="source", - full_name="google.cloud.vision.v1p3beta1.ImportProductSetsInputConfig.source", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=3907, - serialized_end=4028, -) - - -_IMPORTPRODUCTSETSREQUEST = _descriptor.Descriptor( - name="ImportProductSetsRequest", - full_name="google.cloud.vision.v1p3beta1.ImportProductSetsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.vision.v1p3beta1.ImportProductSetsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="input_config", - full_name="google.cloud.vision.v1p3beta1.ImportProductSetsRequest.input_config", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4031, - serialized_end=4204, -) - - -_IMPORTPRODUCTSETSRESPONSE = _descriptor.Descriptor( - name="ImportProductSetsResponse", - full_name="google.cloud.vision.v1p3beta1.ImportProductSetsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="reference_images", - full_name="google.cloud.vision.v1p3beta1.ImportProductSetsResponse.reference_images", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="statuses", - full_name="google.cloud.vision.v1p3beta1.ImportProductSetsResponse.statuses", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4207, - serialized_end=4345, -) - - -_BATCHOPERATIONMETADATA = _descriptor.Descriptor( - name="BatchOperationMetadata", - full_name="google.cloud.vision.v1p3beta1.BatchOperationMetadata", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.vision.v1p3beta1.BatchOperationMetadata.state", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="submit_time", - full_name="google.cloud.vision.v1p3beta1.BatchOperationMetadata.submit_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="end_time", - full_name="google.cloud.vision.v1p3beta1.BatchOperationMetadata.end_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_BATCHOPERATIONMETADATA_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4348, - serialized_end=4634, -) - -_PRODUCT_KEYVALUE.containing_type = _PRODUCT -_PRODUCT.fields_by_name["product_labels"].message_type = _PRODUCT_KEYVALUE -_PRODUCTSET.fields_by_name[ - "index_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_PRODUCTSET.fields_by_name[ - "index_error" -].message_type = google_dot_rpc_dot_status__pb2._STATUS -_REFERENCEIMAGE.fields_by_name[ - "bounding_polys" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_CREATEPRODUCTREQUEST.fields_by_name["product"].message_type = _PRODUCT -_LISTPRODUCTSRESPONSE.fields_by_name["products"].message_type = _PRODUCT -_UPDATEPRODUCTREQUEST.fields_by_name["product"].message_type = _PRODUCT -_UPDATEPRODUCTREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_CREATEPRODUCTSETREQUEST.fields_by_name["product_set"].message_type = _PRODUCTSET -_LISTPRODUCTSETSRESPONSE.fields_by_name["product_sets"].message_type = _PRODUCTSET -_UPDATEPRODUCTSETREQUEST.fields_by_name["product_set"].message_type = _PRODUCTSET -_UPDATEPRODUCTSETREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_CREATEREFERENCEIMAGEREQUEST.fields_by_name[ - "reference_image" -].message_type = _REFERENCEIMAGE -_LISTREFERENCEIMAGESRESPONSE.fields_by_name[ - "reference_images" -].message_type = _REFERENCEIMAGE -_LISTPRODUCTSINPRODUCTSETRESPONSE.fields_by_name["products"].message_type = _PRODUCT -_IMPORTPRODUCTSETSINPUTCONFIG.fields_by_name[ - "gcs_source" -].message_type = _IMPORTPRODUCTSETSGCSSOURCE -_IMPORTPRODUCTSETSINPUTCONFIG.oneofs_by_name["source"].fields.append( - _IMPORTPRODUCTSETSINPUTCONFIG.fields_by_name["gcs_source"] -) -_IMPORTPRODUCTSETSINPUTCONFIG.fields_by_name[ - "gcs_source" -].containing_oneof = _IMPORTPRODUCTSETSINPUTCONFIG.oneofs_by_name["source"] -_IMPORTPRODUCTSETSREQUEST.fields_by_name[ - "input_config" -].message_type = _IMPORTPRODUCTSETSINPUTCONFIG -_IMPORTPRODUCTSETSRESPONSE.fields_by_name[ - "reference_images" -].message_type = _REFERENCEIMAGE -_IMPORTPRODUCTSETSRESPONSE.fields_by_name[ - "statuses" -].message_type = google_dot_rpc_dot_status__pb2._STATUS -_BATCHOPERATIONMETADATA.fields_by_name[ - "state" -].enum_type = _BATCHOPERATIONMETADATA_STATE -_BATCHOPERATIONMETADATA.fields_by_name[ - "submit_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_BATCHOPERATIONMETADATA.fields_by_name[ - "end_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_BATCHOPERATIONMETADATA_STATE.containing_type = _BATCHOPERATIONMETADATA -DESCRIPTOR.message_types_by_name["Product"] = _PRODUCT -DESCRIPTOR.message_types_by_name["ProductSet"] = _PRODUCTSET -DESCRIPTOR.message_types_by_name["ReferenceImage"] = _REFERENCEIMAGE -DESCRIPTOR.message_types_by_name["CreateProductRequest"] = _CREATEPRODUCTREQUEST -DESCRIPTOR.message_types_by_name["ListProductsRequest"] = _LISTPRODUCTSREQUEST -DESCRIPTOR.message_types_by_name["ListProductsResponse"] = _LISTPRODUCTSRESPONSE -DESCRIPTOR.message_types_by_name["GetProductRequest"] = _GETPRODUCTREQUEST -DESCRIPTOR.message_types_by_name["UpdateProductRequest"] = _UPDATEPRODUCTREQUEST -DESCRIPTOR.message_types_by_name["DeleteProductRequest"] = _DELETEPRODUCTREQUEST -DESCRIPTOR.message_types_by_name["CreateProductSetRequest"] = _CREATEPRODUCTSETREQUEST -DESCRIPTOR.message_types_by_name["ListProductSetsRequest"] = _LISTPRODUCTSETSREQUEST -DESCRIPTOR.message_types_by_name["ListProductSetsResponse"] = _LISTPRODUCTSETSRESPONSE -DESCRIPTOR.message_types_by_name["GetProductSetRequest"] = _GETPRODUCTSETREQUEST -DESCRIPTOR.message_types_by_name["UpdateProductSetRequest"] = _UPDATEPRODUCTSETREQUEST -DESCRIPTOR.message_types_by_name["DeleteProductSetRequest"] = _DELETEPRODUCTSETREQUEST -DESCRIPTOR.message_types_by_name[ - "CreateReferenceImageRequest" -] = _CREATEREFERENCEIMAGEREQUEST -DESCRIPTOR.message_types_by_name[ - "ListReferenceImagesRequest" -] = _LISTREFERENCEIMAGESREQUEST -DESCRIPTOR.message_types_by_name[ - "ListReferenceImagesResponse" -] = _LISTREFERENCEIMAGESRESPONSE -DESCRIPTOR.message_types_by_name["GetReferenceImageRequest"] = _GETREFERENCEIMAGEREQUEST -DESCRIPTOR.message_types_by_name[ - "DeleteReferenceImageRequest" -] = _DELETEREFERENCEIMAGEREQUEST -DESCRIPTOR.message_types_by_name[ - "AddProductToProductSetRequest" -] = _ADDPRODUCTTOPRODUCTSETREQUEST -DESCRIPTOR.message_types_by_name[ - "RemoveProductFromProductSetRequest" -] = _REMOVEPRODUCTFROMPRODUCTSETREQUEST -DESCRIPTOR.message_types_by_name[ - "ListProductsInProductSetRequest" -] = _LISTPRODUCTSINPRODUCTSETREQUEST -DESCRIPTOR.message_types_by_name[ - "ListProductsInProductSetResponse" -] = _LISTPRODUCTSINPRODUCTSETRESPONSE -DESCRIPTOR.message_types_by_name[ - "ImportProductSetsGcsSource" -] = _IMPORTPRODUCTSETSGCSSOURCE -DESCRIPTOR.message_types_by_name[ - "ImportProductSetsInputConfig" -] = _IMPORTPRODUCTSETSINPUTCONFIG -DESCRIPTOR.message_types_by_name["ImportProductSetsRequest"] = _IMPORTPRODUCTSETSREQUEST -DESCRIPTOR.message_types_by_name[ - "ImportProductSetsResponse" -] = _IMPORTPRODUCTSETSRESPONSE -DESCRIPTOR.message_types_by_name["BatchOperationMetadata"] = _BATCHOPERATIONMETADATA -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Product = _reflection.GeneratedProtocolMessageType( - "Product", - (_message.Message,), - { - "KeyValue": _reflection.GeneratedProtocolMessageType( - "KeyValue", - (_message.Message,), - { - "DESCRIPTOR": _PRODUCT_KEYVALUE, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """A product label represented as a key-value pair. - - Attributes: - key: - The key of the label attached to the product. Cannot be empty - and cannot exceed 128 bytes. - value: - The value of the label attached to the product. Cannot be - empty and cannot exceed 128 bytes. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.Product.KeyValue) - }, - ), - "DESCRIPTOR": _PRODUCT, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """A Product contains ReferenceImages. - - Attributes: - name: - The resource name of the product. Format is: - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. - This field is ignored when creating a product. - display_name: - The user-provided name for this Product. Must not be empty. - Must be at most 4096 characters long. - description: - User-provided metadata to be stored with this product. Must be - at most 4096 characters long. - product_category: - Immutable. The category for the product identified by the - reference image. This should be either “homegoods-v2”, - “apparel-v2”, or “toys-v2”. The legacy categories “homegoods”, - “apparel”, and “toys” are still supported, but these should - not be used for new products. - product_labels: - Key-value pairs that can be attached to a product. At query - time, constraints can be specified based on the - product_labels. Note that integer values can be provided as - strings, e.g. “1199”. Only strings with integer values can - match a range-based restriction which is to be supported soon. - Multiple values can be assigned to the same key. One product - may have up to 100 product_labels. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.Product) - }, -) -_sym_db.RegisterMessage(Product) -_sym_db.RegisterMessage(Product.KeyValue) - -ProductSet = _reflection.GeneratedProtocolMessageType( - "ProductSet", - (_message.Message,), - { - "DESCRIPTOR": _PRODUCTSET, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """A ProductSet contains Products. A ProductSet can contain a maximum of - 1 million reference images. If the limit is exceeded, periodic - indexing will fail. - - Attributes: - name: - The resource name of the ProductSet. Format is: ``projects/PR - OJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID``. This - field is ignored when creating a ProductSet. - display_name: - The user-provided name for this ProductSet. Must not be empty. - Must be at most 4096 characters long. - index_time: - Output only. The time at which this ProductSet was last - indexed. Query results will reflect all updates before this - time. If this ProductSet has never been indexed, this field is - 0. This field is ignored when creating a ProductSet. - index_error: - Output only. If there was an error with indexing the product - set, the field is populated. This field is ignored when - creating a ProductSet. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ProductSet) - }, -) -_sym_db.RegisterMessage(ProductSet) - -ReferenceImage = _reflection.GeneratedProtocolMessageType( - "ReferenceImage", - (_message.Message,), - { - "DESCRIPTOR": _REFERENCEIMAGE, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """A ``ReferenceImage`` represents a product image and its associated - metadata, such as bounding boxes. - - Attributes: - name: - The resource name of the reference image. Format is: ``proje - cts/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceI - mages/IMAGE_ID``. This field is ignored when creating a - reference image. - uri: - Required. The Google Cloud Storage URI of the reference image. - The URI must start with ``gs://``. - bounding_polys: - Optional. Bounding polygons around the areas of interest in - the reference image. If this field is empty, the system will - try to detect regions of interest. At most 10 bounding - polygons will be used. The provided shape is converted into a - non-rotated rectangle. Once converted, the small edge of the - rectangle must be greater than or equal to 300 pixels. The - aspect ratio must be 1:4 or less (i.e. 1:3 is ok; 1:5 is not). - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ReferenceImage) - }, -) -_sym_db.RegisterMessage(ReferenceImage) - -CreateProductRequest = _reflection.GeneratedProtocolMessageType( - "CreateProductRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATEPRODUCTREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``CreateProduct`` method. - - Attributes: - parent: - Required. The project in which the Product should be created. - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - product: - Required. The product to create. - product_id: - A user-supplied resource id for this Product. If set, the - server will attempt to use this value as the resource id. If - it is already in use, an error is returned with code - ALREADY_EXISTS. Must be at most 128 characters long. It cannot - contain the character ``/``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.CreateProductRequest) - }, -) -_sym_db.RegisterMessage(CreateProductRequest) - -ListProductsRequest = _reflection.GeneratedProtocolMessageType( - "ListProductsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTPRODUCTSREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``ListProducts`` method. - - Attributes: - parent: - Required. The project OR ProductSet from which Products should - be listed. Format: ``projects/PROJECT_ID/locations/LOC_ID`` - page_size: - The maximum number of items to return. Default 10, maximum - 100. - page_token: - The next_page_token returned from a previous List request, if - any. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ListProductsRequest) - }, -) -_sym_db.RegisterMessage(ListProductsRequest) - -ListProductsResponse = _reflection.GeneratedProtocolMessageType( - "ListProductsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTPRODUCTSRESPONSE, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Response message for the ``ListProducts`` method. - - Attributes: - products: - List of products. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results in the list. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ListProductsResponse) - }, -) -_sym_db.RegisterMessage(ListProductsResponse) - -GetProductRequest = _reflection.GeneratedProtocolMessageType( - "GetProductRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETPRODUCTREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``GetProduct`` method. - - Attributes: - name: - Required. Resource name of the Product to get. Format is: - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.GetProductRequest) - }, -) -_sym_db.RegisterMessage(GetProductRequest) - -UpdateProductRequest = _reflection.GeneratedProtocolMessageType( - "UpdateProductRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATEPRODUCTREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``UpdateProduct`` method. - - Attributes: - product: - Required. The Product resource which replaces the one on the - server. product.name is immutable. - update_mask: - The [FieldMask][google.protobuf.FieldMask] that specifies - which fields to update. If update_mask isn’t specified, all - mutable fields are to be updated. Valid mask paths include - ``product_labels``, ``display_name``, and ``description``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.UpdateProductRequest) - }, -) -_sym_db.RegisterMessage(UpdateProductRequest) - -DeleteProductRequest = _reflection.GeneratedProtocolMessageType( - "DeleteProductRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETEPRODUCTREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``DeleteProduct`` method. - - Attributes: - name: - Required. Resource name of product to delete. Format is: - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.DeleteProductRequest) - }, -) -_sym_db.RegisterMessage(DeleteProductRequest) - -CreateProductSetRequest = _reflection.GeneratedProtocolMessageType( - "CreateProductSetRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATEPRODUCTSETREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``CreateProductSet`` method. - - Attributes: - parent: - Required. The project in which the ProductSet should be - created. Format is ``projects/PROJECT_ID/locations/LOC_ID``. - product_set: - Required. The ProductSet to create. - product_set_id: - A user-supplied resource id for this ProductSet. If set, the - server will attempt to use this value as the resource id. If - it is already in use, an error is returned with code - ALREADY_EXISTS. Must be at most 128 characters long. It cannot - contain the character ``/``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.CreateProductSetRequest) - }, -) -_sym_db.RegisterMessage(CreateProductSetRequest) - -ListProductSetsRequest = _reflection.GeneratedProtocolMessageType( - "ListProductSetsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTPRODUCTSETSREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``ListProductSets`` method. - - Attributes: - parent: - Required. The project from which ProductSets should be listed. - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - page_size: - The maximum number of items to return. Default 10, maximum - 100. - page_token: - The next_page_token returned from a previous List request, if - any. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ListProductSetsRequest) - }, -) -_sym_db.RegisterMessage(ListProductSetsRequest) - -ListProductSetsResponse = _reflection.GeneratedProtocolMessageType( - "ListProductSetsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTPRODUCTSETSRESPONSE, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Response message for the ``ListProductSets`` method. - - Attributes: - product_sets: - List of ProductSets. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results in the list. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ListProductSetsResponse) - }, -) -_sym_db.RegisterMessage(ListProductSetsResponse) - -GetProductSetRequest = _reflection.GeneratedProtocolMessageType( - "GetProductSetRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETPRODUCTSETREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``GetProductSet`` method. - - Attributes: - name: - Required. Resource name of the ProductSet to get. Format is: - ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET - _ID`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.GetProductSetRequest) - }, -) -_sym_db.RegisterMessage(GetProductSetRequest) - -UpdateProductSetRequest = _reflection.GeneratedProtocolMessageType( - "UpdateProductSetRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATEPRODUCTSETREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``UpdateProductSet`` method. - - Attributes: - product_set: - Required. The ProductSet resource which replaces the one on - the server. - update_mask: - The [FieldMask][google.protobuf.FieldMask] that specifies - which fields to update. If update_mask isn’t specified, all - mutable fields are to be updated. Valid mask path is - ``display_name``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.UpdateProductSetRequest) - }, -) -_sym_db.RegisterMessage(UpdateProductSetRequest) - -DeleteProductSetRequest = _reflection.GeneratedProtocolMessageType( - "DeleteProductSetRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETEPRODUCTSETREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``DeleteProductSet`` method. - - Attributes: - name: - Required. Resource name of the ProductSet to delete. Format - is: ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT - _SET_ID`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.DeleteProductSetRequest) - }, -) -_sym_db.RegisterMessage(DeleteProductSetRequest) - -CreateReferenceImageRequest = _reflection.GeneratedProtocolMessageType( - "CreateReferenceImageRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATEREFERENCEIMAGEREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``CreateReferenceImage`` method. - - Attributes: - parent: - Required. Resource name of the product in which to create the - reference image. Format is - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. - reference_image: - Required. The reference image to create. If an image ID is - specified, it is ignored. - reference_image_id: - A user-supplied resource id for the ReferenceImage to be - added. If set, the server will attempt to use this value as - the resource id. If it is already in use, an error is returned - with code ALREADY_EXISTS. Must be at most 128 characters long. - It cannot contain the character ``/``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.CreateReferenceImageRequest) - }, -) -_sym_db.RegisterMessage(CreateReferenceImageRequest) - -ListReferenceImagesRequest = _reflection.GeneratedProtocolMessageType( - "ListReferenceImagesRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTREFERENCEIMAGESREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``ListReferenceImages`` method. - - Attributes: - parent: - Required. Resource name of the product containing the - reference images. Format is - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. - page_size: - The maximum number of items to return. Default 10, maximum - 100. - page_token: - A token identifying a page of results to be returned. This is - the value of ``nextPageToken`` returned in a previous - reference image list request. Defaults to the first page if - not specified. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ListReferenceImagesRequest) - }, -) -_sym_db.RegisterMessage(ListReferenceImagesRequest) - -ListReferenceImagesResponse = _reflection.GeneratedProtocolMessageType( - "ListReferenceImagesResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTREFERENCEIMAGESRESPONSE, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Response message for the ``ListReferenceImages`` method. - - Attributes: - reference_images: - The list of reference images. - page_size: - The maximum number of items to return. Default 10, maximum - 100. - next_page_token: - The next_page_token returned from a previous List request, if - any. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ListReferenceImagesResponse) - }, -) -_sym_db.RegisterMessage(ListReferenceImagesResponse) - -GetReferenceImageRequest = _reflection.GeneratedProtocolMessageType( - "GetReferenceImageRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETREFERENCEIMAGEREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``GetReferenceImage`` method. - - Attributes: - name: - Required. The resource name of the ReferenceImage to get. - Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PR - ODUCT_ID/referenceImages/IMAGE_ID``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.GetReferenceImageRequest) - }, -) -_sym_db.RegisterMessage(GetReferenceImageRequest) - -DeleteReferenceImageRequest = _reflection.GeneratedProtocolMessageType( - "DeleteReferenceImageRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETEREFERENCEIMAGEREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``DeleteReferenceImage`` method. - - Attributes: - name: - Required. The resource name of the reference image to delete. - Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PR - ODUCT_ID/referenceImages/IMAGE_ID`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.DeleteReferenceImageRequest) - }, -) -_sym_db.RegisterMessage(DeleteReferenceImageRequest) - -AddProductToProductSetRequest = _reflection.GeneratedProtocolMessageType( - "AddProductToProductSetRequest", - (_message.Message,), - { - "DESCRIPTOR": _ADDPRODUCTTOPRODUCTSETREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``AddProductToProductSet`` method. - - Attributes: - name: - Required. The resource name for the ProductSet to modify. - Format is: ``projects/PROJECT_ID/locations/LOC_ID/productSets/ - PRODUCT_SET_ID`` - product: - Required. The resource name for the Product to be added to - this ProductSet. Format is: - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.AddProductToProductSetRequest) - }, -) -_sym_db.RegisterMessage(AddProductToProductSetRequest) - -RemoveProductFromProductSetRequest = _reflection.GeneratedProtocolMessageType( - "RemoveProductFromProductSetRequest", - (_message.Message,), - { - "DESCRIPTOR": _REMOVEPRODUCTFROMPRODUCTSETREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``RemoveProductFromProductSet`` method. - - Attributes: - name: - Required. The resource name for the ProductSet to modify. - Format is: ``projects/PROJECT_ID/locations/LOC_ID/productSets/ - PRODUCT_SET_ID`` - product: - Required. The resource name for the Product to be removed from - this ProductSet. Format is: - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.RemoveProductFromProductSetRequest) - }, -) -_sym_db.RegisterMessage(RemoveProductFromProductSetRequest) - -ListProductsInProductSetRequest = _reflection.GeneratedProtocolMessageType( - "ListProductsInProductSetRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTPRODUCTSINPRODUCTSETREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``ListProductsInProductSet`` method. - - Attributes: - name: - Required. The ProductSet resource for which to retrieve - Products. Format is: ``projects/PROJECT_ID/locations/LOC_ID/p - roductSets/PRODUCT_SET_ID`` - page_size: - The maximum number of items to return. Default 10, maximum - 100. - page_token: - The next_page_token returned from a previous List request, if - any. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ListProductsInProductSetRequest) - }, -) -_sym_db.RegisterMessage(ListProductsInProductSetRequest) - -ListProductsInProductSetResponse = _reflection.GeneratedProtocolMessageType( - "ListProductsInProductSetResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTPRODUCTSINPRODUCTSETRESPONSE, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Response message for the ``ListProductsInProductSet`` method. - - Attributes: - products: - The list of Products. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results in the list. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse) - }, -) -_sym_db.RegisterMessage(ListProductsInProductSetResponse) - -ImportProductSetsGcsSource = _reflection.GeneratedProtocolMessageType( - "ImportProductSetsGcsSource", - (_message.Message,), - { - "DESCRIPTOR": _IMPORTPRODUCTSETSGCSSOURCE, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """The Google Cloud Storage location for a csv file which preserves a - list of ImportProductSetRequests in each line. - - Attributes: - csv_file_uri: - The Google Cloud Storage URI of the input csv file. The URI - must start with ``gs://``. The format of the input csv file - should be one image per line. In each line, there are 6 - columns. 1. image_uri 2, image_id 3. product_set_id 4. - product_id 5, product_category 6, product_display_name 7, - labels 8. bounding_poly Columns 1, 3, 4, and 5 are required, - other columns are optional. A new ProductSet/Product with the - same id will be created on the fly if the ProductSet/Product - specified by product_set_id/product_id does not exist. The - image_id field is optional but has to be unique if provided. - If it is empty, we will automatically assign an unique id to - the image. The product_display_name field is optional. If it - is empty, a space (" ") is used as the place holder for the - product display_name, which can be updated later through the - realtime API. If the Product with product_id already exists, - the fields product_display_name, product_category and labels - are ignored. If a Product doesn’t exist and needs to be - created on the fly, the product_display_name field refers to [ - Product.display_name][google.cloud.vision.v1p3beta1.Product.di - splay_name], the product_category field refers to [Product.pro - duct_category][google.cloud.vision.v1p3beta1.Product.product_c - ategory], and the labels field refers to [Product.labels][]. - Labels (optional) should be a line containing a list of comma- - separated key-value pairs, with the format - “key_1=value_1,key_2=value_2,…,key_n=value_n”. The - bounding_poly (optional) field is used to identify one region - of interest from the image in the same manner as - CreateReferenceImage. If no bounding_poly is specified, the - system will try to detect regions of interest automatically. - Note that the pipeline will resize the image if the image - resolution is too large to process (above 20MP). Also note - that at most one bounding_poly is allowed per line. If the - image contains multiple regions of interest, the csv should - contain one line per region of interest. The bounding_poly - column should contain an even number of comma-separated - numbers, with the format “p1_x,p1_y,p2_x,p2_y,…,pn_x,pn_y”. - Nonnegative integers should be used for absolute bounding - polygons, and float values in [0, 1] should be used for - normalized bounding polygons. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ImportProductSetsGcsSource) - }, -) -_sym_db.RegisterMessage(ImportProductSetsGcsSource) - -ImportProductSetsInputConfig = _reflection.GeneratedProtocolMessageType( - "ImportProductSetsInputConfig", - (_message.Message,), - { - "DESCRIPTOR": _IMPORTPRODUCTSETSINPUTCONFIG, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """The input content for the ``ImportProductSets`` method. - - Attributes: - source: - The source of the input. - gcs_source: - The Google Cloud Storage location for a csv file which - preserves a list of ImportProductSetRequests in each line. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ImportProductSetsInputConfig) - }, -) -_sym_db.RegisterMessage(ImportProductSetsInputConfig) - -ImportProductSetsRequest = _reflection.GeneratedProtocolMessageType( - "ImportProductSetsRequest", - (_message.Message,), - { - "DESCRIPTOR": _IMPORTPRODUCTSETSREQUEST, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``ImportProductSets`` method. - - Attributes: - parent: - Required. The project in which the ProductSets should be - imported. Format is ``projects/PROJECT_ID/locations/LOC_ID``. - input_config: - Required. The input content for the list of requests. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ImportProductSetsRequest) - }, -) -_sym_db.RegisterMessage(ImportProductSetsRequest) - -ImportProductSetsResponse = _reflection.GeneratedProtocolMessageType( - "ImportProductSetsResponse", - (_message.Message,), - { - "DESCRIPTOR": _IMPORTPRODUCTSETSRESPONSE, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Response message for the ``ImportProductSets`` method. This message - is returned by the [google.longrunning.Operations.GetOperation][google - .longrunning.Operations.GetOperation] method in the returned [google.l - ongrunning.Operation.response][google.longrunning.Operation.response] - field. - - Attributes: - reference_images: - The list of reference_images that are imported successfully. - statuses: - The rpc status for each ImportProductSet request, including - both successes and errors. The number of statuses here - matches the number of lines in the csv file, and statuses[i] - stores the success or failure status of processing the i-th - line of the csv, starting from line 0. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ImportProductSetsResponse) - }, -) -_sym_db.RegisterMessage(ImportProductSetsResponse) - -BatchOperationMetadata = _reflection.GeneratedProtocolMessageType( - "BatchOperationMetadata", - (_message.Message,), - { - "DESCRIPTOR": _BATCHOPERATIONMETADATA, - "__module__": "google.cloud.vision_v1p3beta1.proto.product_search_service_pb2", - "__doc__": """Metadata for the batch operations such as the current state. This is - included in the ``metadata`` field of the ``Operation`` returned by - the ``GetOperation`` call of the ``google::longrunning::Operations`` - service. - - Attributes: - state: - The current state of the batch operation. - submit_time: - The time when the batch request was submitted to the server. - end_time: - The time when the batch request is finished and [google.longru - nning.Operation.done][google.longrunning.Operation.done] is - set to true. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.BatchOperationMetadata) - }, -) -_sym_db.RegisterMessage(BatchOperationMetadata) - - -DESCRIPTOR._options = None -_PRODUCT.fields_by_name["product_category"]._options = None -_PRODUCT._options = None -_PRODUCTSET.fields_by_name["index_time"]._options = None -_PRODUCTSET.fields_by_name["index_error"]._options = None -_PRODUCTSET._options = None -_REFERENCEIMAGE.fields_by_name["uri"]._options = None -_REFERENCEIMAGE.fields_by_name["bounding_polys"]._options = None -_REFERENCEIMAGE._options = None -_CREATEPRODUCTREQUEST.fields_by_name["parent"]._options = None -_CREATEPRODUCTREQUEST.fields_by_name["product"]._options = None -_LISTPRODUCTSREQUEST.fields_by_name["parent"]._options = None -_GETPRODUCTREQUEST.fields_by_name["name"]._options = None -_UPDATEPRODUCTREQUEST.fields_by_name["product"]._options = None -_DELETEPRODUCTREQUEST.fields_by_name["name"]._options = None -_CREATEPRODUCTSETREQUEST.fields_by_name["parent"]._options = None -_CREATEPRODUCTSETREQUEST.fields_by_name["product_set"]._options = None -_LISTPRODUCTSETSREQUEST.fields_by_name["parent"]._options = None -_GETPRODUCTSETREQUEST.fields_by_name["name"]._options = None -_UPDATEPRODUCTSETREQUEST.fields_by_name["product_set"]._options = None -_DELETEPRODUCTSETREQUEST.fields_by_name["name"]._options = None -_CREATEREFERENCEIMAGEREQUEST.fields_by_name["parent"]._options = None -_CREATEREFERENCEIMAGEREQUEST.fields_by_name["reference_image"]._options = None -_LISTREFERENCEIMAGESREQUEST.fields_by_name["parent"]._options = None -_GETREFERENCEIMAGEREQUEST.fields_by_name["name"]._options = None -_DELETEREFERENCEIMAGEREQUEST.fields_by_name["name"]._options = None -_ADDPRODUCTTOPRODUCTSETREQUEST.fields_by_name["name"]._options = None -_ADDPRODUCTTOPRODUCTSETREQUEST.fields_by_name["product"]._options = None -_REMOVEPRODUCTFROMPRODUCTSETREQUEST.fields_by_name["name"]._options = None -_REMOVEPRODUCTFROMPRODUCTSETREQUEST.fields_by_name["product"]._options = None -_LISTPRODUCTSINPRODUCTSETREQUEST.fields_by_name["name"]._options = None -_IMPORTPRODUCTSETSREQUEST.fields_by_name["parent"]._options = None -_IMPORTPRODUCTSETSREQUEST.fields_by_name["input_config"]._options = None - -_PRODUCTSEARCH = _descriptor.ServiceDescriptor( - name="ProductSearch", - full_name="google.cloud.vision.v1p3beta1.ProductSearch", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\025vision.googleapis.com\322A[https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-vision", - create_key=_descriptor._internal_create_key, - serialized_start=4637, - serialized_end=8584, - methods=[ - _descriptor.MethodDescriptor( - name="CreateProductSet", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.CreateProductSet", - index=0, - containing_service=None, - input_type=_CREATEPRODUCTSETREQUEST, - output_type=_PRODUCTSET, - serialized_options=b'\202\323\344\223\002E"6/v1p3beta1/{parent=projects/*/locations/*}/productSets:\013product_set\332A!parent,product_set,product_set_id', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListProductSets", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.ListProductSets", - index=1, - containing_service=None, - input_type=_LISTPRODUCTSETSREQUEST, - output_type=_LISTPRODUCTSETSRESPONSE, - serialized_options=b"\202\323\344\223\0028\0226/v1p3beta1/{parent=projects/*/locations/*}/productSets\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetProductSet", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.GetProductSet", - index=2, - containing_service=None, - input_type=_GETPRODUCTSETREQUEST, - output_type=_PRODUCTSET, - serialized_options=b"\202\323\344\223\0028\0226/v1p3beta1/{name=projects/*/locations/*/productSets/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateProductSet", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.UpdateProductSet", - index=3, - containing_service=None, - input_type=_UPDATEPRODUCTSETREQUEST, - output_type=_PRODUCTSET, - serialized_options=b"\202\323\344\223\002Q2B/v1p3beta1/{product_set.name=projects/*/locations/*/productSets/*}:\013product_set\332A\027product_set,update_mask", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteProductSet", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.DeleteProductSet", - index=4, - containing_service=None, - input_type=_DELETEPRODUCTSETREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\0028*6/v1p3beta1/{name=projects/*/locations/*/productSets/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateProduct", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.CreateProduct", - index=5, - containing_service=None, - input_type=_CREATEPRODUCTREQUEST, - output_type=_PRODUCT, - serialized_options=b'\202\323\344\223\002>"3/v1p3beta1/{parent=projects/*/locations/*}/products:\007product\332A\031parent,product,product_id', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListProducts", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.ListProducts", - index=6, - containing_service=None, - input_type=_LISTPRODUCTSREQUEST, - output_type=_LISTPRODUCTSRESPONSE, - serialized_options=b"\202\323\344\223\0025\0223/v1p3beta1/{parent=projects/*/locations/*}/products\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetProduct", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.GetProduct", - index=7, - containing_service=None, - input_type=_GETPRODUCTREQUEST, - output_type=_PRODUCT, - serialized_options=b"\202\323\344\223\0025\0223/v1p3beta1/{name=projects/*/locations/*/products/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateProduct", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.UpdateProduct", - index=8, - containing_service=None, - input_type=_UPDATEPRODUCTREQUEST, - output_type=_PRODUCT, - serialized_options=b"\202\323\344\223\002F2;/v1p3beta1/{product.name=projects/*/locations/*/products/*}:\007product\332A\023product,update_mask", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteProduct", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.DeleteProduct", - index=9, - containing_service=None, - input_type=_DELETEPRODUCTREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\0025*3/v1p3beta1/{name=projects/*/locations/*/products/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateReferenceImage", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.CreateReferenceImage", - index=10, - containing_service=None, - input_type=_CREATEREFERENCEIMAGEREQUEST, - output_type=_REFERENCEIMAGE, - serialized_options=b'\202\323\344\223\002X"E/v1p3beta1/{parent=projects/*/locations/*/products/*}/referenceImages:\017reference_image\332A)parent,reference_image,reference_image_id', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteReferenceImage", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.DeleteReferenceImage", - index=11, - containing_service=None, - input_type=_DELETEREFERENCEIMAGEREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\002G*E/v1p3beta1/{name=projects/*/locations/*/products/*/referenceImages/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListReferenceImages", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.ListReferenceImages", - index=12, - containing_service=None, - input_type=_LISTREFERENCEIMAGESREQUEST, - output_type=_LISTREFERENCEIMAGESRESPONSE, - serialized_options=b"\202\323\344\223\002G\022E/v1p3beta1/{parent=projects/*/locations/*/products/*}/referenceImages\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetReferenceImage", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.GetReferenceImage", - index=13, - containing_service=None, - input_type=_GETREFERENCEIMAGEREQUEST, - output_type=_REFERENCEIMAGE, - serialized_options=b"\202\323\344\223\002G\022E/v1p3beta1/{name=projects/*/locations/*/products/*/referenceImages/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="AddProductToProductSet", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.AddProductToProductSet", - index=14, - containing_service=None, - input_type=_ADDPRODUCTTOPRODUCTSETREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b'\202\323\344\223\002F"A/v1p3beta1/{name=projects/*/locations/*/productSets/*}:addProduct:\001*\332A\014name,product', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="RemoveProductFromProductSet", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.RemoveProductFromProductSet", - index=15, - containing_service=None, - input_type=_REMOVEPRODUCTFROMPRODUCTSETREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b'\202\323\344\223\002I"D/v1p3beta1/{name=projects/*/locations/*/productSets/*}:removeProduct:\001*\332A\014name,product', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListProductsInProductSet", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.ListProductsInProductSet", - index=16, - containing_service=None, - input_type=_LISTPRODUCTSINPRODUCTSETREQUEST, - output_type=_LISTPRODUCTSINPRODUCTSETRESPONSE, - serialized_options=b"\202\323\344\223\002A\022?/v1p3beta1/{name=projects/*/locations/*/productSets/*}/products\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ImportProductSets", - full_name="google.cloud.vision.v1p3beta1.ProductSearch.ImportProductSets", - index=17, - containing_service=None, - input_type=_IMPORTPRODUCTSETSREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002B"=/v1p3beta1/{parent=projects/*/locations/*}/productSets:import:\001*\332A\023parent,input_config\312A3\n\031ImportProductSetsResponse\022\026BatchOperationMetadata', - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_PRODUCTSEARCH) - -DESCRIPTOR.services_by_name["ProductSearch"] = _PRODUCTSEARCH - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p3beta1/proto/product_search_service_pb2_grpc.py b/google/cloud/vision_v1p3beta1/proto/product_search_service_pb2_grpc.py deleted file mode 100644 index b774e52e..00000000 --- a/google/cloud/vision_v1p3beta1/proto/product_search_service_pb2_grpc.py +++ /dev/null @@ -1,1003 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.vision_v1p3beta1.proto import ( - product_search_service_pb2 as google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 - - -class ProductSearchStub(object): - """Manages Products and ProductSets of reference images for use in product - search. It uses the following resource model: - - - The API has a collection of [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, named - `projects/*/locations/*/productSets/*`, which acts as a way to put different - products into groups to limit identification. - - In parallel, - - - The API has a collection of [Product][google.cloud.vision.v1p3beta1.Product] resources, named - `projects/*/locations/*/products/*` - - - Each [Product][google.cloud.vision.v1p3beta1.Product] has a collection of [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] resources, named - `projects/*/locations/*/products/*/referenceImages/*` - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.CreateProductSet = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/CreateProductSet", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.CreateProductSetRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - ) - self.ListProductSets = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/ListProductSets", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductSetsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductSetsResponse.FromString, - ) - self.GetProductSet = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/GetProductSet", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.GetProductSetRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - ) - self.UpdateProductSet = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/UpdateProductSet", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.UpdateProductSetRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - ) - self.DeleteProductSet = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteProductSet", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.DeleteProductSetRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.CreateProduct = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/CreateProduct", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.CreateProductRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.Product.FromString, - ) - self.ListProducts = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/ListProducts", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductsResponse.FromString, - ) - self.GetProduct = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/GetProduct", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.GetProductRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.Product.FromString, - ) - self.UpdateProduct = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/UpdateProduct", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.UpdateProductRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.Product.FromString, - ) - self.DeleteProduct = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteProduct", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.DeleteProductRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.CreateReferenceImage = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/CreateReferenceImage", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.CreateReferenceImageRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ReferenceImage.FromString, - ) - self.DeleteReferenceImage = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteReferenceImage", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.DeleteReferenceImageRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.ListReferenceImages = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/ListReferenceImages", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesResponse.FromString, - ) - self.GetReferenceImage = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/GetReferenceImage", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.GetReferenceImageRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ReferenceImage.FromString, - ) - self.AddProductToProductSet = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/AddProductToProductSet", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.AddProductToProductSetRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.RemoveProductFromProductSet = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/RemoveProductFromProductSet", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.RemoveProductFromProductSetRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.ListProductsInProductSet = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/ListProductsInProductSet", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetResponse.FromString, - ) - self.ImportProductSets = channel.unary_unary( - "/google.cloud.vision.v1p3beta1.ProductSearch/ImportProductSets", - request_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ImportProductSetsRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - - -class ProductSearchServicer(object): - """Manages Products and ProductSets of reference images for use in product - search. It uses the following resource model: - - - The API has a collection of [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, named - `projects/*/locations/*/productSets/*`, which acts as a way to put different - products into groups to limit identification. - - In parallel, - - - The API has a collection of [Product][google.cloud.vision.v1p3beta1.Product] resources, named - `projects/*/locations/*/products/*` - - - Each [Product][google.cloud.vision.v1p3beta1.Product] has a collection of [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] resources, named - `projects/*/locations/*/products/*/referenceImages/*` - """ - - def CreateProductSet(self, request, context): - """Creates and returns a new ProductSet resource. - - Possible errors: - - * Returns INVALID_ARGUMENT if display_name is missing, or is longer than - 4096 characters. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListProductSets(self, request, context): - """Lists ProductSets in an unspecified order. - - Possible errors: - - * Returns INVALID_ARGUMENT if page_size is greater than 100, or less - than 1. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetProductSet(self, request, context): - """Gets information associated with a ProductSet. - - Possible errors: - - * Returns NOT_FOUND if the ProductSet does not exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateProductSet(self, request, context): - """Makes changes to a ProductSet resource. - Only display_name can be updated currently. - - Possible errors: - - * Returns NOT_FOUND if the ProductSet does not exist. - * Returns INVALID_ARGUMENT if display_name is present in update_mask but - missing from the request or longer than 4096 characters. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteProductSet(self, request, context): - """Permanently deletes a ProductSet. All Products and ReferenceImages in the - ProductSet will be deleted. - - The actual image files are not deleted from Google Cloud Storage. - - Possible errors: - - * Returns NOT_FOUND if the ProductSet does not exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateProduct(self, request, context): - """Creates and returns a new product resource. - - Possible errors: - - * Returns INVALID_ARGUMENT if display_name is missing or longer than 4096 - characters. - * Returns INVALID_ARGUMENT if description is longer than 4096 characters. - * Returns INVALID_ARGUMENT if product_category is missing or invalid. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListProducts(self, request, context): - """Lists products in an unspecified order. - - Possible errors: - - * Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetProduct(self, request, context): - """Gets information associated with a Product. - - Possible errors: - - * Returns NOT_FOUND if the Product does not exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateProduct(self, request, context): - """Makes changes to a Product resource. - Only display_name, description and labels can be updated right now. - - If labels are updated, the change will not be reflected in queries until - the next index time. - - Possible errors: - - * Returns NOT_FOUND if the Product does not exist. - * Returns INVALID_ARGUMENT if display_name is present in update_mask but is - missing from the request or longer than 4096 characters. - * Returns INVALID_ARGUMENT if description is present in update_mask but is - longer than 4096 characters. - * Returns INVALID_ARGUMENT if product_category is present in update_mask. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteProduct(self, request, context): - """Permanently deletes a product and its reference images. - - Metadata of the product and all its images will be deleted right away, but - search queries against ProductSets containing the product may still work - until all related caches are refreshed. - - Possible errors: - - * Returns NOT_FOUND if the product does not exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateReferenceImage(self, request, context): - """Creates and returns a new ReferenceImage resource. - - The `bounding_poly` field is optional. If `bounding_poly` is not specified, - the system will try to detect regions of interest in the image that are - compatible with the product_category on the parent product. If it is - specified, detection is ALWAYS skipped. The system converts polygons into - non-rotated rectangles. - - Note that the pipeline will resize the image if the image resolution is too - large to process (above 50MP). - - Possible errors: - - * Returns INVALID_ARGUMENT if the image_uri is missing or longer than 4096 - characters. - * Returns INVALID_ARGUMENT if the product does not exist. - * Returns INVALID_ARGUMENT if bounding_poly is not provided, and nothing - compatible with the parent product's product_category is detected. - * Returns INVALID_ARGUMENT if bounding_poly contains more than 10 polygons. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteReferenceImage(self, request, context): - """Permanently deletes a reference image. - - The image metadata will be deleted right away, but search queries - against ProductSets containing the image may still work until all related - caches are refreshed. - - The actual image files are not deleted from Google Cloud Storage. - - Possible errors: - - * Returns NOT_FOUND if the reference image does not exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListReferenceImages(self, request, context): - """Lists reference images. - - Possible errors: - - * Returns NOT_FOUND if the parent product does not exist. - * Returns INVALID_ARGUMENT if the page_size is greater than 100, or less - than 1. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetReferenceImage(self, request, context): - """Gets information associated with a ReferenceImage. - - Possible errors: - - * Returns NOT_FOUND if the specified image does not exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def AddProductToProductSet(self, request, context): - """Adds a Product to the specified ProductSet. If the Product is already - present, no change is made. - - One Product can be added to at most 100 ProductSets. - - Possible errors: - - * Returns NOT_FOUND if the Product or the ProductSet doesn't exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def RemoveProductFromProductSet(self, request, context): - """Removes a Product from the specified ProductSet. - - Possible errors: - - * Returns NOT_FOUND If the Product is not found under the ProductSet. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListProductsInProductSet(self, request, context): - """Lists the Products in a ProductSet, in an unspecified order. If the - ProductSet does not exist, the products field of the response will be - empty. - - Possible errors: - - * Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ImportProductSets(self, request, context): - """Asynchronous API that imports a list of reference images to specified - product sets based on a list of image information. - - The [google.longrunning.Operation][google.longrunning.Operation] API can be - used to keep track of the progress and results of the request. - `Operation.metadata` contains `BatchOperationMetadata`. (progress) - `Operation.response` contains `ImportProductSetsResponse`. (results) - - The input source of this method is a csv file on Google Cloud Storage. - For the format of the csv file please see - [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1p3beta1.ImportProductSetsGcsSource.csv_file_uri]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_ProductSearchServicer_to_server(servicer, server): - rpc_method_handlers = { - "CreateProductSet": grpc.unary_unary_rpc_method_handler( - servicer.CreateProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.CreateProductSetRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ProductSet.SerializeToString, - ), - "ListProductSets": grpc.unary_unary_rpc_method_handler( - servicer.ListProductSets, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductSetsRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductSetsResponse.SerializeToString, - ), - "GetProductSet": grpc.unary_unary_rpc_method_handler( - servicer.GetProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.GetProductSetRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ProductSet.SerializeToString, - ), - "UpdateProductSet": grpc.unary_unary_rpc_method_handler( - servicer.UpdateProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.UpdateProductSetRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ProductSet.SerializeToString, - ), - "DeleteProductSet": grpc.unary_unary_rpc_method_handler( - servicer.DeleteProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.DeleteProductSetRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "CreateProduct": grpc.unary_unary_rpc_method_handler( - servicer.CreateProduct, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.CreateProductRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.Product.SerializeToString, - ), - "ListProducts": grpc.unary_unary_rpc_method_handler( - servicer.ListProducts, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductsRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductsResponse.SerializeToString, - ), - "GetProduct": grpc.unary_unary_rpc_method_handler( - servicer.GetProduct, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.GetProductRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.Product.SerializeToString, - ), - "UpdateProduct": grpc.unary_unary_rpc_method_handler( - servicer.UpdateProduct, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.UpdateProductRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.Product.SerializeToString, - ), - "DeleteProduct": grpc.unary_unary_rpc_method_handler( - servicer.DeleteProduct, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.DeleteProductRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "CreateReferenceImage": grpc.unary_unary_rpc_method_handler( - servicer.CreateReferenceImage, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.CreateReferenceImageRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ReferenceImage.SerializeToString, - ), - "DeleteReferenceImage": grpc.unary_unary_rpc_method_handler( - servicer.DeleteReferenceImage, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.DeleteReferenceImageRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "ListReferenceImages": grpc.unary_unary_rpc_method_handler( - servicer.ListReferenceImages, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesResponse.SerializeToString, - ), - "GetReferenceImage": grpc.unary_unary_rpc_method_handler( - servicer.GetReferenceImage, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.GetReferenceImageRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ReferenceImage.SerializeToString, - ), - "AddProductToProductSet": grpc.unary_unary_rpc_method_handler( - servicer.AddProductToProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.AddProductToProductSetRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "RemoveProductFromProductSet": grpc.unary_unary_rpc_method_handler( - servicer.RemoveProductFromProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.RemoveProductFromProductSetRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "ListProductsInProductSet": grpc.unary_unary_rpc_method_handler( - servicer.ListProductsInProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetResponse.SerializeToString, - ), - "ImportProductSets": grpc.unary_unary_rpc_method_handler( - servicer.ImportProductSets, - request_deserializer=google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ImportProductSetsRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.vision.v1p3beta1.ProductSearch", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class ProductSearch(object): - """Manages Products and ProductSets of reference images for use in product - search. It uses the following resource model: - - - The API has a collection of [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, named - `projects/*/locations/*/productSets/*`, which acts as a way to put different - products into groups to limit identification. - - In parallel, - - - The API has a collection of [Product][google.cloud.vision.v1p3beta1.Product] resources, named - `projects/*/locations/*/products/*` - - - Each [Product][google.cloud.vision.v1p3beta1.Product] has a collection of [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] resources, named - `projects/*/locations/*/products/*/referenceImages/*` - """ - - @staticmethod - def CreateProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/CreateProductSet", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.CreateProductSetRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListProductSets( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/ListProductSets", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductSetsRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductSetsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/GetProductSet", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.GetProductSetRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/UpdateProductSet", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.UpdateProductSetRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteProductSet", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.DeleteProductSetRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def CreateProduct( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/CreateProduct", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.CreateProductRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.Product.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListProducts( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/ListProducts", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductsRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetProduct( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/GetProduct", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.GetProductRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.Product.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateProduct( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/UpdateProduct", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.UpdateProductRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.Product.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteProduct( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteProduct", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.DeleteProductRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def CreateReferenceImage( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/CreateReferenceImage", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.CreateReferenceImageRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ReferenceImage.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteReferenceImage( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteReferenceImage", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.DeleteReferenceImageRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListReferenceImages( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/ListReferenceImages", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetReferenceImage( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/GetReferenceImage", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.GetReferenceImageRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ReferenceImage.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def AddProductToProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/AddProductToProductSet", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.AddProductToProductSetRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def RemoveProductFromProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/RemoveProductFromProductSet", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.RemoveProductFromProductSetRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListProductsInProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/ListProductsInProductSet", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ImportProductSets( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p3beta1.ProductSearch/ImportProductSets", - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_product__search__service__pb2.ImportProductSetsRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/vision_v1p3beta1/proto/text_annotation_pb2.py b/google/cloud/vision_v1p3beta1/proto/text_annotation_pb2.py deleted file mode 100644 index dda7ecda..00000000 --- a/google/cloud/vision_v1p3beta1/proto/text_annotation_pb2.py +++ /dev/null @@ -1,1224 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p3beta1/proto/text_annotation.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.cloud.vision_v1p3beta1.proto import ( - geometry_pb2 as google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2, -) - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p3beta1/proto/text_annotation.proto", - package="google.cloud.vision.v1p3beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p3beta1B\023TextAnnotationProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p3beta1;vision\370\001\001", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n9google/cloud/vision_v1p3beta1/proto/text_annotation.proto\x12\x1dgoogle.cloud.vision.v1p3beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x32google/cloud/vision_v1p3beta1/proto/geometry.proto"\xb2\x04\n\x0eTextAnnotation\x12\x32\n\x05pages\x18\x01 \x03(\x0b\x32#.google.cloud.vision.v1p3beta1.Page\x12\x0c\n\x04text\x18\x02 \x01(\t\x1a=\n\x10\x44\x65tectedLanguage\x12\x15\n\rlanguage_code\x18\x01 \x01(\t\x12\x12\n\nconfidence\x18\x02 \x01(\x02\x1a\xdc\x01\n\rDetectedBreak\x12S\n\x04type\x18\x01 \x01(\x0e\x32\x45.google.cloud.vision.v1p3beta1.TextAnnotation.DetectedBreak.BreakType\x12\x11\n\tis_prefix\x18\x02 \x01(\x08"c\n\tBreakType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\t\n\x05SPACE\x10\x01\x12\x0e\n\nSURE_SPACE\x10\x02\x12\x12\n\x0e\x45OL_SURE_SPACE\x10\x03\x12\n\n\x06HYPHEN\x10\x04\x12\x0e\n\nLINE_BREAK\x10\x05\x1a\xbf\x01\n\x0cTextProperty\x12Z\n\x12\x64\x65tected_languages\x18\x01 \x03(\x0b\x32>.google.cloud.vision.v1p3beta1.TextAnnotation.DetectedLanguage\x12S\n\x0e\x64\x65tected_break\x18\x02 \x01(\x0b\x32;.google.cloud.vision.v1p3beta1.TextAnnotation.DetectedBreak"\xbd\x01\n\x04Page\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p3beta1.TextAnnotation.TextProperty\x12\r\n\x05width\x18\x02 \x01(\x05\x12\x0e\n\x06height\x18\x03 \x01(\x05\x12\x34\n\x06\x62locks\x18\x04 \x03(\x0b\x32$.google.cloud.vision.v1p3beta1.Block\x12\x12\n\nconfidence\x18\x05 \x01(\x02"\x82\x03\n\x05\x42lock\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p3beta1.TextAnnotation.TextProperty\x12\x41\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p3beta1.BoundingPoly\x12<\n\nparagraphs\x18\x03 \x03(\x0b\x32(.google.cloud.vision.v1p3beta1.Paragraph\x12\x42\n\nblock_type\x18\x04 \x01(\x0e\x32..google.cloud.vision.v1p3beta1.Block.BlockType\x12\x12\n\nconfidence\x18\x05 \x01(\x02"R\n\tBlockType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x08\n\x04TEXT\x10\x01\x12\t\n\x05TABLE\x10\x02\x12\x0b\n\x07PICTURE\x10\x03\x12\t\n\x05RULER\x10\x04\x12\x0b\n\x07\x42\x41RCODE\x10\x05"\xe4\x01\n\tParagraph\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p3beta1.TextAnnotation.TextProperty\x12\x41\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p3beta1.BoundingPoly\x12\x32\n\x05words\x18\x03 \x03(\x0b\x32#.google.cloud.vision.v1p3beta1.Word\x12\x12\n\nconfidence\x18\x04 \x01(\x02"\xe3\x01\n\x04Word\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p3beta1.TextAnnotation.TextProperty\x12\x41\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p3beta1.BoundingPoly\x12\x36\n\x07symbols\x18\x03 \x03(\x0b\x32%.google.cloud.vision.v1p3beta1.Symbol\x12\x12\n\nconfidence\x18\x04 \x01(\x02"\xbb\x01\n\x06Symbol\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p3beta1.TextAnnotation.TextProperty\x12\x41\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p3beta1.BoundingPoly\x12\x0c\n\x04text\x18\x03 \x01(\t\x12\x12\n\nconfidence\x18\x04 \x01(\x02\x42\x82\x01\n!com.google.cloud.vision.v1p3beta1B\x13TextAnnotationProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p3beta1;vision\xf8\x01\x01\x62\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2.DESCRIPTOR, - ], -) - - -_TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE = _descriptor.EnumDescriptor( - name="BreakType", - full_name="google.cloud.vision.v1p3beta1.TextAnnotation.DetectedBreak.BreakType", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNKNOWN", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SPACE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SURE_SPACE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="EOL_SURE_SPACE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="HYPHEN", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LINE_BREAK", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=444, - serialized_end=543, -) -_sym_db.RegisterEnumDescriptor(_TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE) - -_BLOCK_BLOCKTYPE = _descriptor.EnumDescriptor( - name="BlockType", - full_name="google.cloud.vision.v1p3beta1.Block.BlockType", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNKNOWN", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="TEXT", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="TABLE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="PICTURE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RULER", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="BARCODE", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=1236, - serialized_end=1318, -) -_sym_db.RegisterEnumDescriptor(_BLOCK_BLOCKTYPE) - - -_TEXTANNOTATION_DETECTEDLANGUAGE = _descriptor.Descriptor( - name="DetectedLanguage", - full_name="google.cloud.vision.v1p3beta1.TextAnnotation.DetectedLanguage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="language_code", - full_name="google.cloud.vision.v1p3beta1.TextAnnotation.DetectedLanguage.language_code", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p3beta1.TextAnnotation.DetectedLanguage.confidence", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=259, - serialized_end=320, -) - -_TEXTANNOTATION_DETECTEDBREAK = _descriptor.Descriptor( - name="DetectedBreak", - full_name="google.cloud.vision.v1p3beta1.TextAnnotation.DetectedBreak", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="type", - full_name="google.cloud.vision.v1p3beta1.TextAnnotation.DetectedBreak.type", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="is_prefix", - full_name="google.cloud.vision.v1p3beta1.TextAnnotation.DetectedBreak.is_prefix", - index=1, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=323, - serialized_end=543, -) - -_TEXTANNOTATION_TEXTPROPERTY = _descriptor.Descriptor( - name="TextProperty", - full_name="google.cloud.vision.v1p3beta1.TextAnnotation.TextProperty", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="detected_languages", - full_name="google.cloud.vision.v1p3beta1.TextAnnotation.TextProperty.detected_languages", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="detected_break", - full_name="google.cloud.vision.v1p3beta1.TextAnnotation.TextProperty.detected_break", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=546, - serialized_end=737, -) - -_TEXTANNOTATION = _descriptor.Descriptor( - name="TextAnnotation", - full_name="google.cloud.vision.v1p3beta1.TextAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="pages", - full_name="google.cloud.vision.v1p3beta1.TextAnnotation.pages", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="text", - full_name="google.cloud.vision.v1p3beta1.TextAnnotation.text", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _TEXTANNOTATION_DETECTEDLANGUAGE, - _TEXTANNOTATION_DETECTEDBREAK, - _TEXTANNOTATION_TEXTPROPERTY, - ], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=175, - serialized_end=737, -) - - -_PAGE = _descriptor.Descriptor( - name="Page", - full_name="google.cloud.vision.v1p3beta1.Page", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p3beta1.Page.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="width", - full_name="google.cloud.vision.v1p3beta1.Page.width", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="height", - full_name="google.cloud.vision.v1p3beta1.Page.height", - index=2, - number=3, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="blocks", - full_name="google.cloud.vision.v1p3beta1.Page.blocks", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p3beta1.Page.confidence", - index=4, - number=5, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=740, - serialized_end=929, -) - - -_BLOCK = _descriptor.Descriptor( - name="Block", - full_name="google.cloud.vision.v1p3beta1.Block", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p3beta1.Block.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_box", - full_name="google.cloud.vision.v1p3beta1.Block.bounding_box", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="paragraphs", - full_name="google.cloud.vision.v1p3beta1.Block.paragraphs", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="block_type", - full_name="google.cloud.vision.v1p3beta1.Block.block_type", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p3beta1.Block.confidence", - index=4, - number=5, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_BLOCK_BLOCKTYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=932, - serialized_end=1318, -) - - -_PARAGRAPH = _descriptor.Descriptor( - name="Paragraph", - full_name="google.cloud.vision.v1p3beta1.Paragraph", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p3beta1.Paragraph.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_box", - full_name="google.cloud.vision.v1p3beta1.Paragraph.bounding_box", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="words", - full_name="google.cloud.vision.v1p3beta1.Paragraph.words", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p3beta1.Paragraph.confidence", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1321, - serialized_end=1549, -) - - -_WORD = _descriptor.Descriptor( - name="Word", - full_name="google.cloud.vision.v1p3beta1.Word", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p3beta1.Word.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_box", - full_name="google.cloud.vision.v1p3beta1.Word.bounding_box", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="symbols", - full_name="google.cloud.vision.v1p3beta1.Word.symbols", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p3beta1.Word.confidence", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1552, - serialized_end=1779, -) - - -_SYMBOL = _descriptor.Descriptor( - name="Symbol", - full_name="google.cloud.vision.v1p3beta1.Symbol", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p3beta1.Symbol.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_box", - full_name="google.cloud.vision.v1p3beta1.Symbol.bounding_box", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="text", - full_name="google.cloud.vision.v1p3beta1.Symbol.text", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p3beta1.Symbol.confidence", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1782, - serialized_end=1969, -) - -_TEXTANNOTATION_DETECTEDLANGUAGE.containing_type = _TEXTANNOTATION -_TEXTANNOTATION_DETECTEDBREAK.fields_by_name[ - "type" -].enum_type = _TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE -_TEXTANNOTATION_DETECTEDBREAK.containing_type = _TEXTANNOTATION -_TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE.containing_type = _TEXTANNOTATION_DETECTEDBREAK -_TEXTANNOTATION_TEXTPROPERTY.fields_by_name[ - "detected_languages" -].message_type = _TEXTANNOTATION_DETECTEDLANGUAGE -_TEXTANNOTATION_TEXTPROPERTY.fields_by_name[ - "detected_break" -].message_type = _TEXTANNOTATION_DETECTEDBREAK -_TEXTANNOTATION_TEXTPROPERTY.containing_type = _TEXTANNOTATION -_TEXTANNOTATION.fields_by_name["pages"].message_type = _PAGE -_PAGE.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_PAGE.fields_by_name["blocks"].message_type = _BLOCK -_BLOCK.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_BLOCK.fields_by_name[ - "bounding_box" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_BLOCK.fields_by_name["paragraphs"].message_type = _PARAGRAPH -_BLOCK.fields_by_name["block_type"].enum_type = _BLOCK_BLOCKTYPE -_BLOCK_BLOCKTYPE.containing_type = _BLOCK -_PARAGRAPH.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_PARAGRAPH.fields_by_name[ - "bounding_box" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_PARAGRAPH.fields_by_name["words"].message_type = _WORD -_WORD.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_WORD.fields_by_name[ - "bounding_box" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_WORD.fields_by_name["symbols"].message_type = _SYMBOL -_SYMBOL.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_SYMBOL.fields_by_name[ - "bounding_box" -].message_type = ( - google_dot_cloud_dot_vision__v1p3beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -DESCRIPTOR.message_types_by_name["TextAnnotation"] = _TEXTANNOTATION -DESCRIPTOR.message_types_by_name["Page"] = _PAGE -DESCRIPTOR.message_types_by_name["Block"] = _BLOCK -DESCRIPTOR.message_types_by_name["Paragraph"] = _PARAGRAPH -DESCRIPTOR.message_types_by_name["Word"] = _WORD -DESCRIPTOR.message_types_by_name["Symbol"] = _SYMBOL -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -TextAnnotation = _reflection.GeneratedProtocolMessageType( - "TextAnnotation", - (_message.Message,), - { - "DetectedLanguage": _reflection.GeneratedProtocolMessageType( - "DetectedLanguage", - (_message.Message,), - { - "DESCRIPTOR": _TEXTANNOTATION_DETECTEDLANGUAGE, - "__module__": "google.cloud.vision_v1p3beta1.proto.text_annotation_pb2", - "__doc__": """Detected language for a structural component. - - Attributes: - language_code: - The BCP-47 language code, such as “en-US” or “sr-Latn”. For - more information, see http://www.unicode.org/reports/tr35/#Uni - code_locale_identifier. - confidence: - Confidence of detected language. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.TextAnnotation.DetectedLanguage) - }, - ), - "DetectedBreak": _reflection.GeneratedProtocolMessageType( - "DetectedBreak", - (_message.Message,), - { - "DESCRIPTOR": _TEXTANNOTATION_DETECTEDBREAK, - "__module__": "google.cloud.vision_v1p3beta1.proto.text_annotation_pb2", - "__doc__": """Detected start or end of a structural component. - - Attributes: - type: - Detected break type. - is_prefix: - True if break prepends the element. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.TextAnnotation.DetectedBreak) - }, - ), - "TextProperty": _reflection.GeneratedProtocolMessageType( - "TextProperty", - (_message.Message,), - { - "DESCRIPTOR": _TEXTANNOTATION_TEXTPROPERTY, - "__module__": "google.cloud.vision_v1p3beta1.proto.text_annotation_pb2", - "__doc__": """Additional information detected on the structural component. - - Attributes: - detected_languages: - A list of detected languages together with confidence. - detected_break: - Detected start or end of a text segment. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.TextAnnotation.TextProperty) - }, - ), - "DESCRIPTOR": _TEXTANNOTATION, - "__module__": "google.cloud.vision_v1p3beta1.proto.text_annotation_pb2", - "__doc__": """TextAnnotation contains a structured representation of OCR extracted - text. The hierarchy of an OCR extracted text structure is like this: - TextAnnotation -> Page -> Block -> Paragraph -> Word -> Symbol Each - structural component, starting from Page, may further have their own - properties. Properties describe detected languages, breaks etc.. - Please refer to the [TextAnnotation.TextProperty][google.cloud.vision. - v1p3beta1.TextAnnotation.TextProperty] message definition below for - more detail. - - Attributes: - pages: - List of pages detected by OCR. - text: - UTF-8 text detected on the pages. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.TextAnnotation) - }, -) -_sym_db.RegisterMessage(TextAnnotation) -_sym_db.RegisterMessage(TextAnnotation.DetectedLanguage) -_sym_db.RegisterMessage(TextAnnotation.DetectedBreak) -_sym_db.RegisterMessage(TextAnnotation.TextProperty) - -Page = _reflection.GeneratedProtocolMessageType( - "Page", - (_message.Message,), - { - "DESCRIPTOR": _PAGE, - "__module__": "google.cloud.vision_v1p3beta1.proto.text_annotation_pb2", - "__doc__": """Detected page from OCR. - - Attributes: - property: - Additional information detected on the page. - width: - Page width. For PDFs the unit is points. For images (including - TIFFs) the unit is pixels. - height: - Page height. For PDFs the unit is points. For images - (including TIFFs) the unit is pixels. - blocks: - List of blocks of text, images etc on this page. - confidence: - Confidence of the OCR results on the page. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.Page) - }, -) -_sym_db.RegisterMessage(Page) - -Block = _reflection.GeneratedProtocolMessageType( - "Block", - (_message.Message,), - { - "DESCRIPTOR": _BLOCK, - "__module__": "google.cloud.vision_v1p3beta1.proto.text_annotation_pb2", - "__doc__": """Logical element on the page. - - Attributes: - property: - Additional information detected for the block. - bounding_box: - The bounding box for the block. The vertices are in the order - of top-left, top-right, bottom-right, bottom-left. When a - rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: - - when the text is horizontal it might look like: :: - 0----1 | | 3----2 - when it’s rotated 180 - degrees around the top-left corner it becomes: :: - 2----3 | | 1----0 and the vertice order - will still be (0, 1, 2, 3). - paragraphs: - List of paragraphs in this block (if this blocks is of type - text). - block_type: - Detected block type (text, image etc) for this block. - confidence: - Confidence of the OCR results on the block. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.Block) - }, -) -_sym_db.RegisterMessage(Block) - -Paragraph = _reflection.GeneratedProtocolMessageType( - "Paragraph", - (_message.Message,), - { - "DESCRIPTOR": _PARAGRAPH, - "__module__": "google.cloud.vision_v1p3beta1.proto.text_annotation_pb2", - "__doc__": """Structural unit of text representing a number of words in certain - order. - - Attributes: - property: - Additional information detected for the paragraph. - bounding_box: - The bounding box for the paragraph. The vertices are in the - order of top-left, top-right, bottom-right, bottom-left. When - a rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: \* - when the text is horizontal it might look like: 0—-1 \| \| - 3—-2 \* when it’s rotated 180 degrees around the top-left - corner it becomes: 2—-3 \| \| 1—-0 and the vertice order will - still be (0, 1, 2, 3). - words: - List of words in this paragraph. - confidence: - Confidence of the OCR results for the paragraph. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.Paragraph) - }, -) -_sym_db.RegisterMessage(Paragraph) - -Word = _reflection.GeneratedProtocolMessageType( - "Word", - (_message.Message,), - { - "DESCRIPTOR": _WORD, - "__module__": "google.cloud.vision_v1p3beta1.proto.text_annotation_pb2", - "__doc__": """A word representation. - - Attributes: - property: - Additional information detected for the word. - bounding_box: - The bounding box for the word. The vertices are in the order - of top-left, top-right, bottom-right, bottom-left. When a - rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: \* - when the text is horizontal it might look like: 0—-1 \| \| - 3—-2 \* when it’s rotated 180 degrees around the top-left - corner it becomes: 2—-3 \| \| 1—-0 and the vertice order will - still be (0, 1, 2, 3). - symbols: - List of symbols in the word. The order of the symbols follows - the natural reading order. - confidence: - Confidence of the OCR results for the word. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.Word) - }, -) -_sym_db.RegisterMessage(Word) - -Symbol = _reflection.GeneratedProtocolMessageType( - "Symbol", - (_message.Message,), - { - "DESCRIPTOR": _SYMBOL, - "__module__": "google.cloud.vision_v1p3beta1.proto.text_annotation_pb2", - "__doc__": """A single symbol representation. - - Attributes: - property: - Additional information detected for the symbol. - bounding_box: - The bounding box for the symbol. The vertices are in the order - of top-left, top-right, bottom-right, bottom-left. When a - rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: \* - when the text is horizontal it might look like: 0—-1 \| \| - 3—-2 \* when it’s rotated 180 degrees around the top-left - corner it becomes: 2—-3 \| \| 1—-0 and the vertice order will - still be (0, 1, 2, 3). - text: - The actual UTF-8 representation of the symbol. - confidence: - Confidence of the OCR results for the symbol. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.Symbol) - }, -) -_sym_db.RegisterMessage(Symbol) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p3beta1/proto/text_annotation_pb2_grpc.py b/google/cloud/vision_v1p3beta1/proto/text_annotation_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/vision_v1p3beta1/proto/text_annotation_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/vision_v1p3beta1/proto/web_detection_pb2.py b/google/cloud/vision_v1p3beta1/proto/web_detection_pb2.py deleted file mode 100644 index 5ae78609..00000000 --- a/google/cloud/vision_v1p3beta1/proto/web_detection_pb2.py +++ /dev/null @@ -1,628 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p3beta1/proto/web_detection.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p3beta1/proto/web_detection.proto", - package="google.cloud.vision.v1p3beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p3beta1B\021WebDetectionProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p3beta1;vision\370\001\001", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n7google/cloud/vision_v1p3beta1/proto/web_detection.proto\x12\x1dgoogle.cloud.vision.v1p3beta1\x1a\x1cgoogle/api/annotations.proto"\x8c\x07\n\x0cWebDetection\x12K\n\x0cweb_entities\x18\x01 \x03(\x0b\x32\x35.google.cloud.vision.v1p3beta1.WebDetection.WebEntity\x12R\n\x14\x66ull_matching_images\x18\x02 \x03(\x0b\x32\x34.google.cloud.vision.v1p3beta1.WebDetection.WebImage\x12U\n\x17partial_matching_images\x18\x03 \x03(\x0b\x32\x34.google.cloud.vision.v1p3beta1.WebDetection.WebImage\x12W\n\x1apages_with_matching_images\x18\x04 \x03(\x0b\x32\x33.google.cloud.vision.v1p3beta1.WebDetection.WebPage\x12U\n\x17visually_similar_images\x18\x06 \x03(\x0b\x32\x34.google.cloud.vision.v1p3beta1.WebDetection.WebImage\x12O\n\x11\x62\x65st_guess_labels\x18\x08 \x03(\x0b\x32\x34.google.cloud.vision.v1p3beta1.WebDetection.WebLabel\x1a\x42\n\tWebEntity\x12\x11\n\tentity_id\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\x1a&\n\x08WebImage\x12\x0b\n\x03url\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x1a\xe4\x01\n\x07WebPage\x12\x0b\n\x03url\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x12\n\npage_title\x18\x03 \x01(\t\x12R\n\x14\x66ull_matching_images\x18\x04 \x03(\x0b\x32\x34.google.cloud.vision.v1p3beta1.WebDetection.WebImage\x12U\n\x17partial_matching_images\x18\x05 \x03(\x0b\x32\x34.google.cloud.vision.v1p3beta1.WebDetection.WebImage\x1a\x30\n\x08WebLabel\x12\r\n\x05label\x18\x01 \x01(\t\x12\x15\n\rlanguage_code\x18\x02 \x01(\tB\x80\x01\n!com.google.cloud.vision.v1p3beta1B\x11WebDetectionProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p3beta1;vision\xf8\x01\x01\x62\x06proto3', - dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,], -) - - -_WEBDETECTION_WEBENTITY = _descriptor.Descriptor( - name="WebEntity", - full_name="google.cloud.vision.v1p3beta1.WebDetection.WebEntity", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="entity_id", - full_name="google.cloud.vision.v1p3beta1.WebDetection.WebEntity.entity_id", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p3beta1.WebDetection.WebEntity.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.vision.v1p3beta1.WebDetection.WebEntity.description", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=642, - serialized_end=708, -) - -_WEBDETECTION_WEBIMAGE = _descriptor.Descriptor( - name="WebImage", - full_name="google.cloud.vision.v1p3beta1.WebDetection.WebImage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="url", - full_name="google.cloud.vision.v1p3beta1.WebDetection.WebImage.url", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p3beta1.WebDetection.WebImage.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=710, - serialized_end=748, -) - -_WEBDETECTION_WEBPAGE = _descriptor.Descriptor( - name="WebPage", - full_name="google.cloud.vision.v1p3beta1.WebDetection.WebPage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="url", - full_name="google.cloud.vision.v1p3beta1.WebDetection.WebPage.url", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p3beta1.WebDetection.WebPage.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_title", - full_name="google.cloud.vision.v1p3beta1.WebDetection.WebPage.page_title", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="full_matching_images", - full_name="google.cloud.vision.v1p3beta1.WebDetection.WebPage.full_matching_images", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="partial_matching_images", - full_name="google.cloud.vision.v1p3beta1.WebDetection.WebPage.partial_matching_images", - index=4, - number=5, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=751, - serialized_end=979, -) - -_WEBDETECTION_WEBLABEL = _descriptor.Descriptor( - name="WebLabel", - full_name="google.cloud.vision.v1p3beta1.WebDetection.WebLabel", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="label", - full_name="google.cloud.vision.v1p3beta1.WebDetection.WebLabel.label", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="language_code", - full_name="google.cloud.vision.v1p3beta1.WebDetection.WebLabel.language_code", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=981, - serialized_end=1029, -) - -_WEBDETECTION = _descriptor.Descriptor( - name="WebDetection", - full_name="google.cloud.vision.v1p3beta1.WebDetection", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="web_entities", - full_name="google.cloud.vision.v1p3beta1.WebDetection.web_entities", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="full_matching_images", - full_name="google.cloud.vision.v1p3beta1.WebDetection.full_matching_images", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="partial_matching_images", - full_name="google.cloud.vision.v1p3beta1.WebDetection.partial_matching_images", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="pages_with_matching_images", - full_name="google.cloud.vision.v1p3beta1.WebDetection.pages_with_matching_images", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="visually_similar_images", - full_name="google.cloud.vision.v1p3beta1.WebDetection.visually_similar_images", - index=4, - number=6, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="best_guess_labels", - full_name="google.cloud.vision.v1p3beta1.WebDetection.best_guess_labels", - index=5, - number=8, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _WEBDETECTION_WEBENTITY, - _WEBDETECTION_WEBIMAGE, - _WEBDETECTION_WEBPAGE, - _WEBDETECTION_WEBLABEL, - ], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=121, - serialized_end=1029, -) - -_WEBDETECTION_WEBENTITY.containing_type = _WEBDETECTION -_WEBDETECTION_WEBIMAGE.containing_type = _WEBDETECTION -_WEBDETECTION_WEBPAGE.fields_by_name[ - "full_matching_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION_WEBPAGE.fields_by_name[ - "partial_matching_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION_WEBPAGE.containing_type = _WEBDETECTION -_WEBDETECTION_WEBLABEL.containing_type = _WEBDETECTION -_WEBDETECTION.fields_by_name["web_entities"].message_type = _WEBDETECTION_WEBENTITY -_WEBDETECTION.fields_by_name[ - "full_matching_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION.fields_by_name[ - "partial_matching_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION.fields_by_name[ - "pages_with_matching_images" -].message_type = _WEBDETECTION_WEBPAGE -_WEBDETECTION.fields_by_name[ - "visually_similar_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION.fields_by_name["best_guess_labels"].message_type = _WEBDETECTION_WEBLABEL -DESCRIPTOR.message_types_by_name["WebDetection"] = _WEBDETECTION -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -WebDetection = _reflection.GeneratedProtocolMessageType( - "WebDetection", - (_message.Message,), - { - "WebEntity": _reflection.GeneratedProtocolMessageType( - "WebEntity", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTION_WEBENTITY, - "__module__": "google.cloud.vision_v1p3beta1.proto.web_detection_pb2", - "__doc__": """Entity deduced from similar images on the Internet. - - Attributes: - entity_id: - Opaque entity ID. - score: - Overall relevancy score for the entity. Not normalized and not - comparable across different image queries. - description: - Canonical description of the entity, in English. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.WebDetection.WebEntity) - }, - ), - "WebImage": _reflection.GeneratedProtocolMessageType( - "WebImage", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTION_WEBIMAGE, - "__module__": "google.cloud.vision_v1p3beta1.proto.web_detection_pb2", - "__doc__": """Metadata for online images. - - Attributes: - url: - The result image URL. - score: - (Deprecated) Overall relevancy score for the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.WebDetection.WebImage) - }, - ), - "WebPage": _reflection.GeneratedProtocolMessageType( - "WebPage", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTION_WEBPAGE, - "__module__": "google.cloud.vision_v1p3beta1.proto.web_detection_pb2", - "__doc__": """Metadata for web pages. - - Attributes: - url: - The result web page URL. - score: - (Deprecated) Overall relevancy score for the web page. - page_title: - Title for the web page, may contain HTML markups. - full_matching_images: - Fully matching images on the page. Can include resized copies - of the query image. - partial_matching_images: - Partial matching images on the page. Those images are similar - enough to share some key-point features. For example an - original image will likely have partial matching for its - crops. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.WebDetection.WebPage) - }, - ), - "WebLabel": _reflection.GeneratedProtocolMessageType( - "WebLabel", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTION_WEBLABEL, - "__module__": "google.cloud.vision_v1p3beta1.proto.web_detection_pb2", - "__doc__": """Label to provide extra metadata for the web detection. - - Attributes: - label: - Label for extra metadata. - language_code: - The BCP-47 language code for ``label``, such as “en-US” or - “sr-Latn”. For more information, see http://www.unicode.org/re - ports/tr35/#Unicode_locale_identifier. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.WebDetection.WebLabel) - }, - ), - "DESCRIPTOR": _WEBDETECTION, - "__module__": "google.cloud.vision_v1p3beta1.proto.web_detection_pb2", - "__doc__": """Relevant information for the image from the Internet. - - Attributes: - web_entities: - Deduced entities from similar images on the Internet. - full_matching_images: - Fully matching images from the Internet. Can include resized - copies of the query image. - partial_matching_images: - Partial matching images from the Internet. Those images are - similar enough to share some key-point features. For example - an original image will likely have partial matching for its - crops. - pages_with_matching_images: - Web pages containing the matching images from the Internet. - visually_similar_images: - The visually similar image results. - best_guess_labels: - Best guess text labels for the request image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.WebDetection) - }, -) -_sym_db.RegisterMessage(WebDetection) -_sym_db.RegisterMessage(WebDetection.WebEntity) -_sym_db.RegisterMessage(WebDetection.WebImage) -_sym_db.RegisterMessage(WebDetection.WebPage) -_sym_db.RegisterMessage(WebDetection.WebLabel) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p3beta1/proto/web_detection_pb2_grpc.py b/google/cloud/vision_v1p3beta1/proto/web_detection_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/vision_v1p3beta1/proto/web_detection_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/vision_v1p3beta1/py.typed b/google/cloud/vision_v1p3beta1/py.typed new file mode 100644 index 00000000..8cb07491 --- /dev/null +++ b/google/cloud/vision_v1p3beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-vision package uses inline types. diff --git a/google/cloud/vision_v1p3beta1/services/__init__.py b/google/cloud/vision_v1p3beta1/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/vision_v1p3beta1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/__init__.py b/google/cloud/vision_v1p3beta1/services/image_annotator/__init__.py new file mode 100644 index 00000000..2b601881 --- /dev/null +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import ImageAnnotatorClient +from .async_client import ImageAnnotatorAsyncClient + +__all__ = ( + "ImageAnnotatorClient", + "ImageAnnotatorAsyncClient", +) diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/async_client.py b/google/cloud/vision_v1p3beta1/services/image_annotator/async_client.py new file mode 100644 index 00000000..64d06d59 --- /dev/null +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/async_client.py @@ -0,0 +1,278 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1p3beta1.types import image_annotator + +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport +from .client import ImageAnnotatorClient + + +class ImageAnnotatorAsyncClient: + """Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + """ + + _client: ImageAnnotatorClient + + DEFAULT_ENDPOINT = ImageAnnotatorClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + + from_service_account_file = ImageAnnotatorClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(ImageAnnotatorClient).get_transport_class, type(ImageAnnotatorClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, ImageAnnotatorTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the image annotator client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ImageAnnotatorTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = ImageAnnotatorClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def batch_annotate_images( + self, + request: image_annotator.BatchAnnotateImagesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateImageRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: + r"""Run image detection and annotation for a batch of + images. + + Args: + request (:class:`~.image_annotator.BatchAnnotateImagesRequest`): + The request object. Multiple image annotation requests + are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AnnotateImageRequest]`): + Individual image annotation requests + for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.image_annotator.BatchAnnotateImagesResponse: + Response to a batch image annotation + request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([requests]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = image_annotator.BatchAnnotateImagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_annotate_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def async_batch_annotate_files( + self, + request: image_annotator.AsyncBatchAnnotateFilesRequest = None, + *, + requests: Sequence[image_annotator.AsyncAnnotateFileRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Run asynchronous image detection and annotation for a list of + generic files, such as PDF files, which may contain multiple + pages and multiple images per page. Progress and results can be + retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateFilesResponse`` (results). + + Args: + request (:class:`~.image_annotator.AsyncBatchAnnotateFilesRequest`): + The request object. Multiple async file annotation + requests are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AsyncAnnotateFileRequest]`): + Required. Individual async file + annotation requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.image_annotator.AsyncBatchAnnotateFilesResponse``: + Response to an async batch file annotation request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([requests]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = image_annotator.AsyncBatchAnnotateFilesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.async_batch_annotate_files, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + image_annotator.AsyncBatchAnnotateFilesResponse, + metadata_type=image_annotator.OperationMetadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ImageAnnotatorAsyncClient",) diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/client.py b/google/cloud/vision_v1p3beta1/services/image_annotator/client.py new file mode 100644 index 00000000..a7fc7e0c --- /dev/null +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/client.py @@ -0,0 +1,424 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1p3beta1.types import image_annotator + +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ImageAnnotatorGrpcTransport +from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport + + +class ImageAnnotatorClientMeta(type): + """Metaclass for the ImageAnnotator client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[ImageAnnotatorTransport]] + _transport_registry["grpc"] = ImageAnnotatorGrpcTransport + _transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[ImageAnnotatorTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ImageAnnotatorClient(metaclass=ImageAnnotatorClientMeta): + """Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "vision.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + def __init__( + self, + *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, ImageAnnotatorTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the image annotator client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ImageAnnotatorTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ImageAnnotatorTransport): + # transport is a ImageAnnotatorTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def batch_annotate_images( + self, + request: image_annotator.BatchAnnotateImagesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateImageRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: + r"""Run image detection and annotation for a batch of + images. + + Args: + request (:class:`~.image_annotator.BatchAnnotateImagesRequest`): + The request object. Multiple image annotation requests + are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AnnotateImageRequest]`): + Individual image annotation requests + for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.image_annotator.BatchAnnotateImagesResponse: + Response to a batch image annotation + request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([requests]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a image_annotator.BatchAnnotateImagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, image_annotator.BatchAnnotateImagesRequest): + request = image_annotator.BatchAnnotateImagesRequest(request) + if requests is not None: + for i in range(len(requests)): + requests[i] = image_annotator.AnnotateImageRequest(requests[i]) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_annotate_images] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def async_batch_annotate_files( + self, + request: image_annotator.AsyncBatchAnnotateFilesRequest = None, + *, + requests: Sequence[image_annotator.AsyncAnnotateFileRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Run asynchronous image detection and annotation for a list of + generic files, such as PDF files, which may contain multiple + pages and multiple images per page. Progress and results can be + retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateFilesResponse`` (results). + + Args: + request (:class:`~.image_annotator.AsyncBatchAnnotateFilesRequest`): + The request object. Multiple async file annotation + requests are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AsyncAnnotateFileRequest]`): + Required. Individual async file + annotation requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.image_annotator.AsyncBatchAnnotateFilesResponse``: + Response to an async batch file annotation request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([requests]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a image_annotator.AsyncBatchAnnotateFilesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, image_annotator.AsyncBatchAnnotateFilesRequest): + request = image_annotator.AsyncBatchAnnotateFilesRequest(request) + if requests is not None: + for i in range(len(requests)): + requests[i] = image_annotator.AsyncAnnotateFileRequest(requests[i]) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.async_batch_annotate_files + ] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + image_annotator.AsyncBatchAnnotateFilesResponse, + metadata_type=image_annotator.OperationMetadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ImageAnnotatorClient",) diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/__init__.py b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/__init__.py new file mode 100644 index 00000000..f2315e0d --- /dev/null +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import ImageAnnotatorTransport +from .grpc import ImageAnnotatorGrpcTransport +from .grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ImageAnnotatorTransport]] +_transport_registry["grpc"] = ImageAnnotatorGrpcTransport +_transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport + + +__all__ = ( + "ImageAnnotatorTransport", + "ImageAnnotatorGrpcTransport", + "ImageAnnotatorGrpcAsyncIOTransport", +) diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py new file mode 100644 index 00000000..f5955bab --- /dev/null +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py @@ -0,0 +1,165 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.vision_v1p3beta1.types import image_annotator +from google.longrunning import operations_pb2 as operations # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ImageAnnotatorTransport(abc.ABC): + """Abstract transport class for ImageAnnotator.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ) + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.batch_annotate_images: gapic_v1.method.wrap_method( + self.batch_annotate_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.async_batch_annotate_files: gapic_v1.method.wrap_method( + self.async_batch_annotate_files, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def batch_annotate_images( + self, + ) -> typing.Callable[ + [image_annotator.BatchAnnotateImagesRequest], + typing.Union[ + image_annotator.BatchAnnotateImagesResponse, + typing.Awaitable[image_annotator.BatchAnnotateImagesResponse], + ], + ]: + raise NotImplementedError() + + @property + def async_batch_annotate_files( + self, + ) -> typing.Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + +__all__ = ("ImageAnnotatorTransport",) diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py new file mode 100644 index 00000000..398731df --- /dev/null +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py @@ -0,0 +1,318 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.vision_v1p3beta1.types import image_annotator +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO + + +class ImageAnnotatorGrpcTransport(ImageAnnotatorTransport): + """gRPC backend transport for ImageAnnotator. + + Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def batch_annotate_images( + self, + ) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + image_annotator.BatchAnnotateImagesResponse, + ]: + r"""Return a callable for the batch annotate images method over gRPC. + + Run image detection and annotation for a batch of + images. + + Returns: + Callable[[~.BatchAnnotateImagesRequest], + ~.BatchAnnotateImagesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_annotate_images" not in self._stubs: + self._stubs["batch_annotate_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ImageAnnotator/BatchAnnotateImages", + request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, + response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, + ) + return self._stubs["batch_annotate_images"] + + @property + def async_batch_annotate_files( + self, + ) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], operations.Operation + ]: + r"""Return a callable for the async batch annotate files method over gRPC. + + Run asynchronous image detection and annotation for a list of + generic files, such as PDF files, which may contain multiple + pages and multiple images per page. Progress and results can be + retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateFilesResponse`` (results). + + Returns: + Callable[[~.AsyncBatchAnnotateFilesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "async_batch_annotate_files" not in self._stubs: + self._stubs["async_batch_annotate_files"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ImageAnnotator/AsyncBatchAnnotateFiles", + request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["async_batch_annotate_files"] + + +__all__ = ("ImageAnnotatorGrpcTransport",) diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc_asyncio.py b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc_asyncio.py new file mode 100644 index 00000000..111165e8 --- /dev/null +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc_asyncio.py @@ -0,0 +1,319 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.vision_v1p3beta1.types import image_annotator +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .grpc import ImageAnnotatorGrpcTransport + + +class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): + """gRPC AsyncIO backend transport for ImageAnnotator. + + Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def batch_annotate_images( + self, + ) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + Awaitable[image_annotator.BatchAnnotateImagesResponse], + ]: + r"""Return a callable for the batch annotate images method over gRPC. + + Run image detection and annotation for a batch of + images. + + Returns: + Callable[[~.BatchAnnotateImagesRequest], + Awaitable[~.BatchAnnotateImagesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_annotate_images" not in self._stubs: + self._stubs["batch_annotate_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ImageAnnotator/BatchAnnotateImages", + request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, + response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, + ) + return self._stubs["batch_annotate_images"] + + @property + def async_batch_annotate_files( + self, + ) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + Awaitable[operations.Operation], + ]: + r"""Return a callable for the async batch annotate files method over gRPC. + + Run asynchronous image detection and annotation for a list of + generic files, such as PDF files, which may contain multiple + pages and multiple images per page. Progress and results can be + retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateFilesResponse`` (results). + + Returns: + Callable[[~.AsyncBatchAnnotateFilesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "async_batch_annotate_files" not in self._stubs: + self._stubs["async_batch_annotate_files"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ImageAnnotator/AsyncBatchAnnotateFiles", + request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["async_batch_annotate_files"] + + +__all__ = ("ImageAnnotatorGrpcAsyncIOTransport",) diff --git a/google/cloud/vision_v1p3beta1/services/product_search/__init__.py b/google/cloud/vision_v1p3beta1/services/product_search/__init__.py new file mode 100644 index 00000000..e82b5909 --- /dev/null +++ b/google/cloud/vision_v1p3beta1/services/product_search/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import ProductSearchClient +from .async_client import ProductSearchAsyncClient + +__all__ = ( + "ProductSearchClient", + "ProductSearchAsyncClient", +) diff --git a/google/cloud/vision_v1p3beta1/services/product_search/async_client.py b/google/cloud/vision_v1p3beta1/services/product_search/async_client.py new file mode 100644 index 00000000..1537b605 --- /dev/null +++ b/google/cloud/vision_v1p3beta1/services/product_search/async_client.py @@ -0,0 +1,1878 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1p3beta1.services.product_search import pagers +from google.cloud.vision_v1p3beta1.types import geometry +from google.cloud.vision_v1p3beta1.types import product_search_service +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + +from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport +from .client import ProductSearchClient + + +class ProductSearchAsyncClient: + """Manages Products and ProductSets of reference images for use in + product search. It uses the following resource model: + + - The API has a collection of + [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. + + In parallel, + + - The API has a collection of + [Product][google.cloud.vision.v1p3beta1.Product] resources, named + ``projects/*/locations/*/products/*`` + + - Each [Product][google.cloud.vision.v1p3beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` + """ + + _client: ProductSearchClient + + DEFAULT_ENDPOINT = ProductSearchClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProductSearchClient.DEFAULT_MTLS_ENDPOINT + + product_path = staticmethod(ProductSearchClient.product_path) + parse_product_path = staticmethod(ProductSearchClient.parse_product_path) + product_set_path = staticmethod(ProductSearchClient.product_set_path) + parse_product_set_path = staticmethod(ProductSearchClient.parse_product_set_path) + reference_image_path = staticmethod(ProductSearchClient.reference_image_path) + parse_reference_image_path = staticmethod( + ProductSearchClient.parse_reference_image_path + ) + + from_service_account_file = ProductSearchClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(ProductSearchClient).get_transport_class, type(ProductSearchClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, ProductSearchTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the product search client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProductSearchTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = ProductSearchClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def create_product_set( + self, + request: product_search_service.CreateProductSetRequest = None, + *, + parent: str = None, + product_set: product_search_service.ProductSet = None, + product_set_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Creates and returns a new ProductSet resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. + + Args: + request (:class:`~.product_search_service.CreateProductSetRequest`): + The request object. Request message for the + `CreateProductSet` method. + parent (:class:`str`): + Required. The project in which the ProductSet should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_set (:class:`~.product_search_service.ProductSet`): + Required. The ProductSet to create. + This corresponds to the ``product_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_set_id (:class:`str`): + A user-supplied resource id for this ProductSet. If set, + the server will attempt to use this value as the + resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``product_set_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, product_set, product_set_id]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.CreateProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if product_set is not None: + request.product_set = product_set + if product_set_id is not None: + request.product_set_id = product_set_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_product_sets( + self, + request: product_search_service.ListProductSetsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductSetsAsyncPager: + r"""Lists ProductSets in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductSetsRequest`): + The request object. Request message for the + `ListProductSets` method. + parent (:class:`str`): + Required. The project from which ProductSets should be + listed. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductSetsAsyncPager: + Response message for the ``ListProductSets`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.ListProductSetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_product_sets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductSetsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_product_set( + self, + request: product_search_service.GetProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Gets information associated with a ProductSet. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + + Args: + request (:class:`~.product_search_service.GetProductSetRequest`): + The request object. Request message for the + `GetProductSet` method. + name (:class:`str`): + Required. Resource name of the ProductSet to get. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.GetProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_product_set( + self, + request: product_search_service.UpdateProductSetRequest = None, + *, + product_set: product_search_service.ProductSet = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Makes changes to a ProductSet resource. Only display_name can be + updated currently. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. + + Args: + request (:class:`~.product_search_service.UpdateProductSetRequest`): + The request object. Request message for the + `UpdateProductSet` method. + product_set (:class:`~.product_search_service.ProductSet`): + Required. The ProductSet resource + which replaces the one on the server. + This corresponds to the ``product_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The [FieldMask][google.protobuf.FieldMask] that + specifies which fields to update. If update_mask isn't + specified, all mutable fields are to be updated. Valid + mask path is ``display_name``. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([product_set, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.UpdateProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if product_set is not None: + request.product_set = product_set + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("product_set.name", request.product_set.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_product_set( + self, + request: product_search_service.DeleteProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a ProductSet. All Products and + ReferenceImages in the ProductSet will be deleted. + + The actual image files are not deleted from Google Cloud + Storage. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + + Args: + request (:class:`~.product_search_service.DeleteProductSetRequest`): + The request object. Request message for the + `DeleteProductSet` method. + name (:class:`str`): + Required. Resource name of the ProductSet to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.DeleteProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def create_product( + self, + request: product_search_service.CreateProductRequest = None, + *, + parent: str = None, + product: product_search_service.Product = None, + product_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Creates and returns a new product resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. + + Args: + request (:class:`~.product_search_service.CreateProductRequest`): + The request object. Request message for the + `CreateProduct` method. + parent (:class:`str`): + Required. The project in which the Product should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`~.product_search_service.Product`): + Required. The product to create. + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (:class:`str`): + A user-supplied resource id for this Product. If set, + the server will attempt to use this value as the + resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``product_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, product, product_id]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.CreateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_products( + self, + request: product_search_service.ListProductsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsAsyncPager: + r"""Lists products in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductsRequest`): + The request object. Request message for the + `ListProducts` method. + parent (:class:`str`): + Required. The project OR ProductSet from which Products + should be listed. + + Format: ``projects/PROJECT_ID/locations/LOC_ID`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductsAsyncPager: + Response message for the ``ListProducts`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.ListProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_products, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_product( + self, + request: product_search_service.GetProductRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Gets information associated with a Product. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + + Args: + request (:class:`~.product_search_service.GetProductRequest`): + The request object. Request message for the `GetProduct` + method. + name (:class:`str`): + Required. Resource name of the Product to get. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.GetProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_product( + self, + request: product_search_service.UpdateProductRequest = None, + *, + product: product_search_service.Product = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Makes changes to a Product resource. Only display_name, + description and labels can be updated right now. + + If labels are updated, the change will not be reflected in + queries until the next index time. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. + + Args: + request (:class:`~.product_search_service.UpdateProductRequest`): + The request object. Request message for the + `UpdateProduct` method. + product (:class:`~.product_search_service.Product`): + Required. The Product resource which + replaces the one on the server. + product.name is immutable. + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The [FieldMask][google.protobuf.FieldMask] that + specifies which fields to update. If update_mask isn't + specified, all mutable fields are to be updated. Valid + mask paths include ``product_labels``, ``display_name``, + and ``description``. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([product, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.UpdateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if product is not None: + request.product = product + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("product.name", request.product.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_product( + self, + request: product_search_service.DeleteProductRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a product and its reference images. + + Metadata of the product and all its images will be deleted right + away, but search queries against ProductSets containing the + product may still work until all related caches are refreshed. + + Possible errors: + + - Returns NOT_FOUND if the product does not exist. + + Args: + request (:class:`~.product_search_service.DeleteProductRequest`): + The request object. Request message for the + `DeleteProduct` method. + name (:class:`str`): + Required. Resource name of product to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.DeleteProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def create_reference_image( + self, + request: product_search_service.CreateReferenceImageRequest = None, + *, + parent: str = None, + reference_image: product_search_service.ReferenceImage = None, + reference_image_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ReferenceImage: + r"""Creates and returns a new ReferenceImage resource. + + The ``bounding_poly`` field is optional. If ``bounding_poly`` is + not specified, the system will try to detect regions of interest + in the image that are compatible with the product_category on + the parent product. If it is specified, detection is ALWAYS + skipped. The system converts polygons into non-rotated + rectangles. + + Note that the pipeline will resize the image if the image + resolution is too large to process (above 50MP). + + Possible errors: + + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. + + Args: + request (:class:`~.product_search_service.CreateReferenceImageRequest`): + The request object. Request message for the + `CreateReferenceImage` method. + parent (:class:`str`): + Required. Resource name of the product in which to + create the reference image. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reference_image (:class:`~.product_search_service.ReferenceImage`): + Required. The reference image to + create. If an image ID is specified, it + is ignored. + This corresponds to the ``reference_image`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reference_image_id (:class:`str`): + A user-supplied resource id for the ReferenceImage to be + added. If set, the server will attempt to use this value + as the resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``reference_image_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ReferenceImage: + A ``ReferenceImage`` represents a product image and its + associated metadata, such as bounding boxes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, reference_image, reference_image_id]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.CreateReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if reference_image is not None: + request.reference_image = reference_image + if reference_image_id is not None: + request.reference_image_id = reference_image_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_reference_image( + self, + request: product_search_service.DeleteReferenceImageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a reference image. + + The image metadata will be deleted right away, but search + queries against ProductSets containing the image may still work + until all related caches are refreshed. + + The actual image files are not deleted from Google Cloud + Storage. + + Possible errors: + + - Returns NOT_FOUND if the reference image does not exist. + + Args: + request (:class:`~.product_search_service.DeleteReferenceImageRequest`): + The request object. Request message for the + `DeleteReferenceImage` method. + name (:class:`str`): + Required. The resource name of the reference image to + delete. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.DeleteReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def list_reference_images( + self, + request: product_search_service.ListReferenceImagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListReferenceImagesAsyncPager: + r"""Lists reference images. + + Possible errors: + + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. + + Args: + request (:class:`~.product_search_service.ListReferenceImagesRequest`): + The request object. Request message for the + `ListReferenceImages` method. + parent (:class:`str`): + Required. Resource name of the product containing the + reference images. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListReferenceImagesAsyncPager: + Response message for the ``ListReferenceImages`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.ListReferenceImagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_reference_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListReferenceImagesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_reference_image( + self, + request: product_search_service.GetReferenceImageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ReferenceImage: + r"""Gets information associated with a ReferenceImage. + + Possible errors: + + - Returns NOT_FOUND if the specified image does not exist. + + Args: + request (:class:`~.product_search_service.GetReferenceImageRequest`): + The request object. Request message for the + `GetReferenceImage` method. + name (:class:`str`): + Required. The resource name of the ReferenceImage to + get. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ReferenceImage: + A ``ReferenceImage`` represents a product image and its + associated metadata, such as bounding boxes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.GetReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def add_product_to_product_set( + self, + request: product_search_service.AddProductToProductSetRequest = None, + *, + name: str = None, + product: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Adds a Product to the specified ProductSet. If the Product is + already present, no change is made. + + One Product can be added to at most 100 ProductSets. + + Possible errors: + + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. + + Args: + request (:class:`~.product_search_service.AddProductToProductSetRequest`): + The request object. Request message for the + `AddProductToProductSet` method. + name (:class:`str`): + Required. The resource name for the ProductSet to + modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`str`): + Required. The resource name for the Product to be added + to this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name, product]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.AddProductToProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_product_to_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def remove_product_from_product_set( + self, + request: product_search_service.RemoveProductFromProductSetRequest = None, + *, + name: str = None, + product: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Removes a Product from the specified ProductSet. + + Possible errors: + + - Returns NOT_FOUND If the Product is not found under the + ProductSet. + + Args: + request (:class:`~.product_search_service.RemoveProductFromProductSetRequest`): + The request object. Request message for the + `RemoveProductFromProductSet` method. + name (:class:`str`): + Required. The resource name for the ProductSet to + modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`str`): + Required. The resource name for the Product to be + removed from this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name, product]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.RemoveProductFromProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_product_from_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def list_products_in_product_set( + self, + request: product_search_service.ListProductsInProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsInProductSetAsyncPager: + r"""Lists the Products in a ProductSet, in an unspecified order. If + the ProductSet does not exist, the products field of the + response will be empty. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductsInProductSetRequest`): + The request object. Request message for the + `ListProductsInProductSet` method. + name (:class:`str`): + Required. The ProductSet resource for which to retrieve + Products. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductsInProductSetAsyncPager: + Response message for the ``ListProductsInProductSet`` + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.ListProductsInProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_products_in_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductsInProductSetAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_product_sets( + self, + request: product_search_service.ImportProductSetsRequest = None, + *, + parent: str = None, + input_config: product_search_service.ImportProductSetsInputConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Asynchronous API that imports a list of reference images to + specified product sets based on a list of image information. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) ``Operation.response`` + contains ``ImportProductSetsResponse``. (results) + + The input source of this method is a csv file on Google Cloud + Storage. For the format of the csv file please see + [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1p3beta1.ImportProductSetsGcsSource.csv_file_uri]. + + Args: + request (:class:`~.product_search_service.ImportProductSetsRequest`): + The request object. Request message for the + `ImportProductSets` method. + parent (:class:`str`): + Required. The project in which the ProductSets should be + imported. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + input_config (:class:`~.product_search_service.ImportProductSetsInputConfig`): + Required. The input content for the + list of requests. + This corresponds to the ``input_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.product_search_service.ImportProductSetsResponse``: + Response message for the ``ImportProductSets`` method. + + This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, input_config]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.ImportProductSetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if input_config is not None: + request.input_config = input_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_product_sets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + product_search_service.ImportProductSetsResponse, + metadata_type=product_search_service.BatchOperationMetadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ProductSearchAsyncClient",) diff --git a/google/cloud/vision_v1p3beta1/services/product_search/client.py b/google/cloud/vision_v1p3beta1/services/product_search/client.py new file mode 100644 index 00000000..87e4dceb --- /dev/null +++ b/google/cloud/vision_v1p3beta1/services/product_search/client.py @@ -0,0 +1,1988 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1p3beta1.services.product_search import pagers +from google.cloud.vision_v1p3beta1.types import geometry +from google.cloud.vision_v1p3beta1.types import product_search_service +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + +from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProductSearchGrpcTransport +from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport + + +class ProductSearchClientMeta(type): + """Metaclass for the ProductSearch client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[ProductSearchTransport]] + _transport_registry["grpc"] = ProductSearchGrpcTransport + _transport_registry["grpc_asyncio"] = ProductSearchGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[ProductSearchTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ProductSearchClient(metaclass=ProductSearchClientMeta): + """Manages Products and ProductSets of reference images for use in + product search. It uses the following resource model: + + - The API has a collection of + [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. + + In parallel, + + - The API has a collection of + [Product][google.cloud.vision.v1p3beta1.Product] resources, named + ``projects/*/locations/*/products/*`` + + - Each [Product][google.cloud.vision.v1p3beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "vision.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def product_path(project: str, location: str, product: str,) -> str: + """Return a fully-qualified product string.""" + return "projects/{project}/locations/{location}/products/{product}".format( + project=project, location=location, product=product, + ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str, str]: + """Parse a product path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def product_set_path(project: str, location: str, product_set: str,) -> str: + """Return a fully-qualified product_set string.""" + return "projects/{project}/locations/{location}/productSets/{product_set}".format( + project=project, location=location, product_set=product_set, + ) + + @staticmethod + def parse_product_set_path(path: str) -> Dict[str, str]: + """Parse a product_set path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def reference_image_path( + project: str, location: str, product: str, reference_image: str, + ) -> str: + """Return a fully-qualified reference_image string.""" + return "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( + project=project, + location=location, + product=product, + reference_image=reference_image, + ) + + @staticmethod + def parse_reference_image_path(path: str) -> Dict[str, str]: + """Parse a reference_image path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)/referenceImages/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, ProductSearchTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the product search client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProductSearchTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ProductSearchTransport): + # transport is a ProductSearchTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def create_product_set( + self, + request: product_search_service.CreateProductSetRequest = None, + *, + parent: str = None, + product_set: product_search_service.ProductSet = None, + product_set_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Creates and returns a new ProductSet resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. + + Args: + request (:class:`~.product_search_service.CreateProductSetRequest`): + The request object. Request message for the + `CreateProductSet` method. + parent (:class:`str`): + Required. The project in which the ProductSet should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_set (:class:`~.product_search_service.ProductSet`): + Required. The ProductSet to create. + This corresponds to the ``product_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_set_id (:class:`str`): + A user-supplied resource id for this ProductSet. If set, + the server will attempt to use this value as the + resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``product_set_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product_set, product_set_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.CreateProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.CreateProductSetRequest): + request = product_search_service.CreateProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if product_set is not None: + request.product_set = product_set + if product_set_id is not None: + request.product_set_id = product_set_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_product_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_product_sets( + self, + request: product_search_service.ListProductSetsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductSetsPager: + r"""Lists ProductSets in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductSetsRequest`): + The request object. Request message for the + `ListProductSets` method. + parent (:class:`str`): + Required. The project from which ProductSets should be + listed. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductSetsPager: + Response message for the ``ListProductSets`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.ListProductSetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.ListProductSetsRequest): + request = product_search_service.ListProductSetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_product_sets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductSetsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_product_set( + self, + request: product_search_service.GetProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Gets information associated with a ProductSet. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + + Args: + request (:class:`~.product_search_service.GetProductSetRequest`): + The request object. Request message for the + `GetProductSet` method. + name (:class:`str`): + Required. Resource name of the ProductSet to get. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.GetProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.GetProductSetRequest): + request = product_search_service.GetProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_product_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_product_set( + self, + request: product_search_service.UpdateProductSetRequest = None, + *, + product_set: product_search_service.ProductSet = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Makes changes to a ProductSet resource. Only display_name can be + updated currently. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. + + Args: + request (:class:`~.product_search_service.UpdateProductSetRequest`): + The request object. Request message for the + `UpdateProductSet` method. + product_set (:class:`~.product_search_service.ProductSet`): + Required. The ProductSet resource + which replaces the one on the server. + This corresponds to the ``product_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The [FieldMask][google.protobuf.FieldMask] that + specifies which fields to update. If update_mask isn't + specified, all mutable fields are to be updated. Valid + mask path is ``display_name``. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product_set, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.UpdateProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.UpdateProductSetRequest): + request = product_search_service.UpdateProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if product_set is not None: + request.product_set = product_set + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_product_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("product_set.name", request.product_set.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_product_set( + self, + request: product_search_service.DeleteProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a ProductSet. All Products and + ReferenceImages in the ProductSet will be deleted. + + The actual image files are not deleted from Google Cloud + Storage. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + + Args: + request (:class:`~.product_search_service.DeleteProductSetRequest`): + The request object. Request message for the + `DeleteProductSet` method. + name (:class:`str`): + Required. Resource name of the ProductSet to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.DeleteProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.DeleteProductSetRequest): + request = product_search_service.DeleteProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_product_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def create_product( + self, + request: product_search_service.CreateProductRequest = None, + *, + parent: str = None, + product: product_search_service.Product = None, + product_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Creates and returns a new product resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. + + Args: + request (:class:`~.product_search_service.CreateProductRequest`): + The request object. Request message for the + `CreateProduct` method. + parent (:class:`str`): + Required. The project in which the Product should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`~.product_search_service.Product`): + Required. The product to create. + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (:class:`str`): + A user-supplied resource id for this Product. If set, + the server will attempt to use this value as the + resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``product_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.CreateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.CreateProductRequest): + request = product_search_service.CreateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_products( + self, + request: product_search_service.ListProductsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsPager: + r"""Lists products in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductsRequest`): + The request object. Request message for the + `ListProducts` method. + parent (:class:`str`): + Required. The project OR ProductSet from which Products + should be listed. + + Format: ``projects/PROJECT_ID/locations/LOC_ID`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductsPager: + Response message for the ``ListProducts`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.ListProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.ListProductsRequest): + request = product_search_service.ListProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_product( + self, + request: product_search_service.GetProductRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Gets information associated with a Product. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + + Args: + request (:class:`~.product_search_service.GetProductRequest`): + The request object. Request message for the `GetProduct` + method. + name (:class:`str`): + Required. Resource name of the Product to get. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.GetProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.GetProductRequest): + request = product_search_service.GetProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_product( + self, + request: product_search_service.UpdateProductRequest = None, + *, + product: product_search_service.Product = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Makes changes to a Product resource. Only display_name, + description and labels can be updated right now. + + If labels are updated, the change will not be reflected in + queries until the next index time. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. + + Args: + request (:class:`~.product_search_service.UpdateProductRequest`): + The request object. Request message for the + `UpdateProduct` method. + product (:class:`~.product_search_service.Product`): + Required. The Product resource which + replaces the one on the server. + product.name is immutable. + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The [FieldMask][google.protobuf.FieldMask] that + specifies which fields to update. If update_mask isn't + specified, all mutable fields are to be updated. Valid + mask paths include ``product_labels``, ``display_name``, + and ``description``. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.UpdateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.UpdateProductRequest): + request = product_search_service.UpdateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if product is not None: + request.product = product + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("product.name", request.product.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_product( + self, + request: product_search_service.DeleteProductRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a product and its reference images. + + Metadata of the product and all its images will be deleted right + away, but search queries against ProductSets containing the + product may still work until all related caches are refreshed. + + Possible errors: + + - Returns NOT_FOUND if the product does not exist. + + Args: + request (:class:`~.product_search_service.DeleteProductRequest`): + The request object. Request message for the + `DeleteProduct` method. + name (:class:`str`): + Required. Resource name of product to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.DeleteProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.DeleteProductRequest): + request = product_search_service.DeleteProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def create_reference_image( + self, + request: product_search_service.CreateReferenceImageRequest = None, + *, + parent: str = None, + reference_image: product_search_service.ReferenceImage = None, + reference_image_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ReferenceImage: + r"""Creates and returns a new ReferenceImage resource. + + The ``bounding_poly`` field is optional. If ``bounding_poly`` is + not specified, the system will try to detect regions of interest + in the image that are compatible with the product_category on + the parent product. If it is specified, detection is ALWAYS + skipped. The system converts polygons into non-rotated + rectangles. + + Note that the pipeline will resize the image if the image + resolution is too large to process (above 50MP). + + Possible errors: + + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. + + Args: + request (:class:`~.product_search_service.CreateReferenceImageRequest`): + The request object. Request message for the + `CreateReferenceImage` method. + parent (:class:`str`): + Required. Resource name of the product in which to + create the reference image. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reference_image (:class:`~.product_search_service.ReferenceImage`): + Required. The reference image to + create. If an image ID is specified, it + is ignored. + This corresponds to the ``reference_image`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reference_image_id (:class:`str`): + A user-supplied resource id for the ReferenceImage to be + added. If set, the server will attempt to use this value + as the resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``reference_image_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ReferenceImage: + A ``ReferenceImage`` represents a product image and its + associated metadata, such as bounding boxes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, reference_image, reference_image_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.CreateReferenceImageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.CreateReferenceImageRequest): + request = product_search_service.CreateReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if reference_image is not None: + request.reference_image = reference_image + if reference_image_id is not None: + request.reference_image_id = reference_image_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_reference_image] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_reference_image( + self, + request: product_search_service.DeleteReferenceImageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a reference image. + + The image metadata will be deleted right away, but search + queries against ProductSets containing the image may still work + until all related caches are refreshed. + + The actual image files are not deleted from Google Cloud + Storage. + + Possible errors: + + - Returns NOT_FOUND if the reference image does not exist. + + Args: + request (:class:`~.product_search_service.DeleteReferenceImageRequest`): + The request object. Request message for the + `DeleteReferenceImage` method. + name (:class:`str`): + Required. The resource name of the reference image to + delete. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.DeleteReferenceImageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.DeleteReferenceImageRequest): + request = product_search_service.DeleteReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_reference_image] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def list_reference_images( + self, + request: product_search_service.ListReferenceImagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListReferenceImagesPager: + r"""Lists reference images. + + Possible errors: + + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. + + Args: + request (:class:`~.product_search_service.ListReferenceImagesRequest`): + The request object. Request message for the + `ListReferenceImages` method. + parent (:class:`str`): + Required. Resource name of the product containing the + reference images. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListReferenceImagesPager: + Response message for the ``ListReferenceImages`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.ListReferenceImagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.ListReferenceImagesRequest): + request = product_search_service.ListReferenceImagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_reference_images] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListReferenceImagesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_reference_image( + self, + request: product_search_service.GetReferenceImageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ReferenceImage: + r"""Gets information associated with a ReferenceImage. + + Possible errors: + + - Returns NOT_FOUND if the specified image does not exist. + + Args: + request (:class:`~.product_search_service.GetReferenceImageRequest`): + The request object. Request message for the + `GetReferenceImage` method. + name (:class:`str`): + Required. The resource name of the ReferenceImage to + get. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ReferenceImage: + A ``ReferenceImage`` represents a product image and its + associated metadata, such as bounding boxes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.GetReferenceImageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.GetReferenceImageRequest): + request = product_search_service.GetReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_reference_image] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def add_product_to_product_set( + self, + request: product_search_service.AddProductToProductSetRequest = None, + *, + name: str = None, + product: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Adds a Product to the specified ProductSet. If the Product is + already present, no change is made. + + One Product can be added to at most 100 ProductSets. + + Possible errors: + + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. + + Args: + request (:class:`~.product_search_service.AddProductToProductSetRequest`): + The request object. Request message for the + `AddProductToProductSet` method. + name (:class:`str`): + Required. The resource name for the ProductSet to + modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`str`): + Required. The resource name for the Product to be added + to this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, product]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.AddProductToProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, product_search_service.AddProductToProductSetRequest + ): + request = product_search_service.AddProductToProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.add_product_to_product_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def remove_product_from_product_set( + self, + request: product_search_service.RemoveProductFromProductSetRequest = None, + *, + name: str = None, + product: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Removes a Product from the specified ProductSet. + + Possible errors: + + - Returns NOT_FOUND If the Product is not found under the + ProductSet. + + Args: + request (:class:`~.product_search_service.RemoveProductFromProductSetRequest`): + The request object. Request message for the + `RemoveProductFromProductSet` method. + name (:class:`str`): + Required. The resource name for the ProductSet to + modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`str`): + Required. The resource name for the Product to be + removed from this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, product]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.RemoveProductFromProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, product_search_service.RemoveProductFromProductSetRequest + ): + request = product_search_service.RemoveProductFromProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.remove_product_from_product_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def list_products_in_product_set( + self, + request: product_search_service.ListProductsInProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsInProductSetPager: + r"""Lists the Products in a ProductSet, in an unspecified order. If + the ProductSet does not exist, the products field of the + response will be empty. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductsInProductSetRequest`): + The request object. Request message for the + `ListProductsInProductSet` method. + name (:class:`str`): + Required. The ProductSet resource for which to retrieve + Products. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductsInProductSetPager: + Response message for the ``ListProductsInProductSet`` + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.ListProductsInProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, product_search_service.ListProductsInProductSetRequest + ): + request = product_search_service.ListProductsInProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_products_in_product_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductsInProductSetPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def import_product_sets( + self, + request: product_search_service.ImportProductSetsRequest = None, + *, + parent: str = None, + input_config: product_search_service.ImportProductSetsInputConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Asynchronous API that imports a list of reference images to + specified product sets based on a list of image information. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) ``Operation.response`` + contains ``ImportProductSetsResponse``. (results) + + The input source of this method is a csv file on Google Cloud + Storage. For the format of the csv file please see + [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1p3beta1.ImportProductSetsGcsSource.csv_file_uri]. + + Args: + request (:class:`~.product_search_service.ImportProductSetsRequest`): + The request object. Request message for the + `ImportProductSets` method. + parent (:class:`str`): + Required. The project in which the ProductSets should be + imported. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + input_config (:class:`~.product_search_service.ImportProductSetsInputConfig`): + Required. The input content for the + list of requests. + This corresponds to the ``input_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.product_search_service.ImportProductSetsResponse``: + Response message for the ``ImportProductSets`` method. + + This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, input_config]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.ImportProductSetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.ImportProductSetsRequest): + request = product_search_service.ImportProductSetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if input_config is not None: + request.input_config = input_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_product_sets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + product_search_service.ImportProductSetsResponse, + metadata_type=product_search_service.BatchOperationMetadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ProductSearchClient",) diff --git a/google/cloud/vision_v1p3beta1/services/product_search/pagers.py b/google/cloud/vision_v1p3beta1/services/product_search/pagers.py new file mode 100644 index 00000000..85829a6e --- /dev/null +++ b/google/cloud/vision_v1p3beta1/services/product_search/pagers.py @@ -0,0 +1,546 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.vision_v1p3beta1.types import product_search_service + + +class ListProductSetsPager: + """A pager for iterating through ``list_product_sets`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductSetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``product_sets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProductSets`` requests and continue to iterate + through the ``product_sets`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductSetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., product_search_service.ListProductSetsResponse], + request: product_search_service.ListProductSetsRequest, + response: product_search_service.ListProductSetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductSetsRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductSetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductSetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[product_search_service.ListProductSetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[product_search_service.ProductSet]: + for page in self.pages: + yield from page.product_sets + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListProductSetsAsyncPager: + """A pager for iterating through ``list_product_sets`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductSetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``product_sets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProductSets`` requests and continue to iterate + through the ``product_sets`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductSetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[product_search_service.ListProductSetsResponse] + ], + request: product_search_service.ListProductSetsRequest, + response: product_search_service.ListProductSetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductSetsRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductSetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductSetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[product_search_service.ListProductSetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[product_search_service.ProductSet]: + async def async_generator(): + async for page in self.pages: + for response in page.product_sets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListProductsPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., product_search_service.ListProductsResponse], + request: product_search_service.ListProductsRequest, + response: product_search_service.ListProductsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductsRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[product_search_service.ListProductsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[product_search_service.Product]: + for page in self.pages: + yield from page.products + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListProductsAsyncPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[product_search_service.ListProductsResponse]], + request: product_search_service.ListProductsRequest, + response: product_search_service.ListProductsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductsRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[product_search_service.ListProductsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[product_search_service.Product]: + async def async_generator(): + async for page in self.pages: + for response in page.products: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListReferenceImagesPager: + """A pager for iterating through ``list_reference_images`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListReferenceImagesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``reference_images`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListReferenceImages`` requests and continue to iterate + through the ``reference_images`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListReferenceImagesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., product_search_service.ListReferenceImagesResponse], + request: product_search_service.ListReferenceImagesRequest, + response: product_search_service.ListReferenceImagesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListReferenceImagesRequest`): + The initial request object. + response (:class:`~.product_search_service.ListReferenceImagesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListReferenceImagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[product_search_service.ListReferenceImagesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[product_search_service.ReferenceImage]: + for page in self.pages: + yield from page.reference_images + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListReferenceImagesAsyncPager: + """A pager for iterating through ``list_reference_images`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListReferenceImagesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``reference_images`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListReferenceImages`` requests and continue to iterate + through the ``reference_images`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListReferenceImagesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[product_search_service.ListReferenceImagesResponse] + ], + request: product_search_service.ListReferenceImagesRequest, + response: product_search_service.ListReferenceImagesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListReferenceImagesRequest`): + The initial request object. + response (:class:`~.product_search_service.ListReferenceImagesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListReferenceImagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[product_search_service.ListReferenceImagesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[product_search_service.ReferenceImage]: + async def async_generator(): + async for page in self.pages: + for response in page.reference_images: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListProductsInProductSetPager: + """A pager for iterating through ``list_products_in_product_set`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductsInProductSetResponse` object, and + provides an ``__iter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProductsInProductSet`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductsInProductSetResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., product_search_service.ListProductsInProductSetResponse], + request: product_search_service.ListProductsInProductSetRequest, + response: product_search_service.ListProductsInProductSetResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductsInProductSetRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductsInProductSetResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductsInProductSetRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterable[product_search_service.ListProductsInProductSetResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[product_search_service.Product]: + for page in self.pages: + yield from page.products + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListProductsInProductSetAsyncPager: + """A pager for iterating through ``list_products_in_product_set`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductsInProductSetResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProductsInProductSet`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductsInProductSetResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[product_search_service.ListProductsInProductSetResponse] + ], + request: product_search_service.ListProductsInProductSetRequest, + response: product_search_service.ListProductsInProductSetResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductsInProductSetRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductsInProductSetResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductsInProductSetRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[product_search_service.ListProductsInProductSetResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[product_search_service.Product]: + async def async_generator(): + async for page in self.pages: + for response in page.products: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/vision_v1p3beta1/services/product_search/transports/__init__.py b/google/cloud/vision_v1p3beta1/services/product_search/transports/__init__.py new file mode 100644 index 00000000..2d57de48 --- /dev/null +++ b/google/cloud/vision_v1p3beta1/services/product_search/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import ProductSearchTransport +from .grpc import ProductSearchGrpcTransport +from .grpc_asyncio import ProductSearchGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProductSearchTransport]] +_transport_registry["grpc"] = ProductSearchGrpcTransport +_transport_registry["grpc_asyncio"] = ProductSearchGrpcAsyncIOTransport + + +__all__ = ( + "ProductSearchTransport", + "ProductSearchGrpcTransport", + "ProductSearchGrpcAsyncIOTransport", +) diff --git a/google/cloud/vision_v1p3beta1/services/product_search/transports/base.py b/google/cloud/vision_v1p3beta1/services/product_search/transports/base.py new file mode 100644 index 00000000..2b219f8b --- /dev/null +++ b/google/cloud/vision_v1p3beta1/services/product_search/transports/base.py @@ -0,0 +1,537 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.vision_v1p3beta1.types import product_search_service +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ProductSearchTransport(abc.ABC): + """Abstract transport class for ProductSearch.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ) + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_product_set: gapic_v1.method.wrap_method( + self.create_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_product_sets: gapic_v1.method.wrap_method( + self.list_product_sets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_product_set: gapic_v1.method.wrap_method( + self.get_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update_product_set: gapic_v1.method.wrap_method( + self.update_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.delete_product_set: gapic_v1.method.wrap_method( + self.delete_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.create_product: gapic_v1.method.wrap_method( + self.create_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_products: gapic_v1.method.wrap_method( + self.list_products, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_product: gapic_v1.method.wrap_method( + self.get_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update_product: gapic_v1.method.wrap_method( + self.update_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.delete_product: gapic_v1.method.wrap_method( + self.delete_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.create_reference_image: gapic_v1.method.wrap_method( + self.create_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.delete_reference_image: gapic_v1.method.wrap_method( + self.delete_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_reference_images: gapic_v1.method.wrap_method( + self.list_reference_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_reference_image: gapic_v1.method.wrap_method( + self.get_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.add_product_to_product_set: gapic_v1.method.wrap_method( + self.add_product_to_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.remove_product_from_product_set: gapic_v1.method.wrap_method( + self.remove_product_from_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_products_in_product_set: gapic_v1.method.wrap_method( + self.list_products_in_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.import_product_sets: gapic_v1.method.wrap_method( + self.import_product_sets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_product_set( + self, + ) -> typing.Callable[ + [product_search_service.CreateProductSetRequest], + typing.Union[ + product_search_service.ProductSet, + typing.Awaitable[product_search_service.ProductSet], + ], + ]: + raise NotImplementedError() + + @property + def list_product_sets( + self, + ) -> typing.Callable[ + [product_search_service.ListProductSetsRequest], + typing.Union[ + product_search_service.ListProductSetsResponse, + typing.Awaitable[product_search_service.ListProductSetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_product_set( + self, + ) -> typing.Callable[ + [product_search_service.GetProductSetRequest], + typing.Union[ + product_search_service.ProductSet, + typing.Awaitable[product_search_service.ProductSet], + ], + ]: + raise NotImplementedError() + + @property + def update_product_set( + self, + ) -> typing.Callable[ + [product_search_service.UpdateProductSetRequest], + typing.Union[ + product_search_service.ProductSet, + typing.Awaitable[product_search_service.ProductSet], + ], + ]: + raise NotImplementedError() + + @property + def delete_product_set( + self, + ) -> typing.Callable[ + [product_search_service.DeleteProductSetRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def create_product( + self, + ) -> typing.Callable[ + [product_search_service.CreateProductRequest], + typing.Union[ + product_search_service.Product, + typing.Awaitable[product_search_service.Product], + ], + ]: + raise NotImplementedError() + + @property + def list_products( + self, + ) -> typing.Callable[ + [product_search_service.ListProductsRequest], + typing.Union[ + product_search_service.ListProductsResponse, + typing.Awaitable[product_search_service.ListProductsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_product( + self, + ) -> typing.Callable[ + [product_search_service.GetProductRequest], + typing.Union[ + product_search_service.Product, + typing.Awaitable[product_search_service.Product], + ], + ]: + raise NotImplementedError() + + @property + def update_product( + self, + ) -> typing.Callable[ + [product_search_service.UpdateProductRequest], + typing.Union[ + product_search_service.Product, + typing.Awaitable[product_search_service.Product], + ], + ]: + raise NotImplementedError() + + @property + def delete_product( + self, + ) -> typing.Callable[ + [product_search_service.DeleteProductRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def create_reference_image( + self, + ) -> typing.Callable[ + [product_search_service.CreateReferenceImageRequest], + typing.Union[ + product_search_service.ReferenceImage, + typing.Awaitable[product_search_service.ReferenceImage], + ], + ]: + raise NotImplementedError() + + @property + def delete_reference_image( + self, + ) -> typing.Callable[ + [product_search_service.DeleteReferenceImageRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def list_reference_images( + self, + ) -> typing.Callable[ + [product_search_service.ListReferenceImagesRequest], + typing.Union[ + product_search_service.ListReferenceImagesResponse, + typing.Awaitable[product_search_service.ListReferenceImagesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_reference_image( + self, + ) -> typing.Callable[ + [product_search_service.GetReferenceImageRequest], + typing.Union[ + product_search_service.ReferenceImage, + typing.Awaitable[product_search_service.ReferenceImage], + ], + ]: + raise NotImplementedError() + + @property + def add_product_to_product_set( + self, + ) -> typing.Callable[ + [product_search_service.AddProductToProductSetRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def remove_product_from_product_set( + self, + ) -> typing.Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def list_products_in_product_set( + self, + ) -> typing.Callable[ + [product_search_service.ListProductsInProductSetRequest], + typing.Union[ + product_search_service.ListProductsInProductSetResponse, + typing.Awaitable[product_search_service.ListProductsInProductSetResponse], + ], + ]: + raise NotImplementedError() + + @property + def import_product_sets( + self, + ) -> typing.Callable[ + [product_search_service.ImportProductSetsRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + +__all__ = ("ProductSearchTransport",) diff --git a/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py b/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py new file mode 100644 index 00000000..61f94bb4 --- /dev/null +++ b/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py @@ -0,0 +1,922 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.vision_v1p3beta1.types import product_search_service +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO + + +class ProductSearchGrpcTransport(ProductSearchTransport): + """gRPC backend transport for ProductSearch. + + Manages Products and ProductSets of reference images for use in + product search. It uses the following resource model: + + - The API has a collection of + [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. + + In parallel, + + - The API has a collection of + [Product][google.cloud.vision.v1p3beta1.Product] resources, named + ``projects/*/locations/*/products/*`` + + - Each [Product][google.cloud.vision.v1p3beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def create_product_set( + self, + ) -> Callable[ + [product_search_service.CreateProductSetRequest], + product_search_service.ProductSet, + ]: + r"""Return a callable for the create product set method over gRPC. + + Creates and returns a new ProductSet resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. + + Returns: + Callable[[~.CreateProductSetRequest], + ~.ProductSet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_product_set" not in self._stubs: + self._stubs["create_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/CreateProductSet", + request_serializer=product_search_service.CreateProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["create_product_set"] + + @property + def list_product_sets( + self, + ) -> Callable[ + [product_search_service.ListProductSetsRequest], + product_search_service.ListProductSetsResponse, + ]: + r"""Return a callable for the list product sets method over gRPC. + + Lists ProductSets in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. + + Returns: + Callable[[~.ListProductSetsRequest], + ~.ListProductSetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_product_sets" not in self._stubs: + self._stubs["list_product_sets"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/ListProductSets", + request_serializer=product_search_service.ListProductSetsRequest.serialize, + response_deserializer=product_search_service.ListProductSetsResponse.deserialize, + ) + return self._stubs["list_product_sets"] + + @property + def get_product_set( + self, + ) -> Callable[ + [product_search_service.GetProductSetRequest], product_search_service.ProductSet + ]: + r"""Return a callable for the get product set method over gRPC. + + Gets information associated with a ProductSet. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + + Returns: + Callable[[~.GetProductSetRequest], + ~.ProductSet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_product_set" not in self._stubs: + self._stubs["get_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/GetProductSet", + request_serializer=product_search_service.GetProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["get_product_set"] + + @property + def update_product_set( + self, + ) -> Callable[ + [product_search_service.UpdateProductSetRequest], + product_search_service.ProductSet, + ]: + r"""Return a callable for the update product set method over gRPC. + + Makes changes to a ProductSet resource. Only display_name can be + updated currently. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. + + Returns: + Callable[[~.UpdateProductSetRequest], + ~.ProductSet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_product_set" not in self._stubs: + self._stubs["update_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/UpdateProductSet", + request_serializer=product_search_service.UpdateProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["update_product_set"] + + @property + def delete_product_set( + self, + ) -> Callable[[product_search_service.DeleteProductSetRequest], empty.Empty]: + r"""Return a callable for the delete product set method over gRPC. + + Permanently deletes a ProductSet. All Products and + ReferenceImages in the ProductSet will be deleted. + + The actual image files are not deleted from Google Cloud + Storage. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + + Returns: + Callable[[~.DeleteProductSetRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_product_set" not in self._stubs: + self._stubs["delete_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteProductSet", + request_serializer=product_search_service.DeleteProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_product_set"] + + @property + def create_product( + self, + ) -> Callable[ + [product_search_service.CreateProductRequest], product_search_service.Product + ]: + r"""Return a callable for the create product method over gRPC. + + Creates and returns a new product resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. + + Returns: + Callable[[~.CreateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_product" not in self._stubs: + self._stubs["create_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/CreateProduct", + request_serializer=product_search_service.CreateProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["create_product"] + + @property + def list_products( + self, + ) -> Callable[ + [product_search_service.ListProductsRequest], + product_search_service.ListProductsResponse, + ]: + r"""Return a callable for the list products method over gRPC. + + Lists products in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Returns: + Callable[[~.ListProductsRequest], + ~.ListProductsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_products" not in self._stubs: + self._stubs["list_products"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/ListProducts", + request_serializer=product_search_service.ListProductsRequest.serialize, + response_deserializer=product_search_service.ListProductsResponse.deserialize, + ) + return self._stubs["list_products"] + + @property + def get_product( + self, + ) -> Callable[ + [product_search_service.GetProductRequest], product_search_service.Product + ]: + r"""Return a callable for the get product method over gRPC. + + Gets information associated with a Product. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + + Returns: + Callable[[~.GetProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_product" not in self._stubs: + self._stubs["get_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/GetProduct", + request_serializer=product_search_service.GetProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["get_product"] + + @property + def update_product( + self, + ) -> Callable[ + [product_search_service.UpdateProductRequest], product_search_service.Product + ]: + r"""Return a callable for the update product method over gRPC. + + Makes changes to a Product resource. Only display_name, + description and labels can be updated right now. + + If labels are updated, the change will not be reflected in + queries until the next index time. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. + + Returns: + Callable[[~.UpdateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_product" not in self._stubs: + self._stubs["update_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/UpdateProduct", + request_serializer=product_search_service.UpdateProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["update_product"] + + @property + def delete_product( + self, + ) -> Callable[[product_search_service.DeleteProductRequest], empty.Empty]: + r"""Return a callable for the delete product method over gRPC. + + Permanently deletes a product and its reference images. + + Metadata of the product and all its images will be deleted right + away, but search queries against ProductSets containing the + product may still work until all related caches are refreshed. + + Possible errors: + + - Returns NOT_FOUND if the product does not exist. + + Returns: + Callable[[~.DeleteProductRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_product" not in self._stubs: + self._stubs["delete_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteProduct", + request_serializer=product_search_service.DeleteProductRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_product"] + + @property + def create_reference_image( + self, + ) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + product_search_service.ReferenceImage, + ]: + r"""Return a callable for the create reference image method over gRPC. + + Creates and returns a new ReferenceImage resource. + + The ``bounding_poly`` field is optional. If ``bounding_poly`` is + not specified, the system will try to detect regions of interest + in the image that are compatible with the product_category on + the parent product. If it is specified, detection is ALWAYS + skipped. The system converts polygons into non-rotated + rectangles. + + Note that the pipeline will resize the image if the image + resolution is too large to process (above 50MP). + + Possible errors: + + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. + + Returns: + Callable[[~.CreateReferenceImageRequest], + ~.ReferenceImage]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_reference_image" not in self._stubs: + self._stubs["create_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/CreateReferenceImage", + request_serializer=product_search_service.CreateReferenceImageRequest.serialize, + response_deserializer=product_search_service.ReferenceImage.deserialize, + ) + return self._stubs["create_reference_image"] + + @property + def delete_reference_image( + self, + ) -> Callable[[product_search_service.DeleteReferenceImageRequest], empty.Empty]: + r"""Return a callable for the delete reference image method over gRPC. + + Permanently deletes a reference image. + + The image metadata will be deleted right away, but search + queries against ProductSets containing the image may still work + until all related caches are refreshed. + + The actual image files are not deleted from Google Cloud + Storage. + + Possible errors: + + - Returns NOT_FOUND if the reference image does not exist. + + Returns: + Callable[[~.DeleteReferenceImageRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_reference_image" not in self._stubs: + self._stubs["delete_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteReferenceImage", + request_serializer=product_search_service.DeleteReferenceImageRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_reference_image"] + + @property + def list_reference_images( + self, + ) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + product_search_service.ListReferenceImagesResponse, + ]: + r"""Return a callable for the list reference images method over gRPC. + + Lists reference images. + + Possible errors: + + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. + + Returns: + Callable[[~.ListReferenceImagesRequest], + ~.ListReferenceImagesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_reference_images" not in self._stubs: + self._stubs["list_reference_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/ListReferenceImages", + request_serializer=product_search_service.ListReferenceImagesRequest.serialize, + response_deserializer=product_search_service.ListReferenceImagesResponse.deserialize, + ) + return self._stubs["list_reference_images"] + + @property + def get_reference_image( + self, + ) -> Callable[ + [product_search_service.GetReferenceImageRequest], + product_search_service.ReferenceImage, + ]: + r"""Return a callable for the get reference image method over gRPC. + + Gets information associated with a ReferenceImage. + + Possible errors: + + - Returns NOT_FOUND if the specified image does not exist. + + Returns: + Callable[[~.GetReferenceImageRequest], + ~.ReferenceImage]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_reference_image" not in self._stubs: + self._stubs["get_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/GetReferenceImage", + request_serializer=product_search_service.GetReferenceImageRequest.serialize, + response_deserializer=product_search_service.ReferenceImage.deserialize, + ) + return self._stubs["get_reference_image"] + + @property + def add_product_to_product_set( + self, + ) -> Callable[[product_search_service.AddProductToProductSetRequest], empty.Empty]: + r"""Return a callable for the add product to product set method over gRPC. + + Adds a Product to the specified ProductSet. If the Product is + already present, no change is made. + + One Product can be added to at most 100 ProductSets. + + Possible errors: + + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. + + Returns: + Callable[[~.AddProductToProductSetRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "add_product_to_product_set" not in self._stubs: + self._stubs["add_product_to_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/AddProductToProductSet", + request_serializer=product_search_service.AddProductToProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["add_product_to_product_set"] + + @property + def remove_product_from_product_set( + self, + ) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], empty.Empty + ]: + r"""Return a callable for the remove product from product + set method over gRPC. + + Removes a Product from the specified ProductSet. + + Possible errors: + + - Returns NOT_FOUND If the Product is not found under the + ProductSet. + + Returns: + Callable[[~.RemoveProductFromProductSetRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "remove_product_from_product_set" not in self._stubs: + self._stubs[ + "remove_product_from_product_set" + ] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/RemoveProductFromProductSet", + request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["remove_product_from_product_set"] + + @property + def list_products_in_product_set( + self, + ) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + product_search_service.ListProductsInProductSetResponse, + ]: + r"""Return a callable for the list products in product set method over gRPC. + + Lists the Products in a ProductSet, in an unspecified order. If + the ProductSet does not exist, the products field of the + response will be empty. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Returns: + Callable[[~.ListProductsInProductSetRequest], + ~.ListProductsInProductSetResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_products_in_product_set" not in self._stubs: + self._stubs["list_products_in_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/ListProductsInProductSet", + request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, + response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, + ) + return self._stubs["list_products_in_product_set"] + + @property + def import_product_sets( + self, + ) -> Callable[ + [product_search_service.ImportProductSetsRequest], operations.Operation + ]: + r"""Return a callable for the import product sets method over gRPC. + + Asynchronous API that imports a list of reference images to + specified product sets based on a list of image information. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) ``Operation.response`` + contains ``ImportProductSetsResponse``. (results) + + The input source of this method is a csv file on Google Cloud + Storage. For the format of the csv file please see + [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1p3beta1.ImportProductSetsGcsSource.csv_file_uri]. + + Returns: + Callable[[~.ImportProductSetsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_product_sets" not in self._stubs: + self._stubs["import_product_sets"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/ImportProductSets", + request_serializer=product_search_service.ImportProductSetsRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["import_product_sets"] + + +__all__ = ("ProductSearchGrpcTransport",) diff --git a/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc_asyncio.py b/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc_asyncio.py new file mode 100644 index 00000000..0cbbc97b --- /dev/null +++ b/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc_asyncio.py @@ -0,0 +1,936 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.vision_v1p3beta1.types import product_search_service +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO +from .grpc import ProductSearchGrpcTransport + + +class ProductSearchGrpcAsyncIOTransport(ProductSearchTransport): + """gRPC AsyncIO backend transport for ProductSearch. + + Manages Products and ProductSets of reference images for use in + product search. It uses the following resource model: + + - The API has a collection of + [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. + + In parallel, + + - The API has a collection of + [Product][google.cloud.vision.v1p3beta1.Product] resources, named + ``projects/*/locations/*/products/*`` + + - Each [Product][google.cloud.vision.v1p3beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p3beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def create_product_set( + self, + ) -> Callable[ + [product_search_service.CreateProductSetRequest], + Awaitable[product_search_service.ProductSet], + ]: + r"""Return a callable for the create product set method over gRPC. + + Creates and returns a new ProductSet resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. + + Returns: + Callable[[~.CreateProductSetRequest], + Awaitable[~.ProductSet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_product_set" not in self._stubs: + self._stubs["create_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/CreateProductSet", + request_serializer=product_search_service.CreateProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["create_product_set"] + + @property + def list_product_sets( + self, + ) -> Callable[ + [product_search_service.ListProductSetsRequest], + Awaitable[product_search_service.ListProductSetsResponse], + ]: + r"""Return a callable for the list product sets method over gRPC. + + Lists ProductSets in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. + + Returns: + Callable[[~.ListProductSetsRequest], + Awaitable[~.ListProductSetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_product_sets" not in self._stubs: + self._stubs["list_product_sets"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/ListProductSets", + request_serializer=product_search_service.ListProductSetsRequest.serialize, + response_deserializer=product_search_service.ListProductSetsResponse.deserialize, + ) + return self._stubs["list_product_sets"] + + @property + def get_product_set( + self, + ) -> Callable[ + [product_search_service.GetProductSetRequest], + Awaitable[product_search_service.ProductSet], + ]: + r"""Return a callable for the get product set method over gRPC. + + Gets information associated with a ProductSet. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + + Returns: + Callable[[~.GetProductSetRequest], + Awaitable[~.ProductSet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_product_set" not in self._stubs: + self._stubs["get_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/GetProductSet", + request_serializer=product_search_service.GetProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["get_product_set"] + + @property + def update_product_set( + self, + ) -> Callable[ + [product_search_service.UpdateProductSetRequest], + Awaitable[product_search_service.ProductSet], + ]: + r"""Return a callable for the update product set method over gRPC. + + Makes changes to a ProductSet resource. Only display_name can be + updated currently. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. + + Returns: + Callable[[~.UpdateProductSetRequest], + Awaitable[~.ProductSet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_product_set" not in self._stubs: + self._stubs["update_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/UpdateProductSet", + request_serializer=product_search_service.UpdateProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["update_product_set"] + + @property + def delete_product_set( + self, + ) -> Callable[ + [product_search_service.DeleteProductSetRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the delete product set method over gRPC. + + Permanently deletes a ProductSet. All Products and + ReferenceImages in the ProductSet will be deleted. + + The actual image files are not deleted from Google Cloud + Storage. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + + Returns: + Callable[[~.DeleteProductSetRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_product_set" not in self._stubs: + self._stubs["delete_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteProductSet", + request_serializer=product_search_service.DeleteProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_product_set"] + + @property + def create_product( + self, + ) -> Callable[ + [product_search_service.CreateProductRequest], + Awaitable[product_search_service.Product], + ]: + r"""Return a callable for the create product method over gRPC. + + Creates and returns a new product resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. + + Returns: + Callable[[~.CreateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_product" not in self._stubs: + self._stubs["create_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/CreateProduct", + request_serializer=product_search_service.CreateProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["create_product"] + + @property + def list_products( + self, + ) -> Callable[ + [product_search_service.ListProductsRequest], + Awaitable[product_search_service.ListProductsResponse], + ]: + r"""Return a callable for the list products method over gRPC. + + Lists products in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Returns: + Callable[[~.ListProductsRequest], + Awaitable[~.ListProductsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_products" not in self._stubs: + self._stubs["list_products"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/ListProducts", + request_serializer=product_search_service.ListProductsRequest.serialize, + response_deserializer=product_search_service.ListProductsResponse.deserialize, + ) + return self._stubs["list_products"] + + @property + def get_product( + self, + ) -> Callable[ + [product_search_service.GetProductRequest], + Awaitable[product_search_service.Product], + ]: + r"""Return a callable for the get product method over gRPC. + + Gets information associated with a Product. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + + Returns: + Callable[[~.GetProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_product" not in self._stubs: + self._stubs["get_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/GetProduct", + request_serializer=product_search_service.GetProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["get_product"] + + @property + def update_product( + self, + ) -> Callable[ + [product_search_service.UpdateProductRequest], + Awaitable[product_search_service.Product], + ]: + r"""Return a callable for the update product method over gRPC. + + Makes changes to a Product resource. Only display_name, + description and labels can be updated right now. + + If labels are updated, the change will not be reflected in + queries until the next index time. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. + + Returns: + Callable[[~.UpdateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_product" not in self._stubs: + self._stubs["update_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/UpdateProduct", + request_serializer=product_search_service.UpdateProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["update_product"] + + @property + def delete_product( + self, + ) -> Callable[ + [product_search_service.DeleteProductRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the delete product method over gRPC. + + Permanently deletes a product and its reference images. + + Metadata of the product and all its images will be deleted right + away, but search queries against ProductSets containing the + product may still work until all related caches are refreshed. + + Possible errors: + + - Returns NOT_FOUND if the product does not exist. + + Returns: + Callable[[~.DeleteProductRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_product" not in self._stubs: + self._stubs["delete_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteProduct", + request_serializer=product_search_service.DeleteProductRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_product"] + + @property + def create_reference_image( + self, + ) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + Awaitable[product_search_service.ReferenceImage], + ]: + r"""Return a callable for the create reference image method over gRPC. + + Creates and returns a new ReferenceImage resource. + + The ``bounding_poly`` field is optional. If ``bounding_poly`` is + not specified, the system will try to detect regions of interest + in the image that are compatible with the product_category on + the parent product. If it is specified, detection is ALWAYS + skipped. The system converts polygons into non-rotated + rectangles. + + Note that the pipeline will resize the image if the image + resolution is too large to process (above 50MP). + + Possible errors: + + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. + + Returns: + Callable[[~.CreateReferenceImageRequest], + Awaitable[~.ReferenceImage]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_reference_image" not in self._stubs: + self._stubs["create_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/CreateReferenceImage", + request_serializer=product_search_service.CreateReferenceImageRequest.serialize, + response_deserializer=product_search_service.ReferenceImage.deserialize, + ) + return self._stubs["create_reference_image"] + + @property + def delete_reference_image( + self, + ) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the delete reference image method over gRPC. + + Permanently deletes a reference image. + + The image metadata will be deleted right away, but search + queries against ProductSets containing the image may still work + until all related caches are refreshed. + + The actual image files are not deleted from Google Cloud + Storage. + + Possible errors: + + - Returns NOT_FOUND if the reference image does not exist. + + Returns: + Callable[[~.DeleteReferenceImageRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_reference_image" not in self._stubs: + self._stubs["delete_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/DeleteReferenceImage", + request_serializer=product_search_service.DeleteReferenceImageRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_reference_image"] + + @property + def list_reference_images( + self, + ) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + Awaitable[product_search_service.ListReferenceImagesResponse], + ]: + r"""Return a callable for the list reference images method over gRPC. + + Lists reference images. + + Possible errors: + + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. + + Returns: + Callable[[~.ListReferenceImagesRequest], + Awaitable[~.ListReferenceImagesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_reference_images" not in self._stubs: + self._stubs["list_reference_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/ListReferenceImages", + request_serializer=product_search_service.ListReferenceImagesRequest.serialize, + response_deserializer=product_search_service.ListReferenceImagesResponse.deserialize, + ) + return self._stubs["list_reference_images"] + + @property + def get_reference_image( + self, + ) -> Callable[ + [product_search_service.GetReferenceImageRequest], + Awaitable[product_search_service.ReferenceImage], + ]: + r"""Return a callable for the get reference image method over gRPC. + + Gets information associated with a ReferenceImage. + + Possible errors: + + - Returns NOT_FOUND if the specified image does not exist. + + Returns: + Callable[[~.GetReferenceImageRequest], + Awaitable[~.ReferenceImage]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_reference_image" not in self._stubs: + self._stubs["get_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/GetReferenceImage", + request_serializer=product_search_service.GetReferenceImageRequest.serialize, + response_deserializer=product_search_service.ReferenceImage.deserialize, + ) + return self._stubs["get_reference_image"] + + @property + def add_product_to_product_set( + self, + ) -> Callable[ + [product_search_service.AddProductToProductSetRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the add product to product set method over gRPC. + + Adds a Product to the specified ProductSet. If the Product is + already present, no change is made. + + One Product can be added to at most 100 ProductSets. + + Possible errors: + + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. + + Returns: + Callable[[~.AddProductToProductSetRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "add_product_to_product_set" not in self._stubs: + self._stubs["add_product_to_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/AddProductToProductSet", + request_serializer=product_search_service.AddProductToProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["add_product_to_product_set"] + + @property + def remove_product_from_product_set( + self, + ) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + Awaitable[empty.Empty], + ]: + r"""Return a callable for the remove product from product + set method over gRPC. + + Removes a Product from the specified ProductSet. + + Possible errors: + + - Returns NOT_FOUND If the Product is not found under the + ProductSet. + + Returns: + Callable[[~.RemoveProductFromProductSetRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "remove_product_from_product_set" not in self._stubs: + self._stubs[ + "remove_product_from_product_set" + ] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/RemoveProductFromProductSet", + request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["remove_product_from_product_set"] + + @property + def list_products_in_product_set( + self, + ) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + Awaitable[product_search_service.ListProductsInProductSetResponse], + ]: + r"""Return a callable for the list products in product set method over gRPC. + + Lists the Products in a ProductSet, in an unspecified order. If + the ProductSet does not exist, the products field of the + response will be empty. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Returns: + Callable[[~.ListProductsInProductSetRequest], + Awaitable[~.ListProductsInProductSetResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_products_in_product_set" not in self._stubs: + self._stubs["list_products_in_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/ListProductsInProductSet", + request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, + response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, + ) + return self._stubs["list_products_in_product_set"] + + @property + def import_product_sets( + self, + ) -> Callable[ + [product_search_service.ImportProductSetsRequest], + Awaitable[operations.Operation], + ]: + r"""Return a callable for the import product sets method over gRPC. + + Asynchronous API that imports a list of reference images to + specified product sets based on a list of image information. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) ``Operation.response`` + contains ``ImportProductSetsResponse``. (results) + + The input source of this method is a csv file on Google Cloud + Storage. For the format of the csv file please see + [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1p3beta1.ImportProductSetsGcsSource.csv_file_uri]. + + Returns: + Callable[[~.ImportProductSetsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_product_sets" not in self._stubs: + self._stubs["import_product_sets"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p3beta1.ProductSearch/ImportProductSets", + request_serializer=product_search_service.ImportProductSetsRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["import_product_sets"] + + +__all__ = ("ProductSearchGrpcAsyncIOTransport",) diff --git a/google/cloud/vision_v1p3beta1/types.py b/google/cloud/vision_v1p3beta1/types.py deleted file mode 100644 index 9d146598..00000000 --- a/google/cloud/vision_v1p3beta1/types.py +++ /dev/null @@ -1,74 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.vision_v1p3beta1.proto import geometry_pb2 -from google.cloud.vision_v1p3beta1.proto import image_annotator_pb2 -from google.cloud.vision_v1p3beta1.proto import product_search_pb2 -from google.cloud.vision_v1p3beta1.proto import product_search_service_pb2 -from google.cloud.vision_v1p3beta1.proto import text_annotation_pb2 -from google.cloud.vision_v1p3beta1.proto import web_detection_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import any_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import timestamp_pb2 -from google.protobuf import wrappers_pb2 -from google.rpc import status_pb2 -from google.type import color_pb2 -from google.type import latlng_pb2 - - -_shared_modules = [ - operations_pb2, - any_pb2, - empty_pb2, - field_mask_pb2, - timestamp_pb2, - wrappers_pb2, - status_pb2, - color_pb2, - latlng_pb2, -] - -_local_modules = [ - geometry_pb2, - image_annotator_pb2, - product_search_pb2, - product_search_service_pb2, - text_annotation_pb2, - web_detection_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.vision_v1p3beta1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/vision_v1p3beta1/types/__init__.py b/google/cloud/vision_v1p3beta1/types/__init__.py new file mode 100644 index 00000000..4b9cbb17 --- /dev/null +++ b/google/cloud/vision_v1p3beta1/types/__init__.py @@ -0,0 +1,183 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .geometry import ( + Vertex, + NormalizedVertex, + BoundingPoly, + NormalizedBoundingPoly, + Position, +) +from .product_search_service import ( + Product, + ProductSet, + ReferenceImage, + CreateProductRequest, + ListProductsRequest, + ListProductsResponse, + GetProductRequest, + UpdateProductRequest, + DeleteProductRequest, + CreateProductSetRequest, + ListProductSetsRequest, + ListProductSetsResponse, + GetProductSetRequest, + UpdateProductSetRequest, + DeleteProductSetRequest, + CreateReferenceImageRequest, + ListReferenceImagesRequest, + ListReferenceImagesResponse, + GetReferenceImageRequest, + DeleteReferenceImageRequest, + AddProductToProductSetRequest, + RemoveProductFromProductSetRequest, + ListProductsInProductSetRequest, + ListProductsInProductSetResponse, + ImportProductSetsGcsSource, + ImportProductSetsInputConfig, + ImportProductSetsRequest, + ImportProductSetsResponse, + BatchOperationMetadata, +) +from .product_search import ( + ProductSearchParams, + ProductSearchResults, +) +from .text_annotation import ( + TextAnnotation, + Page, + Block, + Paragraph, + Word, + Symbol, +) +from .web_detection import WebDetection +from .image_annotator import ( + Feature, + ImageSource, + Image, + FaceAnnotation, + LocationInfo, + Property, + EntityAnnotation, + LocalizedObjectAnnotation, + SafeSearchAnnotation, + LatLongRect, + ColorInfo, + DominantColorsAnnotation, + ImageProperties, + CropHint, + CropHintsAnnotation, + CropHintsParams, + WebDetectionParams, + ImageContext, + AnnotateImageRequest, + ImageAnnotationContext, + AnnotateImageResponse, + AnnotateFileResponse, + BatchAnnotateImagesRequest, + BatchAnnotateImagesResponse, + AsyncAnnotateFileRequest, + AsyncAnnotateFileResponse, + AsyncBatchAnnotateFilesRequest, + AsyncBatchAnnotateFilesResponse, + InputConfig, + OutputConfig, + GcsSource, + GcsDestination, + OperationMetadata, +) + + +__all__ = ( + "Vertex", + "NormalizedVertex", + "BoundingPoly", + "NormalizedBoundingPoly", + "Position", + "Product", + "ProductSet", + "ReferenceImage", + "CreateProductRequest", + "ListProductsRequest", + "ListProductsResponse", + "GetProductRequest", + "UpdateProductRequest", + "DeleteProductRequest", + "CreateProductSetRequest", + "ListProductSetsRequest", + "ListProductSetsResponse", + "GetProductSetRequest", + "UpdateProductSetRequest", + "DeleteProductSetRequest", + "CreateReferenceImageRequest", + "ListReferenceImagesRequest", + "ListReferenceImagesResponse", + "GetReferenceImageRequest", + "DeleteReferenceImageRequest", + "AddProductToProductSetRequest", + "RemoveProductFromProductSetRequest", + "ListProductsInProductSetRequest", + "ListProductsInProductSetResponse", + "ImportProductSetsGcsSource", + "ImportProductSetsInputConfig", + "ImportProductSetsRequest", + "ImportProductSetsResponse", + "BatchOperationMetadata", + "ProductSearchParams", + "ProductSearchResults", + "TextAnnotation", + "Page", + "Block", + "Paragraph", + "Word", + "Symbol", + "WebDetection", + "Feature", + "ImageSource", + "Image", + "FaceAnnotation", + "LocationInfo", + "Property", + "EntityAnnotation", + "LocalizedObjectAnnotation", + "SafeSearchAnnotation", + "LatLongRect", + "ColorInfo", + "DominantColorsAnnotation", + "ImageProperties", + "CropHint", + "CropHintsAnnotation", + "CropHintsParams", + "WebDetectionParams", + "ImageContext", + "AnnotateImageRequest", + "ImageAnnotationContext", + "AnnotateImageResponse", + "AnnotateFileResponse", + "BatchAnnotateImagesRequest", + "BatchAnnotateImagesResponse", + "AsyncAnnotateFileRequest", + "AsyncAnnotateFileResponse", + "AsyncBatchAnnotateFilesRequest", + "AsyncBatchAnnotateFilesResponse", + "InputConfig", + "OutputConfig", + "GcsSource", + "GcsDestination", + "OperationMetadata", +) diff --git a/google/cloud/vision_v1p3beta1/types/geometry.py b/google/cloud/vision_v1p3beta1/types/geometry.py new file mode 100644 index 00000000..f5b2b8fc --- /dev/null +++ b/google/cloud/vision_v1p3beta1/types/geometry.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p3beta1", + manifest={ + "Vertex", + "NormalizedVertex", + "BoundingPoly", + "NormalizedBoundingPoly", + "Position", + }, +) + + +class Vertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the vertex coordinates are in the same scale as the + original image. + + Attributes: + x (int): + X coordinate. + y (int): + Y coordinate. + """ + + x = proto.Field(proto.INT32, number=1) + + y = proto.Field(proto.INT32, number=2) + + +class NormalizedVertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the normalized vertex coordinates are relative to the + original image and range from 0 to 1. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate. + """ + + x = proto.Field(proto.FLOAT, number=1) + + y = proto.Field(proto.FLOAT, number=2) + + +class BoundingPoly(proto.Message): + r"""A bounding polygon for the detected image annotation. + + Attributes: + vertices (Sequence[~.geometry.Vertex]): + The bounding polygon vertices. + normalized_vertices (Sequence[~.geometry.NormalizedVertex]): + The bounding polygon normalized vertices. + """ + + vertices = proto.RepeatedField(proto.MESSAGE, number=1, message=Vertex,) + + normalized_vertices = proto.RepeatedField( + proto.MESSAGE, number=2, message=NormalizedVertex, + ) + + +class NormalizedBoundingPoly(proto.Message): + r"""A normalized bounding polygon around a portion of an image. + + Attributes: + vertices (Sequence[~.geometry.NormalizedVertex]): + Normalized vertices of the bounding polygon. + """ + + vertices = proto.RepeatedField(proto.MESSAGE, number=1, message=NormalizedVertex,) + + +class Position(proto.Message): + r"""A 3D position in the image, used primarily for Face detection + landmarks. A valid Position must have both x and y coordinates. + The position coordinates are in the same scale as the original + image. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate. + z (float): + Z coordinate (or depth). + """ + + x = proto.Field(proto.FLOAT, number=1) + + y = proto.Field(proto.FLOAT, number=2) + + z = proto.Field(proto.FLOAT, number=3) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p3beta1/types/image_annotator.py b/google/cloud/vision_v1p3beta1/types/image_annotator.py new file mode 100644 index 00000000..b801ff74 --- /dev/null +++ b/google/cloud/vision_v1p3beta1/types/image_annotator.py @@ -0,0 +1,1039 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.vision_v1p3beta1.types import geometry +from google.cloud.vision_v1p3beta1.types import product_search +from google.cloud.vision_v1p3beta1.types import text_annotation +from google.cloud.vision_v1p3beta1.types import web_detection as gcv_web_detection +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore +from google.type import color_pb2 as gt_color # type: ignore +from google.type import latlng_pb2 as latlng # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p3beta1", + manifest={ + "Likelihood", + "Feature", + "ImageSource", + "Image", + "FaceAnnotation", + "LocationInfo", + "Property", + "EntityAnnotation", + "LocalizedObjectAnnotation", + "SafeSearchAnnotation", + "LatLongRect", + "ColorInfo", + "DominantColorsAnnotation", + "ImageProperties", + "CropHint", + "CropHintsAnnotation", + "CropHintsParams", + "WebDetectionParams", + "ImageContext", + "AnnotateImageRequest", + "ImageAnnotationContext", + "AnnotateImageResponse", + "AnnotateFileResponse", + "BatchAnnotateImagesRequest", + "BatchAnnotateImagesResponse", + "AsyncAnnotateFileRequest", + "AsyncAnnotateFileResponse", + "AsyncBatchAnnotateFilesRequest", + "AsyncBatchAnnotateFilesResponse", + "InputConfig", + "OutputConfig", + "GcsSource", + "GcsDestination", + "OperationMetadata", + }, +) + + +class Likelihood(proto.Enum): + r"""A bucketized representation of likelihood, which is intended + to give clients highly stable results across model upgrades. + """ + UNKNOWN = 0 + VERY_UNLIKELY = 1 + UNLIKELY = 2 + POSSIBLE = 3 + LIKELY = 4 + VERY_LIKELY = 5 + + +class Feature(proto.Message): + r"""The type of Google Cloud Vision API detection to perform, and the + maximum number of results to return for that type. Multiple + ``Feature`` objects can be specified in the ``features`` list. + + Attributes: + type_ (~.image_annotator.Feature.Type): + The feature type. + max_results (int): + Maximum number of results of this type. Does not apply to + ``TEXT_DETECTION``, ``DOCUMENT_TEXT_DETECTION``, or + ``CROP_HINTS``. + model (str): + Model to use for the feature. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + class Type(proto.Enum): + r"""Type of Google Cloud Vision API feature to be extracted.""" + TYPE_UNSPECIFIED = 0 + FACE_DETECTION = 1 + LANDMARK_DETECTION = 2 + LOGO_DETECTION = 3 + LABEL_DETECTION = 4 + TEXT_DETECTION = 5 + DOCUMENT_TEXT_DETECTION = 11 + SAFE_SEARCH_DETECTION = 6 + IMAGE_PROPERTIES = 7 + CROP_HINTS = 9 + WEB_DETECTION = 10 + PRODUCT_SEARCH = 12 + OBJECT_LOCALIZATION = 19 + + type_ = proto.Field(proto.ENUM, number=1, enum=Type,) + + max_results = proto.Field(proto.INT32, number=2) + + model = proto.Field(proto.STRING, number=3) + + +class ImageSource(proto.Message): + r"""External image source (Google Cloud Storage or web URL image + location). + + Attributes: + gcs_image_uri (str): + **Use ``image_uri`` instead.** + + The Google Cloud Storage URI of the form + ``gs://bucket_name/object_name``. Object versioning is not + supported. See `Google Cloud Storage Request + URIs `__ + for more info. + image_uri (str): + The URI of the source image. Can be either: + + 1. A Google Cloud Storage URI of the form + ``gs://bucket_name/object_name``. Object versioning is + not supported. See `Google Cloud Storage Request + URIs `__ + for more info. + + 2. A publicly-accessible image HTTP/HTTPS URL. When fetching + images from HTTP/HTTPS URLs, Google cannot guarantee that + the request will be completed. Your request may fail if + the specified host denies the request (e.g. due to + request throttling or DOS prevention), or if Google + throttles requests to the site for abuse prevention. You + should not depend on externally-hosted images for + production applications. + + When both ``gcs_image_uri`` and ``image_uri`` are specified, + ``image_uri`` takes precedence. + """ + + gcs_image_uri = proto.Field(proto.STRING, number=1) + + image_uri = proto.Field(proto.STRING, number=2) + + +class Image(proto.Message): + r"""Client image to perform Google Cloud Vision API tasks over. + + Attributes: + content (bytes): + Image content, represented as a stream of bytes. Note: As + with all ``bytes`` fields, protobuffers use a pure binary + representation, whereas JSON representations use base64. + source (~.image_annotator.ImageSource): + Google Cloud Storage image location, or publicly-accessible + image URL. If both ``content`` and ``source`` are provided + for an image, ``content`` takes precedence and is used to + perform the image annotation request. + """ + + content = proto.Field(proto.BYTES, number=1) + + source = proto.Field(proto.MESSAGE, number=2, message=ImageSource,) + + +class FaceAnnotation(proto.Message): + r"""A face annotation object contains the results of face + detection. + + Attributes: + bounding_poly (~.geometry.BoundingPoly): + The bounding polygon around the face. The coordinates of the + bounding box are in the original image's scale, as returned + in ``ImageParams``. The bounding box is computed to "frame" + the face in accordance with human expectations. It is based + on the landmarker results. Note that one or more x and/or y + coordinates may not be generated in the ``BoundingPoly`` + (the polygon will be unbounded) if only a partial face + appears in the image to be annotated. + fd_bounding_poly (~.geometry.BoundingPoly): + The ``fd_bounding_poly`` bounding polygon is tighter than + the ``boundingPoly``, and encloses only the skin part of the + face. Typically, it is used to eliminate the face from any + image analysis that detects the "amount of skin" visible in + an image. It is not based on the landmarker results, only on + the initial face detection, hence the fd (face detection) + prefix. + landmarks (Sequence[~.image_annotator.FaceAnnotation.Landmark]): + Detected face landmarks. + roll_angle (float): + Roll angle, which indicates the amount of + clockwise/anti-clockwise rotation of the face relative to + the image vertical about the axis perpendicular to the face. + Range [-180,180]. + pan_angle (float): + Yaw angle, which indicates the leftward/rightward angle that + the face is pointing relative to the vertical plane + perpendicular to the image. Range [-180,180]. + tilt_angle (float): + Pitch angle, which indicates the upwards/downwards angle + that the face is pointing relative to the image's horizontal + plane. Range [-180,180]. + detection_confidence (float): + Detection confidence. Range [0, 1]. + landmarking_confidence (float): + Face landmarking confidence. Range [0, 1]. + joy_likelihood (~.image_annotator.Likelihood): + Joy likelihood. + sorrow_likelihood (~.image_annotator.Likelihood): + Sorrow likelihood. + anger_likelihood (~.image_annotator.Likelihood): + Anger likelihood. + surprise_likelihood (~.image_annotator.Likelihood): + Surprise likelihood. + under_exposed_likelihood (~.image_annotator.Likelihood): + Under-exposed likelihood. + blurred_likelihood (~.image_annotator.Likelihood): + Blurred likelihood. + headwear_likelihood (~.image_annotator.Likelihood): + Headwear likelihood. + """ + + class Landmark(proto.Message): + r"""A face-specific landmark (for example, a face feature). + + Attributes: + type_ (~.image_annotator.FaceAnnotation.Landmark.Type): + Face landmark type. + position (~.geometry.Position): + Face landmark position. + """ + + class Type(proto.Enum): + r"""Face landmark (feature) type. Left and right are defined from the + vantage of the viewer of the image without considering mirror + projections typical of photos. So, ``LEFT_EYE``, typically, is the + person's right eye. + """ + UNKNOWN_LANDMARK = 0 + LEFT_EYE = 1 + RIGHT_EYE = 2 + LEFT_OF_LEFT_EYEBROW = 3 + RIGHT_OF_LEFT_EYEBROW = 4 + LEFT_OF_RIGHT_EYEBROW = 5 + RIGHT_OF_RIGHT_EYEBROW = 6 + MIDPOINT_BETWEEN_EYES = 7 + NOSE_TIP = 8 + UPPER_LIP = 9 + LOWER_LIP = 10 + MOUTH_LEFT = 11 + MOUTH_RIGHT = 12 + MOUTH_CENTER = 13 + NOSE_BOTTOM_RIGHT = 14 + NOSE_BOTTOM_LEFT = 15 + NOSE_BOTTOM_CENTER = 16 + LEFT_EYE_TOP_BOUNDARY = 17 + LEFT_EYE_RIGHT_CORNER = 18 + LEFT_EYE_BOTTOM_BOUNDARY = 19 + LEFT_EYE_LEFT_CORNER = 20 + RIGHT_EYE_TOP_BOUNDARY = 21 + RIGHT_EYE_RIGHT_CORNER = 22 + RIGHT_EYE_BOTTOM_BOUNDARY = 23 + RIGHT_EYE_LEFT_CORNER = 24 + LEFT_EYEBROW_UPPER_MIDPOINT = 25 + RIGHT_EYEBROW_UPPER_MIDPOINT = 26 + LEFT_EAR_TRAGION = 27 + RIGHT_EAR_TRAGION = 28 + LEFT_EYE_PUPIL = 29 + RIGHT_EYE_PUPIL = 30 + FOREHEAD_GLABELLA = 31 + CHIN_GNATHION = 32 + CHIN_LEFT_GONION = 33 + CHIN_RIGHT_GONION = 34 + + type_ = proto.Field(proto.ENUM, number=3, enum="FaceAnnotation.Landmark.Type",) + + position = proto.Field(proto.MESSAGE, number=4, message=geometry.Position,) + + bounding_poly = proto.Field(proto.MESSAGE, number=1, message=geometry.BoundingPoly,) + + fd_bounding_poly = proto.Field( + proto.MESSAGE, number=2, message=geometry.BoundingPoly, + ) + + landmarks = proto.RepeatedField(proto.MESSAGE, number=3, message=Landmark,) + + roll_angle = proto.Field(proto.FLOAT, number=4) + + pan_angle = proto.Field(proto.FLOAT, number=5) + + tilt_angle = proto.Field(proto.FLOAT, number=6) + + detection_confidence = proto.Field(proto.FLOAT, number=7) + + landmarking_confidence = proto.Field(proto.FLOAT, number=8) + + joy_likelihood = proto.Field(proto.ENUM, number=9, enum="Likelihood",) + + sorrow_likelihood = proto.Field(proto.ENUM, number=10, enum="Likelihood",) + + anger_likelihood = proto.Field(proto.ENUM, number=11, enum="Likelihood",) + + surprise_likelihood = proto.Field(proto.ENUM, number=12, enum="Likelihood",) + + under_exposed_likelihood = proto.Field(proto.ENUM, number=13, enum="Likelihood",) + + blurred_likelihood = proto.Field(proto.ENUM, number=14, enum="Likelihood",) + + headwear_likelihood = proto.Field(proto.ENUM, number=15, enum="Likelihood",) + + +class LocationInfo(proto.Message): + r"""Detected entity location information. + + Attributes: + lat_lng (~.latlng.LatLng): + lat/long location coordinates. + """ + + lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng.LatLng,) + + +class Property(proto.Message): + r"""A ``Property`` consists of a user-supplied name/value pair. + + Attributes: + name (str): + Name of the property. + value (str): + Value of the property. + uint64_value (int): + Value of numeric properties. + """ + + name = proto.Field(proto.STRING, number=1) + + value = proto.Field(proto.STRING, number=2) + + uint64_value = proto.Field(proto.UINT64, number=3) + + +class EntityAnnotation(proto.Message): + r"""Set of detected entity features. + + Attributes: + mid (str): + Opaque entity ID. Some IDs may be available in `Google + Knowledge Graph Search + API `__. + locale (str): + The language code for the locale in which the entity textual + ``description`` is expressed. + description (str): + Entity textual description, expressed in its ``locale`` + language. + score (float): + Overall score of the result. Range [0, 1]. + confidence (float): + **Deprecated. Use ``score`` instead.** The accuracy of the + entity detection in an image. For example, for an image in + which the "Eiffel Tower" entity is detected, this field + represents the confidence that there is a tower in the query + image. Range [0, 1]. + topicality (float): + The relevancy of the ICA (Image Content Annotation) label to + the image. For example, the relevancy of "tower" is likely + higher to an image containing the detected "Eiffel Tower" + than to an image containing a detected distant towering + building, even though the confidence that there is a tower + in each image may be the same. Range [0, 1]. + bounding_poly (~.geometry.BoundingPoly): + Image region to which this entity belongs. Not produced for + ``LABEL_DETECTION`` features. + locations (Sequence[~.image_annotator.LocationInfo]): + The location information for the detected entity. Multiple + ``LocationInfo`` elements can be present because one + location may indicate the location of the scene in the + image, and another location may indicate the location of the + place where the image was taken. Location information is + usually present for landmarks. + properties (Sequence[~.image_annotator.Property]): + Some entities may have optional user-supplied ``Property`` + (name/value) fields, such a score or string that qualifies + the entity. + """ + + mid = proto.Field(proto.STRING, number=1) + + locale = proto.Field(proto.STRING, number=2) + + description = proto.Field(proto.STRING, number=3) + + score = proto.Field(proto.FLOAT, number=4) + + confidence = proto.Field(proto.FLOAT, number=5) + + topicality = proto.Field(proto.FLOAT, number=6) + + bounding_poly = proto.Field(proto.MESSAGE, number=7, message=geometry.BoundingPoly,) + + locations = proto.RepeatedField(proto.MESSAGE, number=8, message=LocationInfo,) + + properties = proto.RepeatedField(proto.MESSAGE, number=9, message=Property,) + + +class LocalizedObjectAnnotation(proto.Message): + r"""Set of detected objects with bounding boxes. + + Attributes: + mid (str): + Object ID that should align with + EntityAnnotation mid. + language_code (str): + The BCP-47 language code, such as "en-US" or "sr-Latn". For + more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + name (str): + Object name, expressed in its ``language_code`` language. + score (float): + Score of the result. Range [0, 1]. + bounding_poly (~.geometry.BoundingPoly): + Image region to which this object belongs. + This must be populated. + """ + + mid = proto.Field(proto.STRING, number=1) + + language_code = proto.Field(proto.STRING, number=2) + + name = proto.Field(proto.STRING, number=3) + + score = proto.Field(proto.FLOAT, number=4) + + bounding_poly = proto.Field(proto.MESSAGE, number=5, message=geometry.BoundingPoly,) + + +class SafeSearchAnnotation(proto.Message): + r"""Set of features pertaining to the image, computed by computer + vision methods over safe-search verticals (for example, adult, + spoof, medical, violence). + + Attributes: + adult (~.image_annotator.Likelihood): + Represents the adult content likelihood for + the image. Adult content may contain elements + such as nudity, pornographic images or cartoons, + or sexual activities. + spoof (~.image_annotator.Likelihood): + Spoof likelihood. The likelihood that an + modification was made to the image's canonical + version to make it appear funny or offensive. + medical (~.image_annotator.Likelihood): + Likelihood that this is a medical image. + violence (~.image_annotator.Likelihood): + Likelihood that this image contains violent + content. + racy (~.image_annotator.Likelihood): + Likelihood that the request image contains + racy content. Racy content may include (but is + not limited to) skimpy or sheer clothing, + strategically covered nudity, lewd or + provocative poses, or close-ups of sensitive + body areas. + """ + + adult = proto.Field(proto.ENUM, number=1, enum="Likelihood",) + + spoof = proto.Field(proto.ENUM, number=2, enum="Likelihood",) + + medical = proto.Field(proto.ENUM, number=3, enum="Likelihood",) + + violence = proto.Field(proto.ENUM, number=4, enum="Likelihood",) + + racy = proto.Field(proto.ENUM, number=9, enum="Likelihood",) + + +class LatLongRect(proto.Message): + r"""Rectangle determined by min and max ``LatLng`` pairs. + + Attributes: + min_lat_lng (~.latlng.LatLng): + Min lat/long pair. + max_lat_lng (~.latlng.LatLng): + Max lat/long pair. + """ + + min_lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng.LatLng,) + + max_lat_lng = proto.Field(proto.MESSAGE, number=2, message=latlng.LatLng,) + + +class ColorInfo(proto.Message): + r"""Color information consists of RGB channels, score, and the + fraction of the image that the color occupies in the image. + + Attributes: + color (~.gt_color.Color): + RGB components of the color. + score (float): + Image-specific score for this color. Value in range [0, 1]. + pixel_fraction (float): + The fraction of pixels the color occupies in the image. + Value in range [0, 1]. + """ + + color = proto.Field(proto.MESSAGE, number=1, message=gt_color.Color,) + + score = proto.Field(proto.FLOAT, number=2) + + pixel_fraction = proto.Field(proto.FLOAT, number=3) + + +class DominantColorsAnnotation(proto.Message): + r"""Set of dominant colors and their corresponding scores. + + Attributes: + colors (Sequence[~.image_annotator.ColorInfo]): + RGB color values with their score and pixel + fraction. + """ + + colors = proto.RepeatedField(proto.MESSAGE, number=1, message=ColorInfo,) + + +class ImageProperties(proto.Message): + r"""Stores image properties, such as dominant colors. + + Attributes: + dominant_colors (~.image_annotator.DominantColorsAnnotation): + If present, dominant colors completed + successfully. + """ + + dominant_colors = proto.Field( + proto.MESSAGE, number=1, message=DominantColorsAnnotation, + ) + + +class CropHint(proto.Message): + r"""Single crop hint that is used to generate a new crop when + serving an image. + + Attributes: + bounding_poly (~.geometry.BoundingPoly): + The bounding polygon for the crop region. The coordinates of + the bounding box are in the original image's scale, as + returned in ``ImageParams``. + confidence (float): + Confidence of this being a salient region. Range [0, 1]. + importance_fraction (float): + Fraction of importance of this salient region + with respect to the original image. + """ + + bounding_poly = proto.Field(proto.MESSAGE, number=1, message=geometry.BoundingPoly,) + + confidence = proto.Field(proto.FLOAT, number=2) + + importance_fraction = proto.Field(proto.FLOAT, number=3) + + +class CropHintsAnnotation(proto.Message): + r"""Set of crop hints that are used to generate new crops when + serving images. + + Attributes: + crop_hints (Sequence[~.image_annotator.CropHint]): + Crop hint results. + """ + + crop_hints = proto.RepeatedField(proto.MESSAGE, number=1, message=CropHint,) + + +class CropHintsParams(proto.Message): + r"""Parameters for crop hints annotation request. + + Attributes: + aspect_ratios (Sequence[float]): + Aspect ratios in floats, representing the + ratio of the width to the height of the image. + For example, if the desired aspect ratio is 4/3, + the corresponding float value should be 1.33333. + If not specified, the best possible crop is + returned. The number of provided aspect ratios + is limited to a maximum of 16; any aspect ratios + provided after the 16th are ignored. + """ + + aspect_ratios = proto.RepeatedField(proto.FLOAT, number=1) + + +class WebDetectionParams(proto.Message): + r"""Parameters for web detection request. + + Attributes: + include_geo_results (bool): + Whether to include results derived from the + geo information in the image. + """ + + include_geo_results = proto.Field(proto.BOOL, number=2) + + +class ImageContext(proto.Message): + r"""Image context and/or feature-specific parameters. + + Attributes: + lat_long_rect (~.image_annotator.LatLongRect): + Not used. + language_hints (Sequence[str]): + List of languages to use for TEXT_DETECTION. In most cases, + an empty value yields the best results since it enables + automatic language detection. For languages based on the + Latin alphabet, setting ``language_hints`` is not needed. In + rare cases, when the language of the text in the image is + known, setting a hint will help get better results (although + it will be a significant hindrance if the hint is wrong). + Text detection returns an error if one or more of the + specified languages is not one of the `supported + languages `__. + crop_hints_params (~.image_annotator.CropHintsParams): + Parameters for crop hints annotation request. + product_search_params (~.product_search.ProductSearchParams): + Parameters for product search. + web_detection_params (~.image_annotator.WebDetectionParams): + Parameters for web detection. + """ + + lat_long_rect = proto.Field(proto.MESSAGE, number=1, message=LatLongRect,) + + language_hints = proto.RepeatedField(proto.STRING, number=2) + + crop_hints_params = proto.Field(proto.MESSAGE, number=4, message=CropHintsParams,) + + product_search_params = proto.Field( + proto.MESSAGE, number=5, message=product_search.ProductSearchParams, + ) + + web_detection_params = proto.Field( + proto.MESSAGE, number=6, message=WebDetectionParams, + ) + + +class AnnotateImageRequest(proto.Message): + r"""Request for performing Google Cloud Vision API tasks over a + user-provided image, with user-requested features. + + Attributes: + image (~.image_annotator.Image): + The image to be processed. + features (Sequence[~.image_annotator.Feature]): + Requested features. + image_context (~.image_annotator.ImageContext): + Additional context that may accompany the + image. + """ + + image = proto.Field(proto.MESSAGE, number=1, message=Image,) + + features = proto.RepeatedField(proto.MESSAGE, number=2, message=Feature,) + + image_context = proto.Field(proto.MESSAGE, number=3, message=ImageContext,) + + +class ImageAnnotationContext(proto.Message): + r"""If an image was produced from a file (e.g. a PDF), this + message gives information about the source of that image. + + Attributes: + uri (str): + The URI of the file used to produce the + image. + page_number (int): + If the file was a PDF or TIFF, this field + gives the page number within the file used to + produce the image. + """ + + uri = proto.Field(proto.STRING, number=1) + + page_number = proto.Field(proto.INT32, number=2) + + +class AnnotateImageResponse(proto.Message): + r"""Response to an image annotation request. + + Attributes: + face_annotations (Sequence[~.image_annotator.FaceAnnotation]): + If present, face detection has completed + successfully. + landmark_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, landmark detection has completed + successfully. + logo_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, logo detection has completed + successfully. + label_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, label detection has completed + successfully. + localized_object_annotations (Sequence[~.image_annotator.LocalizedObjectAnnotation]): + If present, localized object detection has + completed successfully. This will be sorted + descending by confidence score. + text_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, text (OCR) detection has + completed successfully. + full_text_annotation (~.text_annotation.TextAnnotation): + If present, text (OCR) detection or document + (OCR) text detection has completed successfully. + This annotation provides the structural + hierarchy for the OCR detected text. + safe_search_annotation (~.image_annotator.SafeSearchAnnotation): + If present, safe-search annotation has + completed successfully. + image_properties_annotation (~.image_annotator.ImageProperties): + If present, image properties were extracted + successfully. + crop_hints_annotation (~.image_annotator.CropHintsAnnotation): + If present, crop hints have completed + successfully. + web_detection (~.gcv_web_detection.WebDetection): + If present, web detection has completed + successfully. + product_search_results (~.product_search.ProductSearchResults): + If present, product search has completed + successfully. + error (~.status.Status): + If set, represents the error message for the operation. Note + that filled-in image annotations are guaranteed to be + correct, even when ``error`` is set. + context (~.image_annotator.ImageAnnotationContext): + If present, contextual information is needed + to understand where this image comes from. + """ + + face_annotations = proto.RepeatedField( + proto.MESSAGE, number=1, message=FaceAnnotation, + ) + + landmark_annotations = proto.RepeatedField( + proto.MESSAGE, number=2, message=EntityAnnotation, + ) + + logo_annotations = proto.RepeatedField( + proto.MESSAGE, number=3, message=EntityAnnotation, + ) + + label_annotations = proto.RepeatedField( + proto.MESSAGE, number=4, message=EntityAnnotation, + ) + + localized_object_annotations = proto.RepeatedField( + proto.MESSAGE, number=22, message=LocalizedObjectAnnotation, + ) + + text_annotations = proto.RepeatedField( + proto.MESSAGE, number=5, message=EntityAnnotation, + ) + + full_text_annotation = proto.Field( + proto.MESSAGE, number=12, message=text_annotation.TextAnnotation, + ) + + safe_search_annotation = proto.Field( + proto.MESSAGE, number=6, message=SafeSearchAnnotation, + ) + + image_properties_annotation = proto.Field( + proto.MESSAGE, number=8, message=ImageProperties, + ) + + crop_hints_annotation = proto.Field( + proto.MESSAGE, number=11, message=CropHintsAnnotation, + ) + + web_detection = proto.Field( + proto.MESSAGE, number=13, message=gcv_web_detection.WebDetection, + ) + + product_search_results = proto.Field( + proto.MESSAGE, number=14, message=product_search.ProductSearchResults, + ) + + error = proto.Field(proto.MESSAGE, number=9, message=status.Status,) + + context = proto.Field(proto.MESSAGE, number=21, message=ImageAnnotationContext,) + + +class AnnotateFileResponse(proto.Message): + r"""Response to a single file annotation request. A file may + contain one or more images, which individually have their own + responses. + + Attributes: + input_config (~.image_annotator.InputConfig): + Information about the file for which this + response is generated. + responses (Sequence[~.image_annotator.AnnotateImageResponse]): + Individual responses to images found within + the file. + """ + + input_config = proto.Field(proto.MESSAGE, number=1, message="InputConfig",) + + responses = proto.RepeatedField( + proto.MESSAGE, number=2, message=AnnotateImageResponse, + ) + + +class BatchAnnotateImagesRequest(proto.Message): + r"""Multiple image annotation requests are batched into a single + service call. + + Attributes: + requests (Sequence[~.image_annotator.AnnotateImageRequest]): + Individual image annotation requests for this + batch. + """ + + requests = proto.RepeatedField( + proto.MESSAGE, number=1, message=AnnotateImageRequest, + ) + + +class BatchAnnotateImagesResponse(proto.Message): + r"""Response to a batch image annotation request. + + Attributes: + responses (Sequence[~.image_annotator.AnnotateImageResponse]): + Individual responses to image annotation + requests within the batch. + """ + + responses = proto.RepeatedField( + proto.MESSAGE, number=1, message=AnnotateImageResponse, + ) + + +class AsyncAnnotateFileRequest(proto.Message): + r"""An offline file annotation request. + + Attributes: + input_config (~.image_annotator.InputConfig): + Required. Information about the input file. + features (Sequence[~.image_annotator.Feature]): + Required. Requested features. + image_context (~.image_annotator.ImageContext): + Additional context that may accompany the + image(s) in the file. + output_config (~.image_annotator.OutputConfig): + Required. The desired output location and + metadata (e.g. format). + """ + + input_config = proto.Field(proto.MESSAGE, number=1, message="InputConfig",) + + features = proto.RepeatedField(proto.MESSAGE, number=2, message=Feature,) + + image_context = proto.Field(proto.MESSAGE, number=3, message=ImageContext,) + + output_config = proto.Field(proto.MESSAGE, number=4, message="OutputConfig",) + + +class AsyncAnnotateFileResponse(proto.Message): + r"""The response for a single offline file annotation request. + + Attributes: + output_config (~.image_annotator.OutputConfig): + The output location and metadata from + AsyncAnnotateFileRequest. + """ + + output_config = proto.Field(proto.MESSAGE, number=1, message="OutputConfig",) + + +class AsyncBatchAnnotateFilesRequest(proto.Message): + r"""Multiple async file annotation requests are batched into a + single service call. + + Attributes: + requests (Sequence[~.image_annotator.AsyncAnnotateFileRequest]): + Required. Individual async file annotation + requests for this batch. + """ + + requests = proto.RepeatedField( + proto.MESSAGE, number=1, message=AsyncAnnotateFileRequest, + ) + + +class AsyncBatchAnnotateFilesResponse(proto.Message): + r"""Response to an async batch file annotation request. + + Attributes: + responses (Sequence[~.image_annotator.AsyncAnnotateFileResponse]): + The list of file annotation responses, one + for each request in + AsyncBatchAnnotateFilesRequest. + """ + + responses = proto.RepeatedField( + proto.MESSAGE, number=1, message=AsyncAnnotateFileResponse, + ) + + +class InputConfig(proto.Message): + r"""The desired input location and metadata. + + Attributes: + gcs_source (~.image_annotator.GcsSource): + The Google Cloud Storage location to read the + input from. + mime_type (str): + The type of the file. Currently only + "application/pdf" and "image/tiff" are + supported. Wildcards are not supported. + """ + + gcs_source = proto.Field(proto.MESSAGE, number=1, message="GcsSource",) + + mime_type = proto.Field(proto.STRING, number=2) + + +class OutputConfig(proto.Message): + r"""The desired output location and metadata. + + Attributes: + gcs_destination (~.image_annotator.GcsDestination): + The Google Cloud Storage location to write + the output(s) to. + batch_size (int): + The max number of response protos to put into each output + JSON file on Google Cloud Storage. The valid range is [1, + 100]. If not specified, the default value is 20. + + For example, for one pdf file with 100 pages, 100 response + protos will be generated. If ``batch_size`` = 20, then 5 + json files each containing 20 response protos will be + written under the prefix ``gcs_destination``.\ ``uri``. + + Currently, batch_size only applies to GcsDestination, with + potential future support for other output configurations. + """ + + gcs_destination = proto.Field(proto.MESSAGE, number=1, message="GcsDestination",) + + batch_size = proto.Field(proto.INT32, number=2) + + +class GcsSource(proto.Message): + r"""The Google Cloud Storage location where the input will be + read from. + + Attributes: + uri (str): + Google Cloud Storage URI for the input file. + This must only be a Google Cloud Storage object. + Wildcards are not currently supported. + """ + + uri = proto.Field(proto.STRING, number=1) + + +class GcsDestination(proto.Message): + r"""The Google Cloud Storage location where the output will be + written to. + + Attributes: + uri (str): + Google Cloud Storage URI where the results will be stored. + Results will be in JSON format and preceded by its + corresponding input URI. This field can either represent a + single file, or a prefix for multiple outputs. Prefixes must + end in a ``/``. + + Examples: + + - File: gs://bucket-name/filename.json + - Prefix: gs://bucket-name/prefix/here/ + - File: gs://bucket-name/prefix/here + + If multiple outputs, each response is still + AnnotateFileResponse, each of which contains some subset of + the full list of AnnotateImageResponse. Multiple outputs can + happen if, for example, the output JSON is too large and + overflows into multiple sharded files. + """ + + uri = proto.Field(proto.STRING, number=1) + + +class OperationMetadata(proto.Message): + r"""Contains metadata for the BatchAnnotateImages operation. + + Attributes: + state (~.image_annotator.OperationMetadata.State): + Current state of the batch operation. + create_time (~.timestamp.Timestamp): + The time when the batch request was received. + update_time (~.timestamp.Timestamp): + The time when the operation result was last + updated. + """ + + class State(proto.Enum): + r"""Batch operation states.""" + STATE_UNSPECIFIED = 0 + CREATED = 1 + RUNNING = 2 + DONE = 3 + CANCELLED = 4 + + state = proto.Field(proto.ENUM, number=1, enum=State,) + + create_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + + update_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p3beta1/types/product_search.py b/google/cloud/vision_v1p3beta1/types/product_search.py new file mode 100644 index 00000000..375bd701 --- /dev/null +++ b/google/cloud/vision_v1p3beta1/types/product_search.py @@ -0,0 +1,203 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.vision_v1p3beta1.types import geometry +from google.cloud.vision_v1p3beta1.types import product_search_service +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p3beta1", + manifest={ + "ProductSearchCategory", + "ProductSearchResultsView", + "ProductSearchParams", + "ProductSearchResults", + }, +) + + +class ProductSearchCategory(proto.Enum): + r"""Supported product search categories.""" + PRODUCT_SEARCH_CATEGORY_UNSPECIFIED = 0 + SHOES = 1 + BAGS = 2 + + +class ProductSearchResultsView(proto.Enum): + r"""Specifies the fields to include in product search results.""" + BASIC = 0 + FULL = 1 + + +class ProductSearchParams(proto.Message): + r"""Parameters for a product search request. + + Attributes: + catalog_name (str): + The resource name of the catalog to search. + + Format is: ``productSearch/catalogs/CATALOG_NAME``. + category (~.product_search.ProductSearchCategory): + The category to search in. Optional. It is inferred by the + system if it is not specified. [Deprecated] Use + ``product_category``. + product_category (str): + The product category to search in. Optional. It is inferred + by the system if it is not specified. Supported values are + ``bag``, ``shoe``, ``sunglasses``, ``dress``, ``outerwear``, + ``skirt``, ``top``, ``shorts``, and ``pants``. + normalized_bounding_poly (~.geometry.NormalizedBoundingPoly): + The bounding polygon around the area of interest in the + image. Optional. If it is not specified, system discretion + will be applied. [Deprecated] Use ``bounding_poly``. + bounding_poly (~.geometry.BoundingPoly): + The bounding polygon around the area of + interest in the image. Optional. If it is not + specified, system discretion will be applied. + view (~.product_search.ProductSearchResultsView): + Specifies the verbosity of the product search results. + Optional. Defaults to ``BASIC``. + product_set (str): + The resource name of a + [ProductSet][google.cloud.vision.v1p3beta1.ProductSet] to be + searched for similar images. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID``. + product_categories (Sequence[str]): + The list of product categories to search in. + Currently, we only consider the first category, + and either "homegoods" or "apparel" should be + specified. + filter (str): + The filtering expression. This can be used to + restrict search results based on Product labels. + We currently support an AND of OR of key-value + expressions, where each expression within an OR + must have the same key. + For example, "(color = red OR color = blue) AND + brand = Google" is acceptable, but not "(color = + red OR brand = Google)" or "color: red". + """ + + catalog_name = proto.Field(proto.STRING, number=1) + + category = proto.Field(proto.ENUM, number=2, enum="ProductSearchCategory",) + + product_category = proto.Field(proto.STRING, number=5) + + normalized_bounding_poly = proto.Field( + proto.MESSAGE, number=3, message=geometry.NormalizedBoundingPoly, + ) + + bounding_poly = proto.Field(proto.MESSAGE, number=9, message=geometry.BoundingPoly,) + + view = proto.Field(proto.ENUM, number=4, enum="ProductSearchResultsView",) + + product_set = proto.Field(proto.STRING, number=6) + + product_categories = proto.RepeatedField(proto.STRING, number=7) + + filter = proto.Field(proto.STRING, number=8) + + +class ProductSearchResults(proto.Message): + r"""Results for a product search request. + + Attributes: + category (~.product_search.ProductSearchCategory): + Product category. [Deprecated] Use ``product_category``. + product_category (str): + Product category. Supported values are ``bag`` and ``shoe``. + [Deprecated] ``product_category`` is provided in each + Product. + index_time (~.timestamp.Timestamp): + Timestamp of the index which provided these + results. Changes made after this time are not + reflected in the current results. + products (Sequence[~.product_search.ProductSearchResults.ProductInfo]): + List of detected products. + results (Sequence[~.product_search.ProductSearchResults.Result]): + List of results, one for each product match. + """ + + class ProductInfo(proto.Message): + r"""Information about a product. + + Attributes: + product_id (str): + Product ID. + image_uri (str): + The URI of the image which matched the query image. + + This field is returned only if ``view`` is set to ``FULL`` + in the request. + score (float): + A confidence level on the match, ranging from 0 (no + confidence) to 1 (full confidence). + + This field is returned only if ``view`` is set to ``FULL`` + in the request. + """ + + product_id = proto.Field(proto.STRING, number=1) + + image_uri = proto.Field(proto.STRING, number=2) + + score = proto.Field(proto.FLOAT, number=3) + + class Result(proto.Message): + r"""Information about a product. + + Attributes: + product (~.product_search_service.Product): + The Product. + score (float): + A confidence level on the match, ranging from 0 (no + confidence) to 1 (full confidence). + + This field is returned only if ``view`` is set to ``FULL`` + in the request. + image (str): + The resource name of the image from the + product that is the closest match to the query. + """ + + product = proto.Field( + proto.MESSAGE, number=1, message=product_search_service.Product, + ) + + score = proto.Field(proto.FLOAT, number=2) + + image = proto.Field(proto.STRING, number=3) + + category = proto.Field(proto.ENUM, number=1, enum="ProductSearchCategory",) + + product_category = proto.Field(proto.STRING, number=4) + + index_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + products = proto.RepeatedField(proto.MESSAGE, number=3, message=ProductInfo,) + + results = proto.RepeatedField(proto.MESSAGE, number=5, message=Result,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p3beta1/types/product_search_service.py b/google/cloud/vision_v1p3beta1/types/product_search_service.py new file mode 100644 index 00000000..0be4fa6c --- /dev/null +++ b/google/cloud/vision_v1p3beta1/types/product_search_service.py @@ -0,0 +1,825 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.vision_v1p3beta1.types import geometry +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p3beta1", + manifest={ + "Product", + "ProductSet", + "ReferenceImage", + "CreateProductRequest", + "ListProductsRequest", + "ListProductsResponse", + "GetProductRequest", + "UpdateProductRequest", + "DeleteProductRequest", + "CreateProductSetRequest", + "ListProductSetsRequest", + "ListProductSetsResponse", + "GetProductSetRequest", + "UpdateProductSetRequest", + "DeleteProductSetRequest", + "CreateReferenceImageRequest", + "ListReferenceImagesRequest", + "ListReferenceImagesResponse", + "GetReferenceImageRequest", + "DeleteReferenceImageRequest", + "AddProductToProductSetRequest", + "RemoveProductFromProductSetRequest", + "ListProductsInProductSetRequest", + "ListProductsInProductSetResponse", + "ImportProductSetsGcsSource", + "ImportProductSetsInputConfig", + "ImportProductSetsRequest", + "ImportProductSetsResponse", + "BatchOperationMetadata", + }, +) + + +class Product(proto.Message): + r"""A Product contains ReferenceImages. + + Attributes: + name (str): + The resource name of the product. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + + This field is ignored when creating a product. + display_name (str): + The user-provided name for this Product. Must + not be empty. Must be at most 4096 characters + long. + description (str): + User-provided metadata to be stored with this + product. Must be at most 4096 characters long. + product_category (str): + Immutable. The category for the product + identified by the reference image. This should + be either "homegoods-v2", "apparel-v2", or + "toys-v2". The legacy categories "homegoods", + "apparel", and "toys" are still supported, but + these should not be used for new products. + product_labels (Sequence[~.product_search_service.Product.KeyValue]): + Key-value pairs that can be attached to a product. At query + time, constraints can be specified based on the + product_labels. + + Note that integer values can be provided as strings, e.g. + "1199". Only strings with integer values can match a + range-based restriction which is to be supported soon. + + Multiple values can be assigned to the same key. One product + may have up to 100 product_labels. + """ + + class KeyValue(proto.Message): + r"""A product label represented as a key-value pair. + + Attributes: + key (str): + The key of the label attached to the product. + Cannot be empty and cannot exceed 128 bytes. + value (str): + The value of the label attached to the + product. Cannot be empty and cannot exceed 128 + bytes. + """ + + key = proto.Field(proto.STRING, number=1) + + value = proto.Field(proto.STRING, number=2) + + name = proto.Field(proto.STRING, number=1) + + display_name = proto.Field(proto.STRING, number=2) + + description = proto.Field(proto.STRING, number=3) + + product_category = proto.Field(proto.STRING, number=4) + + product_labels = proto.RepeatedField(proto.MESSAGE, number=5, message=KeyValue,) + + +class ProductSet(proto.Message): + r"""A ProductSet contains Products. A ProductSet can contain a + maximum of 1 million reference images. If the limit is exceeded, + periodic indexing will fail. + + Attributes: + name (str): + The resource name of the ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID``. + + This field is ignored when creating a ProductSet. + display_name (str): + The user-provided name for this ProductSet. + Must not be empty. Must be at most 4096 + characters long. + index_time (~.timestamp.Timestamp): + Output only. The time at which this + ProductSet was last indexed. Query results will + reflect all updates before this time. If this + ProductSet has never been indexed, this field is + 0. + + This field is ignored when creating a + ProductSet. + index_error (~.status.Status): + Output only. If there was an error with + indexing the product set, the field is + populated. + This field is ignored when creating a + ProductSet. + """ + + name = proto.Field(proto.STRING, number=1) + + display_name = proto.Field(proto.STRING, number=2) + + index_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + index_error = proto.Field(proto.MESSAGE, number=4, message=status.Status,) + + +class ReferenceImage(proto.Message): + r"""A ``ReferenceImage`` represents a product image and its associated + metadata, such as bounding boxes. + + Attributes: + name (str): + The resource name of the reference image. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. + + This field is ignored when creating a reference image. + uri (str): + Required. The Google Cloud Storage URI of the reference + image. + + The URI must start with ``gs://``. + bounding_polys (Sequence[~.geometry.BoundingPoly]): + Optional. Bounding polygons around the areas + of interest in the reference image. If this + field is empty, the system will try to detect + regions of interest. At most 10 bounding + polygons will be used. + The provided shape is converted into a non- + rotated rectangle. Once converted, the small + edge of the rectangle must be greater than or + equal to 300 pixels. The aspect ratio must be + 1:4 or less (i.e. 1:3 is ok; 1:5 is not). + """ + + name = proto.Field(proto.STRING, number=1) + + uri = proto.Field(proto.STRING, number=2) + + bounding_polys = proto.RepeatedField( + proto.MESSAGE, number=3, message=geometry.BoundingPoly, + ) + + +class CreateProductRequest(proto.Message): + r"""Request message for the ``CreateProduct`` method. + + Attributes: + parent (str): + Required. The project in which the Product should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + product (~.product_search_service.Product): + Required. The product to create. + product_id (str): + A user-supplied resource id for this Product. If set, the + server will attempt to use this value as the resource id. If + it is already in use, an error is returned with code + ALREADY_EXISTS. Must be at most 128 characters long. It + cannot contain the character ``/``. + """ + + parent = proto.Field(proto.STRING, number=1) + + product = proto.Field(proto.MESSAGE, number=2, message=Product,) + + product_id = proto.Field(proto.STRING, number=3) + + +class ListProductsRequest(proto.Message): + r"""Request message for the ``ListProducts`` method. + + Attributes: + parent (str): + Required. The project OR ProductSet from which Products + should be listed. + + Format: ``projects/PROJECT_ID/locations/LOC_ID`` + page_size (int): + The maximum number of items to return. + Default 10, maximum 100. + page_token (str): + The next_page_token returned from a previous List request, + if any. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListProductsResponse(proto.Message): + r"""Response message for the ``ListProducts`` method. + + Attributes: + products (Sequence[~.product_search_service.Product]): + List of products. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + products = proto.RepeatedField(proto.MESSAGE, number=1, message=Product,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetProductRequest(proto.Message): + r"""Request message for the ``GetProduct`` method. + + Attributes: + name (str): + Required. Resource name of the Product to get. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + +class UpdateProductRequest(proto.Message): + r"""Request message for the ``UpdateProduct`` method. + + Attributes: + product (~.product_search_service.Product): + Required. The Product resource which replaces + the one on the server. product.name is + immutable. + update_mask (~.field_mask.FieldMask): + The [FieldMask][google.protobuf.FieldMask] that specifies + which fields to update. If update_mask isn't specified, all + mutable fields are to be updated. Valid mask paths include + ``product_labels``, ``display_name``, and ``description``. + """ + + product = proto.Field(proto.MESSAGE, number=1, message=Product,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class DeleteProductRequest(proto.Message): + r"""Request message for the ``DeleteProduct`` method. + + Attributes: + name (str): + Required. Resource name of product to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + +class CreateProductSetRequest(proto.Message): + r"""Request message for the ``CreateProductSet`` method. + + Attributes: + parent (str): + Required. The project in which the ProductSet should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + product_set (~.product_search_service.ProductSet): + Required. The ProductSet to create. + product_set_id (str): + A user-supplied resource id for this ProductSet. If set, the + server will attempt to use this value as the resource id. If + it is already in use, an error is returned with code + ALREADY_EXISTS. Must be at most 128 characters long. It + cannot contain the character ``/``. + """ + + parent = proto.Field(proto.STRING, number=1) + + product_set = proto.Field(proto.MESSAGE, number=2, message=ProductSet,) + + product_set_id = proto.Field(proto.STRING, number=3) + + +class ListProductSetsRequest(proto.Message): + r"""Request message for the ``ListProductSets`` method. + + Attributes: + parent (str): + Required. The project from which ProductSets should be + listed. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + page_size (int): + The maximum number of items to return. + Default 10, maximum 100. + page_token (str): + The next_page_token returned from a previous List request, + if any. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListProductSetsResponse(proto.Message): + r"""Response message for the ``ListProductSets`` method. + + Attributes: + product_sets (Sequence[~.product_search_service.ProductSet]): + List of ProductSets. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + product_sets = proto.RepeatedField(proto.MESSAGE, number=1, message=ProductSet,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetProductSetRequest(proto.Message): + r"""Request message for the ``GetProductSet`` method. + + Attributes: + name (str): + Required. Resource name of the ProductSet to get. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + +class UpdateProductSetRequest(proto.Message): + r"""Request message for the ``UpdateProductSet`` method. + + Attributes: + product_set (~.product_search_service.ProductSet): + Required. The ProductSet resource which + replaces the one on the server. + update_mask (~.field_mask.FieldMask): + The [FieldMask][google.protobuf.FieldMask] that specifies + which fields to update. If update_mask isn't specified, all + mutable fields are to be updated. Valid mask path is + ``display_name``. + """ + + product_set = proto.Field(proto.MESSAGE, number=1, message=ProductSet,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class DeleteProductSetRequest(proto.Message): + r"""Request message for the ``DeleteProductSet`` method. + + Attributes: + name (str): + Required. Resource name of the ProductSet to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + +class CreateReferenceImageRequest(proto.Message): + r"""Request message for the ``CreateReferenceImage`` method. + + Attributes: + parent (str): + Required. Resource name of the product in which to create + the reference image. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + reference_image (~.product_search_service.ReferenceImage): + Required. The reference image to create. + If an image ID is specified, it is ignored. + reference_image_id (str): + A user-supplied resource id for the ReferenceImage to be + added. If set, the server will attempt to use this value as + the resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + """ + + parent = proto.Field(proto.STRING, number=1) + + reference_image = proto.Field(proto.MESSAGE, number=2, message=ReferenceImage,) + + reference_image_id = proto.Field(proto.STRING, number=3) + + +class ListReferenceImagesRequest(proto.Message): + r"""Request message for the ``ListReferenceImages`` method. + + Attributes: + parent (str): + Required. Resource name of the product containing the + reference images. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + page_size (int): + The maximum number of items to return. + Default 10, maximum 100. + page_token (str): + A token identifying a page of results to be returned. This + is the value of ``nextPageToken`` returned in a previous + reference image list request. + + Defaults to the first page if not specified. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListReferenceImagesResponse(proto.Message): + r"""Response message for the ``ListReferenceImages`` method. + + Attributes: + reference_images (Sequence[~.product_search_service.ReferenceImage]): + The list of reference images. + page_size (int): + The maximum number of items to return. + Default 10, maximum 100. + next_page_token (str): + The next_page_token returned from a previous List request, + if any. + """ + + @property + def raw_page(self): + return self + + reference_images = proto.RepeatedField( + proto.MESSAGE, number=1, message=ReferenceImage, + ) + + page_size = proto.Field(proto.INT32, number=2) + + next_page_token = proto.Field(proto.STRING, number=3) + + +class GetReferenceImageRequest(proto.Message): + r"""Request message for the ``GetReferenceImage`` method. + + Attributes: + name (str): + Required. The resource name of the ReferenceImage to get. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class DeleteReferenceImageRequest(proto.Message): + r"""Request message for the ``DeleteReferenceImage`` method. + + Attributes: + name (str): + Required. The resource name of the reference image to + delete. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + +class AddProductToProductSetRequest(proto.Message): + r"""Request message for the ``AddProductToProductSet`` method. + + Attributes: + name (str): + Required. The resource name for the ProductSet to modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + product (str): + Required. The resource name for the Product to be added to + this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + product = proto.Field(proto.STRING, number=2) + + +class RemoveProductFromProductSetRequest(proto.Message): + r"""Request message for the ``RemoveProductFromProductSet`` method. + + Attributes: + name (str): + Required. The resource name for the ProductSet to modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + product (str): + Required. The resource name for the Product to be removed + from this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + product = proto.Field(proto.STRING, number=2) + + +class ListProductsInProductSetRequest(proto.Message): + r"""Request message for the ``ListProductsInProductSet`` method. + + Attributes: + name (str): + Required. The ProductSet resource for which to retrieve + Products. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + page_size (int): + The maximum number of items to return. + Default 10, maximum 100. + page_token (str): + The next_page_token returned from a previous List request, + if any. + """ + + name = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListProductsInProductSetResponse(proto.Message): + r"""Response message for the ``ListProductsInProductSet`` method. + + Attributes: + products (Sequence[~.product_search_service.Product]): + The list of Products. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + products = proto.RepeatedField(proto.MESSAGE, number=1, message=Product,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class ImportProductSetsGcsSource(proto.Message): + r"""The Google Cloud Storage location for a csv file which + preserves a list of ImportProductSetRequests in each line. + + Attributes: + csv_file_uri (str): + The Google Cloud Storage URI of the input csv file. + + The URI must start with ``gs://``. + + The format of the input csv file should be one image per + line. In each line, there are 6 columns. + + 1. image_uri 2, image_id + 2. product_set_id + 3. product_id 5, product_category 6, product_display_name 7, + labels + 4. bounding_poly + + Columns 1, 3, 4, and 5 are required, other columns are + optional. A new ProductSet/Product with the same id will be + created on the fly if the ProductSet/Product specified by + product_set_id/product_id does not exist. + + The image_id field is optional but has to be unique if + provided. If it is empty, we will automatically assign an + unique id to the image. + + The product_display_name field is optional. If it is empty, + a space (" ") is used as the place holder for the product + display_name, which can be updated later through the + realtime API. + + If the Product with product_id already exists, the fields + product_display_name, product_category and labels are + ignored. + + If a Product doesn't exist and needs to be created on the + fly, the product_display_name field refers to + [Product.display_name][google.cloud.vision.v1p3beta1.Product.display_name], + the product_category field refers to + [Product.product_category][google.cloud.vision.v1p3beta1.Product.product_category], + and the labels field refers to [Product.labels][]. + + Labels (optional) should be a line containing a list of + comma-separated key-value pairs, with the format + "key_1=value_1,key_2=value_2,...,key_n=value_n". + + The bounding_poly (optional) field is used to identify one + region of interest from the image in the same manner as + CreateReferenceImage. If no bounding_poly is specified, the + system will try to detect regions of interest automatically. + + Note that the pipeline will resize the image if the image + resolution is too large to process (above 20MP). + + Also note that at most one bounding_poly is allowed per + line. If the image contains multiple regions of interest, + the csv should contain one line per region of interest. + + The bounding_poly column should contain an even number of + comma-separated numbers, with the format + "p1_x,p1_y,p2_x,p2_y,...,pn_x,pn_y". Nonnegative integers + should be used for absolute bounding polygons, and float + values in [0, 1] should be used for normalized bounding + polygons. + """ + + csv_file_uri = proto.Field(proto.STRING, number=1) + + +class ImportProductSetsInputConfig(proto.Message): + r"""The input content for the ``ImportProductSets`` method. + + Attributes: + gcs_source (~.product_search_service.ImportProductSetsGcsSource): + The Google Cloud Storage location for a csv + file which preserves a list of + ImportProductSetRequests in each line. + """ + + gcs_source = proto.Field( + proto.MESSAGE, number=1, oneof="source", message=ImportProductSetsGcsSource, + ) + + +class ImportProductSetsRequest(proto.Message): + r"""Request message for the ``ImportProductSets`` method. + + Attributes: + parent (str): + Required. The project in which the ProductSets should be + imported. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + input_config (~.product_search_service.ImportProductSetsInputConfig): + Required. The input content for the list of + requests. + """ + + parent = proto.Field(proto.STRING, number=1) + + input_config = proto.Field( + proto.MESSAGE, number=2, message=ImportProductSetsInputConfig, + ) + + +class ImportProductSetsResponse(proto.Message): + r"""Response message for the ``ImportProductSets`` method. + + This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + Attributes: + reference_images (Sequence[~.product_search_service.ReferenceImage]): + The list of reference_images that are imported successfully. + statuses (Sequence[~.status.Status]): + The rpc status for each ImportProductSet request, including + both successes and errors. + + The number of statuses here matches the number of lines in + the csv file, and statuses[i] stores the success or failure + status of processing the i-th line of the csv, starting from + line 0. + """ + + reference_images = proto.RepeatedField( + proto.MESSAGE, number=1, message=ReferenceImage, + ) + + statuses = proto.RepeatedField(proto.MESSAGE, number=2, message=status.Status,) + + +class BatchOperationMetadata(proto.Message): + r"""Metadata for the batch operations such as the current state. + + This is included in the ``metadata`` field of the ``Operation`` + returned by the ``GetOperation`` call of the + ``google::longrunning::Operations`` service. + + Attributes: + state (~.product_search_service.BatchOperationMetadata.State): + The current state of the batch operation. + submit_time (~.timestamp.Timestamp): + The time when the batch request was submitted + to the server. + end_time (~.timestamp.Timestamp): + The time when the batch request is finished and + [google.longrunning.Operation.done][google.longrunning.Operation.done] + is set to true. + """ + + class State(proto.Enum): + r"""Enumerates the possible states that the batch request can be + in. + """ + STATE_UNSPECIFIED = 0 + PROCESSING = 1 + SUCCESSFUL = 2 + FAILED = 3 + CANCELLED = 4 + + state = proto.Field(proto.ENUM, number=1, enum=State,) + + submit_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p3beta1/types/text_annotation.py b/google/cloud/vision_v1p3beta1/types/text_annotation.py new file mode 100644 index 00000000..1c3c212e --- /dev/null +++ b/google/cloud/vision_v1p3beta1/types/text_annotation.py @@ -0,0 +1,320 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.vision_v1p3beta1.types import geometry + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p3beta1", + manifest={"TextAnnotation", "Page", "Block", "Paragraph", "Word", "Symbol",}, +) + + +class TextAnnotation(proto.Message): + r"""TextAnnotation contains a structured representation of OCR extracted + text. The hierarchy of an OCR extracted text structure is like this: + TextAnnotation -> Page -> Block -> Paragraph -> Word -> Symbol Each + structural component, starting from Page, may further have their own + properties. Properties describe detected languages, breaks etc.. + Please refer to the + [TextAnnotation.TextProperty][google.cloud.vision.v1p3beta1.TextAnnotation.TextProperty] + message definition below for more detail. + + Attributes: + pages (Sequence[~.text_annotation.Page]): + List of pages detected by OCR. + text (str): + UTF-8 text detected on the pages. + """ + + class DetectedLanguage(proto.Message): + r"""Detected language for a structural component. + + Attributes: + language_code (str): + The BCP-47 language code, such as "en-US" or "sr-Latn". For + more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + confidence (float): + Confidence of detected language. Range [0, 1]. + """ + + language_code = proto.Field(proto.STRING, number=1) + + confidence = proto.Field(proto.FLOAT, number=2) + + class DetectedBreak(proto.Message): + r"""Detected start or end of a structural component. + + Attributes: + type_ (~.text_annotation.TextAnnotation.DetectedBreak.BreakType): + Detected break type. + is_prefix (bool): + True if break prepends the element. + """ + + class BreakType(proto.Enum): + r"""Enum to denote the type of break found. New line, space etc.""" + UNKNOWN = 0 + SPACE = 1 + SURE_SPACE = 2 + EOL_SURE_SPACE = 3 + HYPHEN = 4 + LINE_BREAK = 5 + + type_ = proto.Field( + proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", + ) + + is_prefix = proto.Field(proto.BOOL, number=2) + + class TextProperty(proto.Message): + r"""Additional information detected on the structural component. + + Attributes: + detected_languages (Sequence[~.text_annotation.TextAnnotation.DetectedLanguage]): + A list of detected languages together with + confidence. + detected_break (~.text_annotation.TextAnnotation.DetectedBreak): + Detected start or end of a text segment. + """ + + detected_languages = proto.RepeatedField( + proto.MESSAGE, number=1, message="TextAnnotation.DetectedLanguage", + ) + + detected_break = proto.Field( + proto.MESSAGE, number=2, message="TextAnnotation.DetectedBreak", + ) + + pages = proto.RepeatedField(proto.MESSAGE, number=1, message="Page",) + + text = proto.Field(proto.STRING, number=2) + + +class Page(proto.Message): + r"""Detected page from OCR. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected on the page. + width (int): + Page width. For PDFs the unit is points. For + images (including TIFFs) the unit is pixels. + height (int): + Page height. For PDFs the unit is points. For + images (including TIFFs) the unit is pixels. + blocks (Sequence[~.text_annotation.Block]): + List of blocks of text, images etc on this + page. + confidence (float): + Confidence of the OCR results on the page. Range [0, 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + width = proto.Field(proto.INT32, number=2) + + height = proto.Field(proto.INT32, number=3) + + blocks = proto.RepeatedField(proto.MESSAGE, number=4, message="Block",) + + confidence = proto.Field(proto.FLOAT, number=5) + + +class Block(proto.Message): + r"""Logical element on the page. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the + block. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the block. The vertices are in the + order of top-left, top-right, bottom-right, bottom-left. + When a rotation of the bounding box is detected the rotation + is represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: + + :: + + 0----1 + | | + 3----2 + + - when it's rotated 180 degrees around the top-left corner + it becomes: + + :: + + 2----3 + | | + 1----0 + + and the vertice order will still be (0, 1, 2, 3). + paragraphs (Sequence[~.text_annotation.Paragraph]): + List of paragraphs in this block (if this + blocks is of type text). + block_type (~.text_annotation.Block.BlockType): + Detected block type (text, image etc) for + this block. + confidence (float): + Confidence of the OCR results on the block. Range [0, 1]. + """ + + class BlockType(proto.Enum): + r"""Type of a block (text, image etc) as identified by OCR.""" + UNKNOWN = 0 + TEXT = 1 + TABLE = 2 + PICTURE = 3 + RULER = 4 + BARCODE = 5 + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + paragraphs = proto.RepeatedField(proto.MESSAGE, number=3, message="Paragraph",) + + block_type = proto.Field(proto.ENUM, number=4, enum=BlockType,) + + confidence = proto.Field(proto.FLOAT, number=5) + + +class Paragraph(proto.Message): + r"""Structural unit of text representing a number of words in + certain order. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the + paragraph. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the paragraph. The vertices are in the + order of top-left, top-right, bottom-right, bottom-left. + When a rotation of the bounding box is detected the rotation + is represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). + words (Sequence[~.text_annotation.Word]): + List of words in this paragraph. + confidence (float): + Confidence of the OCR results for the paragraph. Range [0, + 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + words = proto.RepeatedField(proto.MESSAGE, number=3, message="Word",) + + confidence = proto.Field(proto.FLOAT, number=4) + + +class Word(proto.Message): + r"""A word representation. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the word. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the word. The vertices are in the order + of top-left, top-right, bottom-right, bottom-left. When a + rotation of the bounding box is detected the rotation is + represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). + symbols (Sequence[~.text_annotation.Symbol]): + List of symbols in the word. + The order of the symbols follows the natural + reading order. + confidence (float): + Confidence of the OCR results for the word. Range [0, 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + symbols = proto.RepeatedField(proto.MESSAGE, number=3, message="Symbol",) + + confidence = proto.Field(proto.FLOAT, number=4) + + +class Symbol(proto.Message): + r"""A single symbol representation. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the + symbol. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the symbol. The vertices are in the + order of top-left, top-right, bottom-right, bottom-left. + When a rotation of the bounding box is detected the rotation + is represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertice order + will still be (0, 1, 2, 3). + text (str): + The actual UTF-8 representation of the + symbol. + confidence (float): + Confidence of the OCR results for the symbol. Range [0, 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + text = proto.Field(proto.STRING, number=3) + + confidence = proto.Field(proto.FLOAT, number=4) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p3beta1/types/web_detection.py b/google/cloud/vision_v1p3beta1/types/web_detection.py new file mode 100644 index 00000000..6a24d5c2 --- /dev/null +++ b/google/cloud/vision_v1p3beta1/types/web_detection.py @@ -0,0 +1,161 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p3beta1", manifest={"WebDetection",}, +) + + +class WebDetection(proto.Message): + r"""Relevant information for the image from the Internet. + + Attributes: + web_entities (Sequence[~.web_detection.WebDetection.WebEntity]): + Deduced entities from similar images on the + Internet. + full_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Fully matching images from the Internet. + Can include resized copies of the query image. + partial_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Partial matching images from the Internet. + Those images are similar enough to share some + key-point features. For example an original + image will likely have partial matching for its + crops. + pages_with_matching_images (Sequence[~.web_detection.WebDetection.WebPage]): + Web pages containing the matching images from + the Internet. + visually_similar_images (Sequence[~.web_detection.WebDetection.WebImage]): + The visually similar image results. + best_guess_labels (Sequence[~.web_detection.WebDetection.WebLabel]): + Best guess text labels for the request image. + """ + + class WebEntity(proto.Message): + r"""Entity deduced from similar images on the Internet. + + Attributes: + entity_id (str): + Opaque entity ID. + score (float): + Overall relevancy score for the entity. + Not normalized and not comparable across + different image queries. + description (str): + Canonical description of the entity, in + English. + """ + + entity_id = proto.Field(proto.STRING, number=1) + + score = proto.Field(proto.FLOAT, number=2) + + description = proto.Field(proto.STRING, number=3) + + class WebImage(proto.Message): + r"""Metadata for online images. + + Attributes: + url (str): + The result image URL. + score (float): + (Deprecated) Overall relevancy score for the + image. + """ + + url = proto.Field(proto.STRING, number=1) + + score = proto.Field(proto.FLOAT, number=2) + + class WebPage(proto.Message): + r"""Metadata for web pages. + + Attributes: + url (str): + The result web page URL. + score (float): + (Deprecated) Overall relevancy score for the + web page. + page_title (str): + Title for the web page, may contain HTML + markups. + full_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Fully matching images on the page. + Can include resized copies of the query image. + partial_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Partial matching images on the page. + Those images are similar enough to share some + key-point features. For example an original + image will likely have partial matching for its + crops. + """ + + url = proto.Field(proto.STRING, number=1) + + score = proto.Field(proto.FLOAT, number=2) + + page_title = proto.Field(proto.STRING, number=3) + + full_matching_images = proto.RepeatedField( + proto.MESSAGE, number=4, message="WebDetection.WebImage", + ) + + partial_matching_images = proto.RepeatedField( + proto.MESSAGE, number=5, message="WebDetection.WebImage", + ) + + class WebLabel(proto.Message): + r"""Label to provide extra metadata for the web detection. + + Attributes: + label (str): + Label for extra metadata. + language_code (str): + The BCP-47 language code for ``label``, such as "en-US" or + "sr-Latn". For more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + """ + + label = proto.Field(proto.STRING, number=1) + + language_code = proto.Field(proto.STRING, number=2) + + web_entities = proto.RepeatedField(proto.MESSAGE, number=1, message=WebEntity,) + + full_matching_images = proto.RepeatedField( + proto.MESSAGE, number=2, message=WebImage, + ) + + partial_matching_images = proto.RepeatedField( + proto.MESSAGE, number=3, message=WebImage, + ) + + pages_with_matching_images = proto.RepeatedField( + proto.MESSAGE, number=4, message=WebPage, + ) + + visually_similar_images = proto.RepeatedField( + proto.MESSAGE, number=6, message=WebImage, + ) + + best_guess_labels = proto.RepeatedField(proto.MESSAGE, number=8, message=WebLabel,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p4beta1/__init__.py b/google/cloud/vision_v1p4beta1/__init__.py index 7050e0b0..ff3c3fb5 100644 --- a/google/cloud/vision_v1p4beta1/__init__.py +++ b/google/cloud/vision_v1p4beta1/__init__.py @@ -1,56 +1,206 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # -# https://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - - -from __future__ import absolute_import +# from google.cloud.vision_helpers.decorators import add_single_feature_methods from google.cloud.vision_helpers import VisionHelpers -import sys -import warnings - -from google.cloud.vision_v1p4beta1 import types -from google.cloud.vision_v1p4beta1.gapic import enums -from google.cloud.vision_v1p4beta1.gapic import image_annotator_client as iac -from google.cloud.vision_v1p4beta1.gapic import product_search_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - -class ProductSearchClient(product_search_client.ProductSearchClient): - __doc__ = product_search_client.ProductSearchClient.__doc__ - enums = enums +from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient +from .services.product_search import ProductSearchClient +from .types.face import Celebrity +from .types.face import FaceRecognitionParams +from .types.face import FaceRecognitionResult +from .types.geometry import BoundingPoly +from .types.geometry import NormalizedVertex +from .types.geometry import Position +from .types.geometry import Vertex +from .types.image_annotator import AnnotateFileRequest +from .types.image_annotator import AnnotateFileResponse +from .types.image_annotator import AnnotateImageRequest +from .types.image_annotator import AnnotateImageResponse +from .types.image_annotator import AsyncAnnotateFileRequest +from .types.image_annotator import AsyncAnnotateFileResponse +from .types.image_annotator import AsyncBatchAnnotateFilesRequest +from .types.image_annotator import AsyncBatchAnnotateFilesResponse +from .types.image_annotator import AsyncBatchAnnotateImagesRequest +from .types.image_annotator import AsyncBatchAnnotateImagesResponse +from .types.image_annotator import BatchAnnotateFilesRequest +from .types.image_annotator import BatchAnnotateFilesResponse +from .types.image_annotator import BatchAnnotateImagesRequest +from .types.image_annotator import BatchAnnotateImagesResponse +from .types.image_annotator import ColorInfo +from .types.image_annotator import CropHint +from .types.image_annotator import CropHintsAnnotation +from .types.image_annotator import CropHintsParams +from .types.image_annotator import DominantColorsAnnotation +from .types.image_annotator import EntityAnnotation +from .types.image_annotator import FaceAnnotation +from .types.image_annotator import Feature +from .types.image_annotator import GcsDestination +from .types.image_annotator import GcsSource +from .types.image_annotator import Image +from .types.image_annotator import ImageAnnotationContext +from .types.image_annotator import ImageContext +from .types.image_annotator import ImageProperties +from .types.image_annotator import ImageSource +from .types.image_annotator import InputConfig +from .types.image_annotator import LatLongRect +from .types.image_annotator import Likelihood +from .types.image_annotator import LocalizedObjectAnnotation +from .types.image_annotator import LocationInfo +from .types.image_annotator import OperationMetadata +from .types.image_annotator import OutputConfig +from .types.image_annotator import Property +from .types.image_annotator import SafeSearchAnnotation +from .types.image_annotator import WebDetectionParams +from .types.product_search import ProductSearchParams +from .types.product_search import ProductSearchResults +from .types.product_search_service import AddProductToProductSetRequest +from .types.product_search_service import BatchOperationMetadata +from .types.product_search_service import CreateProductRequest +from .types.product_search_service import CreateProductSetRequest +from .types.product_search_service import CreateReferenceImageRequest +from .types.product_search_service import DeleteProductRequest +from .types.product_search_service import DeleteProductSetRequest +from .types.product_search_service import DeleteReferenceImageRequest +from .types.product_search_service import GetProductRequest +from .types.product_search_service import GetProductSetRequest +from .types.product_search_service import GetReferenceImageRequest +from .types.product_search_service import ImportProductSetsGcsSource +from .types.product_search_service import ImportProductSetsInputConfig +from .types.product_search_service import ImportProductSetsRequest +from .types.product_search_service import ImportProductSetsResponse +from .types.product_search_service import ListProductSetsRequest +from .types.product_search_service import ListProductSetsResponse +from .types.product_search_service import ListProductsInProductSetRequest +from .types.product_search_service import ListProductsInProductSetResponse +from .types.product_search_service import ListProductsRequest +from .types.product_search_service import ListProductsResponse +from .types.product_search_service import ListReferenceImagesRequest +from .types.product_search_service import ListReferenceImagesResponse +from .types.product_search_service import Product +from .types.product_search_service import ProductSet +from .types.product_search_service import ProductSetPurgeConfig +from .types.product_search_service import PurgeProductsRequest +from .types.product_search_service import ReferenceImage +from .types.product_search_service import RemoveProductFromProductSetRequest +from .types.product_search_service import UpdateProductRequest +from .types.product_search_service import UpdateProductSetRequest +from .types.text_annotation import Block +from .types.text_annotation import Page +from .types.text_annotation import Paragraph +from .types.text_annotation import Symbol +from .types.text_annotation import TextAnnotation +from .types.text_annotation import Word +from .types.web_detection import WebDetection @add_single_feature_methods -class ImageAnnotatorClient(VisionHelpers, iac.ImageAnnotatorClient): - __doc__ = iac.ImageAnnotatorClient.__doc__ - enums = enums +class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): + __doc__ = IacImageAnnotatorClient.__doc__ + Feature = Feature __all__ = ( - "enums", - "types", + "AddProductToProductSetRequest", + "AnnotateFileRequest", + "AnnotateFileResponse", + "AnnotateImageRequest", + "AnnotateImageResponse", + "AsyncAnnotateFileRequest", + "AsyncAnnotateFileResponse", + "AsyncBatchAnnotateFilesRequest", + "AsyncBatchAnnotateFilesResponse", + "AsyncBatchAnnotateImagesRequest", + "AsyncBatchAnnotateImagesResponse", + "BatchAnnotateFilesRequest", + "BatchAnnotateFilesResponse", + "BatchAnnotateImagesRequest", + "BatchAnnotateImagesResponse", + "BatchOperationMetadata", + "Block", + "BoundingPoly", + "Celebrity", + "ColorInfo", + "CreateProductRequest", + "CreateProductSetRequest", + "CreateReferenceImageRequest", + "CropHint", + "CropHintsAnnotation", + "CropHintsParams", + "DeleteProductRequest", + "DeleteProductSetRequest", + "DeleteReferenceImageRequest", + "DominantColorsAnnotation", + "EntityAnnotation", + "FaceAnnotation", + "FaceRecognitionParams", + "FaceRecognitionResult", + "Feature", + "GcsDestination", + "GcsSource", + "GetProductRequest", + "GetProductSetRequest", + "GetReferenceImageRequest", + "Image", + "ImageAnnotationContext", + "ImageContext", + "ImageProperties", + "ImageSource", + "ImportProductSetsGcsSource", + "ImportProductSetsInputConfig", + "ImportProductSetsRequest", + "ImportProductSetsResponse", + "InputConfig", + "LatLongRect", + "Likelihood", + "ListProductSetsRequest", + "ListProductSetsResponse", + "ListProductsInProductSetRequest", + "ListProductsInProductSetResponse", + "ListProductsRequest", + "ListProductsResponse", + "ListReferenceImagesRequest", + "ListReferenceImagesResponse", + "LocalizedObjectAnnotation", + "LocationInfo", + "NormalizedVertex", + "OperationMetadata", + "OutputConfig", + "Page", + "Paragraph", + "Position", + "Product", "ProductSearchClient", + "ProductSearchParams", + "ProductSearchResults", + "ProductSet", + "ProductSetPurgeConfig", + "Property", + "PurgeProductsRequest", + "ReferenceImage", + "RemoveProductFromProductSetRequest", + "SafeSearchAnnotation", + "Symbol", + "TextAnnotation", + "UpdateProductRequest", + "UpdateProductSetRequest", + "Vertex", + "WebDetection", + "WebDetectionParams", + "Word", "ImageAnnotatorClient", ) diff --git a/google/cloud/vision_v1p4beta1/gapic/__init__.py b/google/cloud/vision_v1p4beta1/gapic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/vision_v1p4beta1/gapic/enums.py b/google/cloud/vision_v1p4beta1/gapic/enums.py deleted file mode 100644 index 911d2e7c..00000000 --- a/google/cloud/vision_v1p4beta1/gapic/enums.py +++ /dev/null @@ -1,255 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Wrappers for protocol buffer enum types.""" - -import enum - - -class Likelihood(enum.IntEnum): - """ - A bucketized representation of likelihood, which is intended to give clients - highly stable results across model upgrades. - - Attributes: - UNKNOWN (int): Unknown likelihood. - VERY_UNLIKELY (int): It is very unlikely. - UNLIKELY (int): It is unlikely. - POSSIBLE (int): It is possible. - LIKELY (int): It is likely. - VERY_LIKELY (int): It is very likely. - """ - - UNKNOWN = 0 - VERY_UNLIKELY = 1 - UNLIKELY = 2 - POSSIBLE = 3 - LIKELY = 4 - VERY_LIKELY = 5 - - -class BatchOperationMetadata(object): - class State(enum.IntEnum): - """ - Enumerates the possible states that the batch request can be in. - - Attributes: - STATE_UNSPECIFIED (int): Invalid. - PROCESSING (int): Request is actively being processed. - SUCCESSFUL (int): The request is done and at least one item has been successfully - processed. - FAILED (int): The request is done and no item has been successfully processed. - CANCELLED (int): The request is done after the longrunning.Operations.CancelOperation has - been called by the user. Any records that were processed before the - cancel command are output as specified in the request. - """ - - STATE_UNSPECIFIED = 0 - PROCESSING = 1 - SUCCESSFUL = 2 - FAILED = 3 - CANCELLED = 4 - - -class Block(object): - class BlockType(enum.IntEnum): - """ - Type of a block (text, image etc) as identified by OCR. - - Attributes: - UNKNOWN (int): Unknown block type. - TEXT (int): Regular text block. - TABLE (int): Table block. - PICTURE (int): Image block. - RULER (int): Horizontal/vertical line box. - BARCODE (int): Barcode block. - """ - - UNKNOWN = 0 - TEXT = 1 - TABLE = 2 - PICTURE = 3 - RULER = 4 - BARCODE = 5 - - -class FaceAnnotation(object): - class Landmark(object): - class Type(enum.IntEnum): - """ - Face landmark (feature) type. Left and right are defined from the - vantage of the viewer of the image without considering mirror - projections typical of photos. So, ``LEFT_EYE``, typically, is the - person's right eye. - - Attributes: - UNKNOWN_LANDMARK (int): Unknown face landmark detected. Should not be filled. - LEFT_EYE (int): Left eye. - RIGHT_EYE (int): Right eye. - LEFT_OF_LEFT_EYEBROW (int): Left of left eyebrow. - RIGHT_OF_LEFT_EYEBROW (int): Right of left eyebrow. - LEFT_OF_RIGHT_EYEBROW (int): Left of right eyebrow. - RIGHT_OF_RIGHT_EYEBROW (int): Right of right eyebrow. - MIDPOINT_BETWEEN_EYES (int): Midpoint between eyes. - NOSE_TIP (int): Nose tip. - UPPER_LIP (int): Upper lip. - LOWER_LIP (int): Lower lip. - MOUTH_LEFT (int): Mouth left. - MOUTH_RIGHT (int): Mouth right. - MOUTH_CENTER (int): Mouth center. - NOSE_BOTTOM_RIGHT (int): Nose, bottom right. - NOSE_BOTTOM_LEFT (int): Nose, bottom left. - NOSE_BOTTOM_CENTER (int): Nose, bottom center. - LEFT_EYE_TOP_BOUNDARY (int): Left eye, top boundary. - LEFT_EYE_RIGHT_CORNER (int): Left eye, right corner. - LEFT_EYE_BOTTOM_BOUNDARY (int): Left eye, bottom boundary. - LEFT_EYE_LEFT_CORNER (int): Left eye, left corner. - RIGHT_EYE_TOP_BOUNDARY (int): Right eye, top boundary. - RIGHT_EYE_RIGHT_CORNER (int): Right eye, right corner. - RIGHT_EYE_BOTTOM_BOUNDARY (int): Right eye, bottom boundary. - RIGHT_EYE_LEFT_CORNER (int): Right eye, left corner. - LEFT_EYEBROW_UPPER_MIDPOINT (int): Left eyebrow, upper midpoint. - RIGHT_EYEBROW_UPPER_MIDPOINT (int): Right eyebrow, upper midpoint. - LEFT_EAR_TRAGION (int): Left ear tragion. - RIGHT_EAR_TRAGION (int): Right ear tragion. - LEFT_EYE_PUPIL (int): Left eye pupil. - RIGHT_EYE_PUPIL (int): Right eye pupil. - FOREHEAD_GLABELLA (int): Forehead glabella. - CHIN_GNATHION (int): Chin gnathion. - CHIN_LEFT_GONION (int): Chin left gonion. - CHIN_RIGHT_GONION (int): Chin right gonion. - """ - - UNKNOWN_LANDMARK = 0 - LEFT_EYE = 1 - RIGHT_EYE = 2 - LEFT_OF_LEFT_EYEBROW = 3 - RIGHT_OF_LEFT_EYEBROW = 4 - LEFT_OF_RIGHT_EYEBROW = 5 - RIGHT_OF_RIGHT_EYEBROW = 6 - MIDPOINT_BETWEEN_EYES = 7 - NOSE_TIP = 8 - UPPER_LIP = 9 - LOWER_LIP = 10 - MOUTH_LEFT = 11 - MOUTH_RIGHT = 12 - MOUTH_CENTER = 13 - NOSE_BOTTOM_RIGHT = 14 - NOSE_BOTTOM_LEFT = 15 - NOSE_BOTTOM_CENTER = 16 - LEFT_EYE_TOP_BOUNDARY = 17 - LEFT_EYE_RIGHT_CORNER = 18 - LEFT_EYE_BOTTOM_BOUNDARY = 19 - LEFT_EYE_LEFT_CORNER = 20 - RIGHT_EYE_TOP_BOUNDARY = 21 - RIGHT_EYE_RIGHT_CORNER = 22 - RIGHT_EYE_BOTTOM_BOUNDARY = 23 - RIGHT_EYE_LEFT_CORNER = 24 - LEFT_EYEBROW_UPPER_MIDPOINT = 25 - RIGHT_EYEBROW_UPPER_MIDPOINT = 26 - LEFT_EAR_TRAGION = 27 - RIGHT_EAR_TRAGION = 28 - LEFT_EYE_PUPIL = 29 - RIGHT_EYE_PUPIL = 30 - FOREHEAD_GLABELLA = 31 - CHIN_GNATHION = 32 - CHIN_LEFT_GONION = 33 - CHIN_RIGHT_GONION = 34 - - -class Feature(object): - class Type(enum.IntEnum): - """ - Type of Google Cloud Vision API feature to be extracted. - - Attributes: - TYPE_UNSPECIFIED (int): Unspecified feature type. - FACE_DETECTION (int): Run face detection. - LANDMARK_DETECTION (int): Run landmark detection. - LOGO_DETECTION (int): Run logo detection. - LABEL_DETECTION (int): Run label detection. - TEXT_DETECTION (int): Run text detection / optical character recognition (OCR). Text - detection is optimized for areas of text within a larger image; if the - image is a document, use ``DOCUMENT_TEXT_DETECTION`` instead. - DOCUMENT_TEXT_DETECTION (int): Run dense text document OCR. Takes precedence when both - ``DOCUMENT_TEXT_DETECTION`` and ``TEXT_DETECTION`` are present. - SAFE_SEARCH_DETECTION (int): Run Safe Search to detect potentially unsafe - or undesirable content. - IMAGE_PROPERTIES (int): Compute a set of image properties, such as the - image's dominant colors. - CROP_HINTS (int): Run crop hints. - WEB_DETECTION (int): Run web detection. - PRODUCT_SEARCH (int): Run Product Search. - OBJECT_LOCALIZATION (int): Run localizer for object detection. - """ - - TYPE_UNSPECIFIED = 0 - FACE_DETECTION = 1 - LANDMARK_DETECTION = 2 - LOGO_DETECTION = 3 - LABEL_DETECTION = 4 - TEXT_DETECTION = 5 - DOCUMENT_TEXT_DETECTION = 11 - SAFE_SEARCH_DETECTION = 6 - IMAGE_PROPERTIES = 7 - CROP_HINTS = 9 - WEB_DETECTION = 10 - PRODUCT_SEARCH = 12 - OBJECT_LOCALIZATION = 19 - - -class OperationMetadata(object): - class State(enum.IntEnum): - """ - Batch operation states. - - Attributes: - STATE_UNSPECIFIED (int): Invalid. - CREATED (int): Request is received. - RUNNING (int): Request is actively being processed. - DONE (int): The batch processing is done. - CANCELLED (int): The batch processing was cancelled. - """ - - STATE_UNSPECIFIED = 0 - CREATED = 1 - RUNNING = 2 - DONE = 3 - CANCELLED = 4 - - -class TextAnnotation(object): - class DetectedBreak(object): - class BreakType(enum.IntEnum): - """ - Enum to denote the type of break found. New line, space etc. - - Attributes: - UNKNOWN (int): Unknown break label type. - SPACE (int): Regular space. - SURE_SPACE (int): Sure space (very wide). - EOL_SURE_SPACE (int): Line-wrapping break. - HYPHEN (int): End-line hyphen that is not present in text; does not co-occur with - ``SPACE``, ``LEADER_SPACE``, or ``LINE_BREAK``. - LINE_BREAK (int): Line break that ends a paragraph. - """ - - UNKNOWN = 0 - SPACE = 1 - SURE_SPACE = 2 - EOL_SURE_SPACE = 3 - HYPHEN = 4 - LINE_BREAK = 5 diff --git a/google/cloud/vision_v1p4beta1/gapic/image_annotator_client.py b/google/cloud/vision_v1p4beta1/gapic/image_annotator_client.py deleted file mode 100644 index 2ee10005..00000000 --- a/google/cloud/vision_v1p4beta1/gapic/image_annotator_client.py +++ /dev/null @@ -1,498 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.vision.v1p4beta1 ImageAnnotator API.""" - -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.grpc_helpers -import google.api_core.operation -from google.api_core import operations_v1 -import grpc - -from google.cloud.vision_v1p4beta1.gapic import enums -from google.cloud.vision_v1p4beta1.gapic import image_annotator_client_config -from google.cloud.vision_v1p4beta1.gapic.transports import ( - image_annotator_grpc_transport, -) -from google.cloud.vision_v1p4beta1.proto import image_annotator_pb2 -from google.cloud.vision_v1p4beta1.proto import image_annotator_pb2_grpc -from google.cloud.vision_v1p4beta1.proto import product_search_service_pb2 -from google.cloud.vision_v1p4beta1.proto import product_search_service_pb2_grpc -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-vision",).version - - -class ImageAnnotatorClient(object): - """ - Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - SERVICE_ADDRESS = "vision.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.vision.v1p4beta1.ImageAnnotator" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ImageAnnotatorClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.ImageAnnotatorGrpcTransport, - Callable[[~.Credentials, type], ~.ImageAnnotatorGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = image_annotator_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=image_annotator_grpc_transport.ImageAnnotatorGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = image_annotator_grpc_transport.ImageAnnotatorGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def async_batch_annotate_images( - self, - requests, - output_config, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Run asynchronous image detection and annotation for a list of - images. - - Progress and results can be retrieved through the - ``google.longrunning.Operations`` interface. ``Operation.metadata`` - contains ``OperationMetadata`` (metadata). ``Operation.response`` - contains ``AsyncBatchAnnotateImagesResponse`` (results). - - This service will write image annotation outputs to json files in - customer GCS bucket, each json file containing - BatchAnnotateImagesResponse proto. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ImageAnnotatorClient() - >>> - >>> # TODO: Initialize `requests`: - >>> requests = [] - >>> - >>> # TODO: Initialize `output_config`: - >>> output_config = {} - >>> - >>> response = client.async_batch_annotate_images(requests, output_config) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - requests (list[Union[dict, ~google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]]): Required. Individual image annotation requests for this batch. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p4beta1.types.AnnotateImageRequest` - output_config (Union[dict, ~google.cloud.vision_v1p4beta1.types.OutputConfig]): Required. The desired output location and metadata (e.g. format). - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p4beta1.types.OutputConfig` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p4beta1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "async_batch_annotate_images" not in self._inner_api_calls: - self._inner_api_calls[ - "async_batch_annotate_images" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.async_batch_annotate_images, - default_retry=self._method_configs["AsyncBatchAnnotateImages"].retry, - default_timeout=self._method_configs[ - "AsyncBatchAnnotateImages" - ].timeout, - client_info=self._client_info, - ) - - request = image_annotator_pb2.AsyncBatchAnnotateImagesRequest( - requests=requests, output_config=output_config, - ) - operation = self._inner_api_calls["async_batch_annotate_images"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - image_annotator_pb2.AsyncBatchAnnotateImagesResponse, - metadata_type=image_annotator_pb2.OperationMetadata, - ) - - def async_batch_annotate_files( - self, - requests, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Run asynchronous image detection and annotation for a list of - generic files, such as PDF files, which may contain multiple pages and - multiple images per page. Progress and results can be retrieved through - the ``google.longrunning.Operations`` interface. ``Operation.metadata`` - contains ``OperationMetadata`` (metadata). ``Operation.response`` - contains ``AsyncBatchAnnotateFilesResponse`` (results). - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ImageAnnotatorClient() - >>> - >>> # TODO: Initialize `requests`: - >>> requests = [] - >>> - >>> response = client.async_batch_annotate_files(requests) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - requests (list[Union[dict, ~google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileRequest]]): Required. Individual async file annotation requests for this batch. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileRequest` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p4beta1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "async_batch_annotate_files" not in self._inner_api_calls: - self._inner_api_calls[ - "async_batch_annotate_files" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.async_batch_annotate_files, - default_retry=self._method_configs["AsyncBatchAnnotateFiles"].retry, - default_timeout=self._method_configs["AsyncBatchAnnotateFiles"].timeout, - client_info=self._client_info, - ) - - request = image_annotator_pb2.AsyncBatchAnnotateFilesRequest(requests=requests,) - operation = self._inner_api_calls["async_batch_annotate_files"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - image_annotator_pb2.AsyncBatchAnnotateFilesResponse, - metadata_type=image_annotator_pb2.OperationMetadata, - ) - - def batch_annotate_images( - self, - requests, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Run image detection and annotation for a batch of images. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ImageAnnotatorClient() - >>> - >>> # TODO: Initialize `requests`: - >>> requests = [] - >>> - >>> response = client.batch_annotate_images(requests) - - Args: - requests (list[Union[dict, ~google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]]): Required. Individual image annotation requests for this batch. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p4beta1.types.AnnotateImageRequest` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p4beta1.types.BatchAnnotateImagesResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "batch_annotate_images" not in self._inner_api_calls: - self._inner_api_calls[ - "batch_annotate_images" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.batch_annotate_images, - default_retry=self._method_configs["BatchAnnotateImages"].retry, - default_timeout=self._method_configs["BatchAnnotateImages"].timeout, - client_info=self._client_info, - ) - - request = image_annotator_pb2.BatchAnnotateImagesRequest(requests=requests,) - return self._inner_api_calls["batch_annotate_images"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def batch_annotate_files( - self, - requests, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Service that performs image detection and annotation for a batch of files. - Now only "application/pdf", "image/tiff" and "image/gif" are supported. - - This service will extract at most 5 (customers can specify which 5 in - AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each - file provided and perform detection and annotation for each image - extracted. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ImageAnnotatorClient() - >>> - >>> # TODO: Initialize `requests`: - >>> requests = [] - >>> - >>> response = client.batch_annotate_files(requests) - - Args: - requests (list[Union[dict, ~google.cloud.vision_v1p4beta1.types.AnnotateFileRequest]]): Required. The list of file annotation requests. Right now we support only - one AnnotateFileRequest in BatchAnnotateFilesRequest. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p4beta1.types.AnnotateFileRequest` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p4beta1.types.BatchAnnotateFilesResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "batch_annotate_files" not in self._inner_api_calls: - self._inner_api_calls[ - "batch_annotate_files" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.batch_annotate_files, - default_retry=self._method_configs["BatchAnnotateFiles"].retry, - default_timeout=self._method_configs["BatchAnnotateFiles"].timeout, - client_info=self._client_info, - ) - - request = image_annotator_pb2.BatchAnnotateFilesRequest(requests=requests,) - return self._inner_api_calls["batch_annotate_files"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) diff --git a/google/cloud/vision_v1p4beta1/gapic/image_annotator_client_config.py b/google/cloud/vision_v1p4beta1/gapic/image_annotator_client_config.py deleted file mode 100644 index 279577e8..00000000 --- a/google/cloud/vision_v1p4beta1/gapic/image_annotator_client_config.py +++ /dev/null @@ -1,49 +0,0 @@ -config = { - "interfaces": { - "google.cloud.vision.v1p4beta1.ImageAnnotator": { - "retry_codes": {"retry_policy_1_codes": [], "no_retry_codes": []}, - "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 600000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 600000, - "total_timeout_millis": 600000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - }, - "methods": { - "AsyncBatchAnnotateImages": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "AsyncBatchAnnotateFiles": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "BatchAnnotateImages": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "BatchAnnotateFiles": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - }, - } - } -} diff --git a/google/cloud/vision_v1p4beta1/gapic/product_search_client.py b/google/cloud/vision_v1p4beta1/gapic/product_search_client.py deleted file mode 100644 index 61b97ba3..00000000 --- a/google/cloud/vision_v1p4beta1/gapic/product_search_client.py +++ /dev/null @@ -1,2026 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Accesses the google.cloud.vision.v1p4beta1 ProductSearch API.""" - -import functools -import pkg_resources -import warnings - -from google.oauth2 import service_account -import google.api_core.client_options -import google.api_core.gapic_v1.client_info -import google.api_core.gapic_v1.config -import google.api_core.gapic_v1.method -import google.api_core.gapic_v1.routing_header -import google.api_core.grpc_helpers -import google.api_core.operation -from google.api_core import operations_v1 -import google.api_core.page_iterator -import google.api_core.path_template -import google.api_core.protobuf_helpers -import grpc - -from google.cloud.vision_v1p4beta1.gapic import enums -from google.cloud.vision_v1p4beta1.gapic import product_search_client_config -from google.cloud.vision_v1p4beta1.gapic.transports import product_search_grpc_transport -from google.cloud.vision_v1p4beta1.proto import product_search_service_pb2 -from google.cloud.vision_v1p4beta1.proto import product_search_service_pb2_grpc -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 - - -_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-vision",).version - - -class ProductSearchClient(object): - """ - Manages Products and ProductSets of reference images for use in - product search. It uses the following resource model: - - - The API has a collection of ``ProductSet`` resources, named - ``projects/*/locations/*/productSets/*``, which acts as a way to put - different products into groups to limit identification. - - In parallel, - - - The API has a collection of ``Product`` resources, named - ``projects/*/locations/*/products/*`` - - - Each ``Product`` has a collection of ``ReferenceImage`` resources, - named ``projects/*/locations/*/products/*/referenceImages/*`` - """ - - SERVICE_ADDRESS = "vision.googleapis.com:443" - """The default address of the service.""" - - # The name of the interface for this client. This is the key used to - # find the method configuration in the client_config dictionary. - _INTERFACE_NAME = "google.cloud.vision.v1p4beta1.ProductSearch" - - @classmethod - def from_service_account_file(cls, filename, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - ProductSearchClient: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @classmethod - def location_path(cls, project, location): - """Return a fully-qualified location string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}", - project=project, - location=location, - ) - - @classmethod - def product_path(cls, project, location, product): - """Return a fully-qualified product string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/products/{product}", - project=project, - location=location, - product=product, - ) - - @classmethod - def product_set_path(cls, project, location, product_set): - """Return a fully-qualified product_set string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/productSets/{product_set}", - project=project, - location=location, - product_set=product_set, - ) - - @classmethod - def reference_image_path(cls, project, location, product, reference_image): - """Return a fully-qualified reference_image string.""" - return google.api_core.path_template.expand( - "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}", - project=project, - location=location, - product=product, - reference_image=reference_image, - ) - - def __init__( - self, - transport=None, - channel=None, - credentials=None, - client_config=None, - client_info=None, - client_options=None, - ): - """Constructor. - - Args: - transport (Union[~.ProductSearchGrpcTransport, - Callable[[~.Credentials, type], ~.ProductSearchGrpcTransport]): A transport - instance, responsible for actually making the API calls. - The default transport uses the gRPC protocol. - This argument may also be a callable which returns a - transport instance. Callables will be sent the credentials - as the first argument and the default transport class as - the second argument. - channel (grpc.Channel): DEPRECATED. A ``Channel`` instance - through which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is mutually exclusive with providing a - transport instance to ``transport``; doing so will raise - an exception. - client_config (dict): DEPRECATED. A dictionary of call options for - each method. If not specified, the default configuration is used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - client_options (Union[dict, google.api_core.client_options.ClientOptions]): - Client options used to set user options on the client. API Endpoint - should be set through client_options. - """ - # Raise deprecation warnings for things we want to go away. - if client_config is not None: - warnings.warn( - "The `client_config` argument is deprecated.", - PendingDeprecationWarning, - stacklevel=2, - ) - else: - client_config = product_search_client_config.config - - if channel: - warnings.warn( - "The `channel` argument is deprecated; use " "`transport` instead.", - PendingDeprecationWarning, - stacklevel=2, - ) - - api_endpoint = self.SERVICE_ADDRESS - if client_options: - if type(client_options) == dict: - client_options = google.api_core.client_options.from_dict( - client_options - ) - if client_options.api_endpoint: - api_endpoint = client_options.api_endpoint - - # Instantiate the transport. - # The transport is responsible for handling serialization and - # deserialization and actually sending data to the service. - if transport: - if callable(transport): - self.transport = transport( - credentials=credentials, - default_class=product_search_grpc_transport.ProductSearchGrpcTransport, - address=api_endpoint, - ) - else: - if credentials: - raise ValueError( - "Received both a transport instance and " - "credentials; these are mutually exclusive." - ) - self.transport = transport - else: - self.transport = product_search_grpc_transport.ProductSearchGrpcTransport( - address=api_endpoint, channel=channel, credentials=credentials, - ) - - if client_info is None: - client_info = google.api_core.gapic_v1.client_info.ClientInfo( - gapic_version=_GAPIC_LIBRARY_VERSION, - ) - else: - client_info.gapic_version = _GAPIC_LIBRARY_VERSION - self._client_info = client_info - - # Parse out the default settings for retry and timeout for each RPC - # from the client configuration. - # (Ordinarily, these are the defaults specified in the `*_config.py` - # file next to this one.) - self._method_configs = google.api_core.gapic_v1.config.parse_method_configs( - client_config["interfaces"][self._INTERFACE_NAME], - ) - - # Save a dictionary of cached API call functions. - # These are the actual callables which invoke the proper - # transport methods, wrapped with `wrap_method` to add retry, - # timeout, and the like. - self._inner_api_calls = {} - - # Service calls - def import_product_sets( - self, - parent, - input_config, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Asynchronous API that imports a list of reference images to - specified product sets based on a list of image information. - - The ``google.longrunning.Operation`` API can be used to keep track of - the progress and results of the request. ``Operation.metadata`` contains - ``BatchOperationMetadata``. (progress) ``Operation.response`` contains - ``ImportProductSetsResponse``. (results) - - The input source of this method is a csv file on Google Cloud Storage. - For the format of the csv file please see - ``ImportProductSetsGcsSource.csv_file_uri``. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `input_config`: - >>> input_config = {} - >>> - >>> response = client.import_product_sets(parent, input_config) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - parent (str): Required. The project in which the ProductSets should be imported. - - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - input_config (Union[dict, ~google.cloud.vision_v1p4beta1.types.ImportProductSetsInputConfig]): Required. The input content for the list of requests. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p4beta1.types.ImportProductSetsInputConfig` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p4beta1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "import_product_sets" not in self._inner_api_calls: - self._inner_api_calls[ - "import_product_sets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.import_product_sets, - default_retry=self._method_configs["ImportProductSets"].retry, - default_timeout=self._method_configs["ImportProductSets"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.ImportProductSetsRequest( - parent=parent, input_config=input_config, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["import_product_sets"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - product_search_service_pb2.ImportProductSetsResponse, - metadata_type=product_search_service_pb2.BatchOperationMetadata, - ) - - def create_product_set( - self, - parent, - product_set, - product_set_id=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates and returns a new ProductSet resource. - - Possible errors: - - - Returns INVALID_ARGUMENT if display_name is missing, or is longer - than 4096 characters. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `product_set`: - >>> product_set = {} - >>> - >>> response = client.create_product_set(parent, product_set) - - Args: - parent (str): Required. The project in which the ProductSet should be created. - - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - product_set (Union[dict, ~google.cloud.vision_v1p4beta1.types.ProductSet]): Required. The ProductSet to create. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p4beta1.types.ProductSet` - product_set_id (str): A user-supplied resource id for this ProductSet. If set, the server - will attempt to use this value as the resource id. If it is already in - use, an error is returned with code ALREADY_EXISTS. Must be at most 128 - characters long. It cannot contain the character ``/``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p4beta1.types.ProductSet` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "create_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_product_set, - default_retry=self._method_configs["CreateProductSet"].retry, - default_timeout=self._method_configs["CreateProductSet"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.CreateProductSetRequest( - parent=parent, product_set=product_set, product_set_id=product_set_id, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_product_sets( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists ProductSets in an unspecified order. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100, or less - than 1. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_product_sets(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_product_sets(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The project from which ProductSets should be listed. - - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.vision_v1p4beta1.types.ProductSet` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_product_sets" not in self._inner_api_calls: - self._inner_api_calls[ - "list_product_sets" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_product_sets, - default_retry=self._method_configs["ListProductSets"].retry, - default_timeout=self._method_configs["ListProductSets"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.ListProductSetsRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_product_sets"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="product_sets", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_product_set( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets information associated with a ProductSet. - - Possible errors: - - - Returns NOT_FOUND if the ProductSet does not exist. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> name = client.product_set_path('[PROJECT]', '[LOCATION]', '[PRODUCT_SET]') - >>> - >>> response = client.get_product_set(name) - - Args: - name (str): Required. Resource name of the ProductSet to get. - - Format is: - ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p4beta1.types.ProductSet` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "get_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_product_set, - default_retry=self._method_configs["GetProductSet"].retry, - default_timeout=self._method_configs["GetProductSet"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.GetProductSetRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_product_set( - self, - product_set, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Makes changes to a ProductSet resource. Only display_name can be - updated currently. - - Possible errors: - - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in update_mask - but missing from the request or longer than 4096 characters. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> # TODO: Initialize `product_set`: - >>> product_set = {} - >>> - >>> response = client.update_product_set(product_set) - - Args: - product_set (Union[dict, ~google.cloud.vision_v1p4beta1.types.ProductSet]): Required. The ProductSet resource which replaces the one on the server. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p4beta1.types.ProductSet` - update_mask (Union[dict, ~google.cloud.vision_v1p4beta1.types.FieldMask]): The ``FieldMask`` that specifies which fields to update. If - update_mask isn't specified, all mutable fields are to be updated. Valid - mask path is ``display_name``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p4beta1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p4beta1.types.ProductSet` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "update_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_product_set, - default_retry=self._method_configs["UpdateProductSet"].retry, - default_timeout=self._method_configs["UpdateProductSet"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.UpdateProductSetRequest( - product_set=product_set, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("product_set.name", product_set.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_product_set( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Permanently deletes a ProductSet. Products and ReferenceImages in the - ProductSet are not deleted. - - The actual image files are not deleted from Google Cloud Storage. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> name = client.product_set_path('[PROJECT]', '[LOCATION]', '[PRODUCT_SET]') - >>> - >>> client.delete_product_set(name) - - Args: - name (str): Required. Resource name of the ProductSet to delete. - - Format is: - ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_product_set, - default_retry=self._method_configs["DeleteProductSet"].retry, - default_timeout=self._method_configs["DeleteProductSet"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.DeleteProductSetRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_product( - self, - parent, - product, - product_id=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates and returns a new product resource. - - Possible errors: - - - Returns INVALID_ARGUMENT if display_name is missing or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or invalid. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # TODO: Initialize `product`: - >>> product = {} - >>> - >>> response = client.create_product(parent, product) - - Args: - parent (str): Required. The project in which the Product should be created. - - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - product (Union[dict, ~google.cloud.vision_v1p4beta1.types.Product]): Required. The product to create. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p4beta1.types.Product` - product_id (str): A user-supplied resource id for this Product. If set, the server - will attempt to use this value as the resource id. If it is already in - use, an error is returned with code ALREADY_EXISTS. Must be at most 128 - characters long. It cannot contain the character ``/``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p4beta1.types.Product` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_product" not in self._inner_api_calls: - self._inner_api_calls[ - "create_product" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_product, - default_retry=self._method_configs["CreateProduct"].retry, - default_timeout=self._method_configs["CreateProduct"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.CreateProductRequest( - parent=parent, product=product, product_id=product_id, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_product"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_products( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists products in an unspecified order. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100 or less - than 1. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> # Iterate over all results - >>> for element in client.list_products(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_products(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. The project OR ProductSet from which Products should be - listed. - - Format: ``projects/PROJECT_ID/locations/LOC_ID`` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.vision_v1p4beta1.types.Product` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_products" not in self._inner_api_calls: - self._inner_api_calls[ - "list_products" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_products, - default_retry=self._method_configs["ListProducts"].retry, - default_timeout=self._method_configs["ListProducts"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.ListProductsRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_products"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="products", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_product( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets information associated with a Product. - - Possible errors: - - - Returns NOT_FOUND if the Product does not exist. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> name = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> response = client.get_product(name) - - Args: - name (str): Required. Resource name of the Product to get. - - Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p4beta1.types.Product` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_product" not in self._inner_api_calls: - self._inner_api_calls[ - "get_product" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_product, - default_retry=self._method_configs["GetProduct"].retry, - default_timeout=self._method_configs["GetProduct"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.GetProductRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_product"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def update_product( - self, - product, - update_mask=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Makes changes to a Product resource. Only the ``display_name``, - ``description``, and ``labels`` fields can be updated right now. - - If labels are updated, the change will not be reflected in queries until - the next index time. - - Possible errors: - - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in update_mask - but is missing from the request or longer than 4096 characters. - - Returns INVALID_ARGUMENT if description is present in update_mask but - is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> # TODO: Initialize `product`: - >>> product = {} - >>> - >>> response = client.update_product(product) - - Args: - product (Union[dict, ~google.cloud.vision_v1p4beta1.types.Product]): Required. The Product resource which replaces the one on the server. - product.name is immutable. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p4beta1.types.Product` - update_mask (Union[dict, ~google.cloud.vision_v1p4beta1.types.FieldMask]): The ``FieldMask`` that specifies which fields to update. If - update_mask isn't specified, all mutable fields are to be updated. Valid - mask paths include ``product_labels``, ``display_name``, and - ``description``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p4beta1.types.FieldMask` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p4beta1.types.Product` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "update_product" not in self._inner_api_calls: - self._inner_api_calls[ - "update_product" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.update_product, - default_retry=self._method_configs["UpdateProduct"].retry, - default_timeout=self._method_configs["UpdateProduct"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.UpdateProductRequest( - product=product, update_mask=update_mask, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("product.name", product.name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["update_product"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_product( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Permanently deletes a product and its reference images. - - Metadata of the product and all its images will be deleted right away, but - search queries against ProductSets containing the product may still work - until all related caches are refreshed. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> name = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> client.delete_product(name) - - Args: - name (str): Required. Resource name of product to delete. - - Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_product" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_product" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_product, - default_retry=self._method_configs["DeleteProduct"].retry, - default_timeout=self._method_configs["DeleteProduct"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.DeleteProductRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_product"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_reference_image( - self, - parent, - reference_image, - reference_image_id=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Creates and returns a new ReferenceImage resource. - - The ``bounding_poly`` field is optional. If ``bounding_poly`` is not - specified, the system will try to detect regions of interest in the - image that are compatible with the product_category on the parent - product. If it is specified, detection is ALWAYS skipped. The system - converts polygons into non-rotated rectangles. - - Note that the pipeline will resize the image if the image resolution is - too large to process (above 50MP). - - Possible errors: - - - Returns INVALID_ARGUMENT if the image_uri is missing or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category is - detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than 10 - polygons. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> parent = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> # TODO: Initialize `reference_image`: - >>> reference_image = {} - >>> - >>> response = client.create_reference_image(parent, reference_image) - - Args: - parent (str): Required. Resource name of the product in which to create the - reference image. - - Format is ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. - reference_image (Union[dict, ~google.cloud.vision_v1p4beta1.types.ReferenceImage]): Required. The reference image to create. - If an image ID is specified, it is ignored. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p4beta1.types.ReferenceImage` - reference_image_id (str): A user-supplied resource id for the ReferenceImage to be added. If - set, the server will attempt to use this value as the resource id. If it - is already in use, an error is returned with code ALREADY_EXISTS. Must - be at most 128 characters long. It cannot contain the character ``/``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p4beta1.types.ReferenceImage` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "create_reference_image" not in self._inner_api_calls: - self._inner_api_calls[ - "create_reference_image" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_reference_image, - default_retry=self._method_configs["CreateReferenceImage"].retry, - default_timeout=self._method_configs["CreateReferenceImage"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.CreateReferenceImageRequest( - parent=parent, - reference_image=reference_image, - reference_image_id=reference_image_id, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["create_reference_image"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def delete_reference_image( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Permanently deletes a reference image. - - The image metadata will be deleted right away, but search queries - against ProductSets containing the image may still work until all related - caches are refreshed. - - The actual image files are not deleted from Google Cloud Storage. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> name = client.reference_image_path('[PROJECT]', '[LOCATION]', '[PRODUCT]', '[REFERENCE_IMAGE]') - >>> - >>> client.delete_reference_image(name) - - Args: - name (str): Required. The resource name of the reference image to delete. - - Format is: - - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "delete_reference_image" not in self._inner_api_calls: - self._inner_api_calls[ - "delete_reference_image" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_reference_image, - default_retry=self._method_configs["DeleteReferenceImage"].retry, - default_timeout=self._method_configs["DeleteReferenceImage"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.DeleteReferenceImageRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["delete_reference_image"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_reference_images( - self, - parent, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists reference images. - - Possible errors: - - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, or - less than 1. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> parent = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> # Iterate over all results - >>> for element in client.list_reference_images(parent): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_reference_images(parent).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. Resource name of the product containing the reference - images. - - Format is ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.vision_v1p4beta1.types.ReferenceImage` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_reference_images" not in self._inner_api_calls: - self._inner_api_calls[ - "list_reference_images" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_reference_images, - default_retry=self._method_configs["ListReferenceImages"].retry, - default_timeout=self._method_configs["ListReferenceImages"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.ListReferenceImagesRequest( - parent=parent, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_reference_images"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="reference_images", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def get_reference_image( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets information associated with a ReferenceImage. - - Possible errors: - - - Returns NOT_FOUND if the specified image does not exist. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> name = client.reference_image_path('[PROJECT]', '[LOCATION]', '[PRODUCT]', '[REFERENCE_IMAGE]') - >>> - >>> response = client.get_reference_image(name) - - Args: - name (str): Required. The resource name of the ReferenceImage to get. - - Format is: - - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p4beta1.types.ReferenceImage` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_reference_image" not in self._inner_api_calls: - self._inner_api_calls[ - "get_reference_image" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_reference_image, - default_retry=self._method_configs["GetReferenceImage"].retry, - default_timeout=self._method_configs["GetReferenceImage"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.GetReferenceImageRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["get_reference_image"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def add_product_to_product_set( - self, - name, - product, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Adds a Product to the specified ProductSet. If the Product is - already present, no change is made. - - One Product can be added to at most 100 ProductSets. - - Possible errors: - - - Returns NOT_FOUND if the Product or the ProductSet doesn't exist. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> name = client.product_set_path('[PROJECT]', '[LOCATION]', '[PRODUCT_SET]') - >>> product = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> client.add_product_to_product_set(name, product) - - Args: - name (str): Required. The resource name for the ProductSet to modify. - - Format is: - ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` - product (str): Required. The resource name for the Product to be added to this - ProductSet. - - Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "add_product_to_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "add_product_to_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.add_product_to_product_set, - default_retry=self._method_configs["AddProductToProductSet"].retry, - default_timeout=self._method_configs["AddProductToProductSet"].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.AddProductToProductSetRequest( - name=name, product=product, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["add_product_to_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def remove_product_from_product_set( - self, - name, - product, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Removes a Product from the specified ProductSet. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> name = client.product_set_path('[PROJECT]', '[LOCATION]', '[PRODUCT_SET]') - >>> product = client.product_path('[PROJECT]', '[LOCATION]', '[PRODUCT]') - >>> - >>> client.remove_product_from_product_set(name, product) - - Args: - name (str): Required. The resource name for the ProductSet to modify. - - Format is: - ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` - product (str): Required. The resource name for the Product to be removed from this - ProductSet. - - Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "remove_product_from_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "remove_product_from_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.remove_product_from_product_set, - default_retry=self._method_configs["RemoveProductFromProductSet"].retry, - default_timeout=self._method_configs[ - "RemoveProductFromProductSet" - ].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.RemoveProductFromProductSetRequest( - name=name, product=product, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - self._inner_api_calls["remove_product_from_product_set"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def list_products_in_product_set( - self, - name, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Lists the Products in a ProductSet, in an unspecified order. If the - ProductSet does not exist, the products field of the response will be - empty. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100 or less - than 1. - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> name = client.product_set_path('[PROJECT]', '[LOCATION]', '[PRODUCT_SET]') - >>> - >>> # Iterate over all results - >>> for element in client.list_products_in_product_set(name): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.list_products_in_product_set(name).pages: - ... for element in page: - ... # process element - ... pass - - Args: - name (str): Required. The ProductSet resource for which to retrieve Products. - - Format is: - ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.vision_v1p4beta1.types.Product` instances. - You can also iterate over the pages of the response - using its `pages` property. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "list_products_in_product_set" not in self._inner_api_calls: - self._inner_api_calls[ - "list_products_in_product_set" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.list_products_in_product_set, - default_retry=self._method_configs["ListProductsInProductSet"].retry, - default_timeout=self._method_configs[ - "ListProductsInProductSet" - ].timeout, - client_info=self._client_info, - ) - - request = product_search_service_pb2.ListProductsInProductSetRequest( - name=name, page_size=page_size, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["list_products_in_product_set"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="products", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def purge_products( - self, - parent, - product_set_purge_config=None, - delete_orphan_products=None, - force=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Asynchronous API to delete all Products in a ProductSet or all - Products that are in no ProductSet. - - If a Product is a member of the specified ProductSet in addition to - other ProductSets, the Product will still be deleted. - - It is recommended to not delete the specified ProductSet until after - this operation has completed. It is also recommended to not add any of - the Products involved in the batch delete to a new ProductSet while this - operation is running because those Products may still end up deleted. - - It's not possible to undo the PurgeProducts operation. Therefore, it is - recommended to keep the csv files used in ImportProductSets (if that was - how you originally built the Product Set) before starting PurgeProducts, - in case you need to re-import the data after deletion. - - If the plan is to purge all of the Products from a ProductSet and then - re-use the empty ProductSet to re-import new Products into the empty - ProductSet, you must wait until the PurgeProducts operation has finished - for that ProductSet. - - The ``google.longrunning.Operation`` API can be used to keep track of - the progress and results of the request. ``Operation.metadata`` contains - ``BatchOperationMetadata``. (progress) - - Example: - >>> from google.cloud import vision_v1p4beta1 - >>> - >>> client = vision_v1p4beta1.ProductSearchClient() - >>> - >>> parent = client.location_path('[PROJECT]', '[LOCATION]') - >>> - >>> response = client.purge_products(parent) - >>> - >>> def callback(operation_future): - ... # Handle result. - ... result = operation_future.result() - >>> - >>> response.add_done_callback(callback) - >>> - >>> # Handle metadata. - >>> metadata = response.metadata() - - Args: - parent (str): Required. The project and location in which the Products should be - deleted. - - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - product_set_purge_config (Union[dict, ~google.cloud.vision_v1p4beta1.types.ProductSetPurgeConfig]): Specify which ProductSet contains the Products to be deleted. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.vision_v1p4beta1.types.ProductSetPurgeConfig` - delete_orphan_products (bool): If delete_orphan_products is true, all Products that are not in any - ProductSet will be deleted. - force (bool): The default value is false. Override this value to true to actually perform - the purge. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.vision_v1p4beta1.types._OperationFuture` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "purge_products" not in self._inner_api_calls: - self._inner_api_calls[ - "purge_products" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.purge_products, - default_retry=self._method_configs["PurgeProducts"].retry, - default_timeout=self._method_configs["PurgeProducts"].timeout, - client_info=self._client_info, - ) - - # Sanity check: We have some fields which are mutually exclusive; - # raise ValueError if more than one is sent. - google.api_core.protobuf_helpers.check_oneof( - product_set_purge_config=product_set_purge_config, - delete_orphan_products=delete_orphan_products, - ) - - request = product_search_service_pb2.PurgeProductsRequest( - parent=parent, - product_set_purge_config=product_set_purge_config, - delete_orphan_products=delete_orphan_products, - force=force, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("parent", parent)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - operation = self._inner_api_calls["purge_products"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - return google.api_core.operation.from_gapic( - operation, - self.transport._operations_client, - empty_pb2.Empty, - metadata_type=product_search_service_pb2.BatchOperationMetadata, - ) diff --git a/google/cloud/vision_v1p4beta1/gapic/product_search_client_config.py b/google/cloud/vision_v1p4beta1/gapic/product_search_client_config.py deleted file mode 100644 index a94442e6..00000000 --- a/google/cloud/vision_v1p4beta1/gapic/product_search_client_config.py +++ /dev/null @@ -1,137 +0,0 @@ -config = { - "interfaces": { - "google.cloud.vision.v1p4beta1.ProductSearch": { - "retry_codes": { - "no_retry_codes": [], - "retry_policy_3_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "retry_policy_2_codes": [], - }, - "retry_params": { - "retry_policy_3_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 600000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 600000, - "total_timeout_millis": 600000, - }, - "retry_policy_2_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 600000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 600000, - "total_timeout_millis": 600000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - }, - "methods": { - "ImportProductSets": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "CreateProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListProductSets": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "GetProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "UpdateProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "DeleteProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "CreateProduct": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListProducts": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "GetProduct": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "UpdateProduct": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "DeleteProduct": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "CreateReferenceImage": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "DeleteReferenceImage": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "ListReferenceImages": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "GetReferenceImage": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "AddProductToProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "RemoveProductFromProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "ListProductsInProductSet": { - "timeout_millis": 600000, - "retry_codes_name": "retry_policy_3_codes", - "retry_params_name": "retry_policy_3_params", - }, - "PurgeProducts": { - "timeout_millis": 60000, - "retry_codes_name": "no_retry_codes", - "retry_params_name": "no_retry_params", - }, - }, - } - } -} diff --git a/google/cloud/vision_v1p4beta1/gapic/transports/__init__.py b/google/cloud/vision_v1p4beta1/gapic/transports/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/vision_v1p4beta1/gapic/transports/image_annotator_grpc_transport.py b/google/cloud/vision_v1p4beta1/gapic/transports/image_annotator_grpc_transport.py deleted file mode 100644 index b60bdde9..00000000 --- a/google/cloud/vision_v1p4beta1/gapic/transports/image_annotator_grpc_transport.py +++ /dev/null @@ -1,194 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers -from google.api_core import operations_v1 - -from google.cloud.vision_v1p4beta1.proto import image_annotator_pb2_grpc - - -class ImageAnnotatorGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.vision.v1p4beta1 ImageAnnotator API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ) - - def __init__( - self, channel=None, credentials=None, address="vision.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "image_annotator_stub": image_annotator_pb2_grpc.ImageAnnotatorStub( - channel - ), - } - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="vision.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def async_batch_annotate_images(self): - """Return the gRPC stub for :meth:`ImageAnnotatorClient.async_batch_annotate_images`. - - Run asynchronous image detection and annotation for a list of - images. - - Progress and results can be retrieved through the - ``google.longrunning.Operations`` interface. ``Operation.metadata`` - contains ``OperationMetadata`` (metadata). ``Operation.response`` - contains ``AsyncBatchAnnotateImagesResponse`` (results). - - This service will write image annotation outputs to json files in - customer GCS bucket, each json file containing - BatchAnnotateImagesResponse proto. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["image_annotator_stub"].AsyncBatchAnnotateImages - - @property - def async_batch_annotate_files(self): - """Return the gRPC stub for :meth:`ImageAnnotatorClient.async_batch_annotate_files`. - - Run asynchronous image detection and annotation for a list of - generic files, such as PDF files, which may contain multiple pages and - multiple images per page. Progress and results can be retrieved through - the ``google.longrunning.Operations`` interface. ``Operation.metadata`` - contains ``OperationMetadata`` (metadata). ``Operation.response`` - contains ``AsyncBatchAnnotateFilesResponse`` (results). - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["image_annotator_stub"].AsyncBatchAnnotateFiles - - @property - def batch_annotate_images(self): - """Return the gRPC stub for :meth:`ImageAnnotatorClient.batch_annotate_images`. - - Run image detection and annotation for a batch of images. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["image_annotator_stub"].BatchAnnotateImages - - @property - def batch_annotate_files(self): - """Return the gRPC stub for :meth:`ImageAnnotatorClient.batch_annotate_files`. - - Service that performs image detection and annotation for a batch of files. - Now only "application/pdf", "image/tiff" and "image/gif" are supported. - - This service will extract at most 5 (customers can specify which 5 in - AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each - file provided and perform detection and annotation for each image - extracted. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["image_annotator_stub"].BatchAnnotateFiles diff --git a/google/cloud/vision_v1p4beta1/gapic/transports/product_search_grpc_transport.py b/google/cloud/vision_v1p4beta1/gapic/transports/product_search_grpc_transport.py deleted file mode 100644 index ea0f1fce..00000000 --- a/google/cloud/vision_v1p4beta1/gapic/transports/product_search_grpc_transport.py +++ /dev/null @@ -1,510 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -import google.api_core.grpc_helpers -from google.api_core import operations_v1 - -from google.cloud.vision_v1p4beta1.proto import product_search_service_pb2_grpc - - -class ProductSearchGrpcTransport(object): - """gRPC transport class providing stubs for - google.cloud.vision.v1p4beta1 ProductSearch API. - - The transport provides access to the raw gRPC stubs, - which can be used to take advantage of advanced - features of gRPC. - """ - - # The scopes needed to make gRPC calls to all of the methods defined - # in this service. - _OAUTH_SCOPES = ( - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/cloud-vision", - ) - - def __init__( - self, channel=None, credentials=None, address="vision.googleapis.com:443" - ): - """Instantiate the transport class. - - Args: - channel (grpc.Channel): A ``Channel`` instance through - which to make calls. This argument is mutually exclusive - with ``credentials``; providing both will raise an exception. - credentials (google.auth.credentials.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If none - are specified, the client will attempt to ascertain the - credentials from the environment. - address (str): The address where the service is hosted. - """ - # If both `channel` and `credentials` are specified, raise an - # exception (channels come with credentials baked in already). - if channel is not None and credentials is not None: - raise ValueError( - "The `channel` and `credentials` arguments are mutually " "exclusive.", - ) - - # Create the channel. - if channel is None: - channel = self.create_channel( - address=address, - credentials=credentials, - options={ - "grpc.max_send_message_length": -1, - "grpc.max_receive_message_length": -1, - }.items(), - ) - - self._channel = channel - - # gRPC uses objects called "stubs" that are bound to the - # channel and provide a basic method for each RPC. - self._stubs = { - "product_search_stub": product_search_service_pb2_grpc.ProductSearchStub( - channel - ), - } - - # Because this API includes a method that returns a - # long-running operation (proto: google.longrunning.Operation), - # instantiate an LRO client. - self._operations_client = google.api_core.operations_v1.OperationsClient( - channel - ) - - @classmethod - def create_channel( - cls, address="vision.googleapis.com:443", credentials=None, **kwargs - ): - """Create and return a gRPC channel object. - - Args: - address (str): The host for the channel to use. - credentials (~.Credentials): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - kwargs (dict): Keyword arguments, which are passed to the - channel creation. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return google.api_core.grpc_helpers.create_channel( - address, credentials=credentials, scopes=cls._OAUTH_SCOPES, **kwargs - ) - - @property - def channel(self): - """The gRPC channel used by the transport. - - Returns: - grpc.Channel: A gRPC channel object. - """ - return self._channel - - @property - def import_product_sets(self): - """Return the gRPC stub for :meth:`ProductSearchClient.import_product_sets`. - - Asynchronous API that imports a list of reference images to - specified product sets based on a list of image information. - - The ``google.longrunning.Operation`` API can be used to keep track of - the progress and results of the request. ``Operation.metadata`` contains - ``BatchOperationMetadata``. (progress) ``Operation.response`` contains - ``ImportProductSetsResponse``. (results) - - The input source of this method is a csv file on Google Cloud Storage. - For the format of the csv file please see - ``ImportProductSetsGcsSource.csv_file_uri``. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].ImportProductSets - - @property - def create_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.create_product_set`. - - Creates and returns a new ProductSet resource. - - Possible errors: - - - Returns INVALID_ARGUMENT if display_name is missing, or is longer - than 4096 characters. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].CreateProductSet - - @property - def list_product_sets(self): - """Return the gRPC stub for :meth:`ProductSearchClient.list_product_sets`. - - Lists ProductSets in an unspecified order. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100, or less - than 1. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].ListProductSets - - @property - def get_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.get_product_set`. - - Gets information associated with a ProductSet. - - Possible errors: - - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].GetProductSet - - @property - def update_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.update_product_set`. - - Makes changes to a ProductSet resource. Only display_name can be - updated currently. - - Possible errors: - - - Returns NOT_FOUND if the ProductSet does not exist. - - Returns INVALID_ARGUMENT if display_name is present in update_mask - but missing from the request or longer than 4096 characters. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].UpdateProductSet - - @property - def delete_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.delete_product_set`. - - Permanently deletes a ProductSet. Products and ReferenceImages in the - ProductSet are not deleted. - - The actual image files are not deleted from Google Cloud Storage. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].DeleteProductSet - - @property - def create_product(self): - """Return the gRPC stub for :meth:`ProductSearchClient.create_product`. - - Creates and returns a new product resource. - - Possible errors: - - - Returns INVALID_ARGUMENT if display_name is missing or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if description is longer than 4096 - characters. - - Returns INVALID_ARGUMENT if product_category is missing or invalid. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].CreateProduct - - @property - def list_products(self): - """Return the gRPC stub for :meth:`ProductSearchClient.list_products`. - - Lists products in an unspecified order. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100 or less - than 1. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].ListProducts - - @property - def get_product(self): - """Return the gRPC stub for :meth:`ProductSearchClient.get_product`. - - Gets information associated with a Product. - - Possible errors: - - - Returns NOT_FOUND if the Product does not exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].GetProduct - - @property - def update_product(self): - """Return the gRPC stub for :meth:`ProductSearchClient.update_product`. - - Makes changes to a Product resource. Only the ``display_name``, - ``description``, and ``labels`` fields can be updated right now. - - If labels are updated, the change will not be reflected in queries until - the next index time. - - Possible errors: - - - Returns NOT_FOUND if the Product does not exist. - - Returns INVALID_ARGUMENT if display_name is present in update_mask - but is missing from the request or longer than 4096 characters. - - Returns INVALID_ARGUMENT if description is present in update_mask but - is longer than 4096 characters. - - Returns INVALID_ARGUMENT if product_category is present in - update_mask. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].UpdateProduct - - @property - def delete_product(self): - """Return the gRPC stub for :meth:`ProductSearchClient.delete_product`. - - Permanently deletes a product and its reference images. - - Metadata of the product and all its images will be deleted right away, but - search queries against ProductSets containing the product may still work - until all related caches are refreshed. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].DeleteProduct - - @property - def create_reference_image(self): - """Return the gRPC stub for :meth:`ProductSearchClient.create_reference_image`. - - Creates and returns a new ReferenceImage resource. - - The ``bounding_poly`` field is optional. If ``bounding_poly`` is not - specified, the system will try to detect regions of interest in the - image that are compatible with the product_category on the parent - product. If it is specified, detection is ALWAYS skipped. The system - converts polygons into non-rotated rectangles. - - Note that the pipeline will resize the image if the image resolution is - too large to process (above 50MP). - - Possible errors: - - - Returns INVALID_ARGUMENT if the image_uri is missing or longer than - 4096 characters. - - Returns INVALID_ARGUMENT if the product does not exist. - - Returns INVALID_ARGUMENT if bounding_poly is not provided, and - nothing compatible with the parent product's product_category is - detected. - - Returns INVALID_ARGUMENT if bounding_poly contains more than 10 - polygons. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].CreateReferenceImage - - @property - def delete_reference_image(self): - """Return the gRPC stub for :meth:`ProductSearchClient.delete_reference_image`. - - Permanently deletes a reference image. - - The image metadata will be deleted right away, but search queries - against ProductSets containing the image may still work until all related - caches are refreshed. - - The actual image files are not deleted from Google Cloud Storage. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].DeleteReferenceImage - - @property - def list_reference_images(self): - """Return the gRPC stub for :meth:`ProductSearchClient.list_reference_images`. - - Lists reference images. - - Possible errors: - - - Returns NOT_FOUND if the parent product does not exist. - - Returns INVALID_ARGUMENT if the page_size is greater than 100, or - less than 1. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].ListReferenceImages - - @property - def get_reference_image(self): - """Return the gRPC stub for :meth:`ProductSearchClient.get_reference_image`. - - Gets information associated with a ReferenceImage. - - Possible errors: - - - Returns NOT_FOUND if the specified image does not exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].GetReferenceImage - - @property - def add_product_to_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.add_product_to_product_set`. - - Adds a Product to the specified ProductSet. If the Product is - already present, no change is made. - - One Product can be added to at most 100 ProductSets. - - Possible errors: - - - Returns NOT_FOUND if the Product or the ProductSet doesn't exist. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].AddProductToProductSet - - @property - def remove_product_from_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.remove_product_from_product_set`. - - Removes a Product from the specified ProductSet. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].RemoveProductFromProductSet - - @property - def list_products_in_product_set(self): - """Return the gRPC stub for :meth:`ProductSearchClient.list_products_in_product_set`. - - Lists the Products in a ProductSet, in an unspecified order. If the - ProductSet does not exist, the products field of the response will be - empty. - - Possible errors: - - - Returns INVALID_ARGUMENT if page_size is greater than 100 or less - than 1. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].ListProductsInProductSet - - @property - def purge_products(self): - """Return the gRPC stub for :meth:`ProductSearchClient.purge_products`. - - Asynchronous API to delete all Products in a ProductSet or all - Products that are in no ProductSet. - - If a Product is a member of the specified ProductSet in addition to - other ProductSets, the Product will still be deleted. - - It is recommended to not delete the specified ProductSet until after - this operation has completed. It is also recommended to not add any of - the Products involved in the batch delete to a new ProductSet while this - operation is running because those Products may still end up deleted. - - It's not possible to undo the PurgeProducts operation. Therefore, it is - recommended to keep the csv files used in ImportProductSets (if that was - how you originally built the Product Set) before starting PurgeProducts, - in case you need to re-import the data after deletion. - - If the plan is to purge all of the Products from a ProductSet and then - re-use the empty ProductSet to re-import new Products into the empty - ProductSet, you must wait until the PurgeProducts operation has finished - for that ProductSet. - - The ``google.longrunning.Operation`` API can be used to keep track of - the progress and results of the request. ``Operation.metadata`` contains - ``BatchOperationMetadata``. (progress) - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["product_search_stub"].PurgeProducts diff --git a/google/cloud/vision_v1p4beta1/proto/__init__.py b/google/cloud/vision_v1p4beta1/proto/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/google/cloud/vision_v1p4beta1/proto/face_pb2.py b/google/cloud/vision_v1p4beta1/proto/face_pb2.py deleted file mode 100644 index 6b0756d4..00000000 --- a/google/cloud/vision_v1p4beta1/proto/face_pb2.py +++ /dev/null @@ -1,286 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p4beta1/proto/face.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.cloud.vision_v1p4beta1.proto import ( - geometry_pb2 as google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2, -) - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p4beta1/proto/face.proto", - package="google.cloud.vision.v1p4beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p4beta1B\016CelebrityProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision\370\001\001\242\002\004GCVN", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n.google/cloud/vision_v1p4beta1/proto/face.proto\x12\x1dgoogle.cloud.vision.v1p4beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x32google/cloud/vision_v1p4beta1/proto/geometry.proto".\n\x15\x46\x61\x63\x65RecognitionParams\x12\x15\n\rcelebrity_set\x18\x01 \x03(\t"D\n\tCelebrity\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t"h\n\x15\x46\x61\x63\x65RecognitionResult\x12;\n\tcelebrity\x18\x01 \x01(\x0b\x32(.google.cloud.vision.v1p4beta1.Celebrity\x12\x12\n\nconfidence\x18\x02 \x01(\x02\x42\x84\x01\n!com.google.cloud.vision.v1p4beta1B\x0e\x43\x65lebrityProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision\xf8\x01\x01\xa2\x02\x04GCVNb\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2.DESCRIPTOR, - ], -) - - -_FACERECOGNITIONPARAMS = _descriptor.Descriptor( - name="FaceRecognitionParams", - full_name="google.cloud.vision.v1p4beta1.FaceRecognitionParams", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="celebrity_set", - full_name="google.cloud.vision.v1p4beta1.FaceRecognitionParams.celebrity_set", - index=0, - number=1, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=163, - serialized_end=209, -) - - -_CELEBRITY = _descriptor.Descriptor( - name="Celebrity", - full_name="google.cloud.vision.v1p4beta1.Celebrity", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p4beta1.Celebrity.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="display_name", - full_name="google.cloud.vision.v1p4beta1.Celebrity.display_name", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.vision.v1p4beta1.Celebrity.description", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=211, - serialized_end=279, -) - - -_FACERECOGNITIONRESULT = _descriptor.Descriptor( - name="FaceRecognitionResult", - full_name="google.cloud.vision.v1p4beta1.FaceRecognitionResult", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="celebrity", - full_name="google.cloud.vision.v1p4beta1.FaceRecognitionResult.celebrity", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p4beta1.FaceRecognitionResult.confidence", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=281, - serialized_end=385, -) - -_FACERECOGNITIONRESULT.fields_by_name["celebrity"].message_type = _CELEBRITY -DESCRIPTOR.message_types_by_name["FaceRecognitionParams"] = _FACERECOGNITIONPARAMS -DESCRIPTOR.message_types_by_name["Celebrity"] = _CELEBRITY -DESCRIPTOR.message_types_by_name["FaceRecognitionResult"] = _FACERECOGNITIONRESULT -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -FaceRecognitionParams = _reflection.GeneratedProtocolMessageType( - "FaceRecognitionParams", - (_message.Message,), - { - "DESCRIPTOR": _FACERECOGNITIONPARAMS, - "__module__": "google.cloud.vision_v1p4beta1.proto.face_pb2", - "__doc__": """Parameters for a celebrity recognition request. - - Attributes: - celebrity_set: - The resource names for one or more - [CelebritySet][google.cloud.vision.v1p4beta1.CelebritySet]s. A - celebrity set is preloaded and can be specified as - “builtin/default”. If this is specified, the algorithm will - try to match the faces detected in the input image to the - Celebrities in the CelebritySets. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.FaceRecognitionParams) - }, -) -_sym_db.RegisterMessage(FaceRecognitionParams) - -Celebrity = _reflection.GeneratedProtocolMessageType( - "Celebrity", - (_message.Message,), - { - "DESCRIPTOR": _CELEBRITY, - "__module__": "google.cloud.vision_v1p4beta1.proto.face_pb2", - "__doc__": """A Celebrity is a group of Faces with an identity. - - Attributes: - name: - The resource name of the preloaded Celebrity. Has the format - ``builtin/{mid}``. - display_name: - The Celebrity’s display name. - description: - The Celebrity’s description. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.Celebrity) - }, -) -_sym_db.RegisterMessage(Celebrity) - -FaceRecognitionResult = _reflection.GeneratedProtocolMessageType( - "FaceRecognitionResult", - (_message.Message,), - { - "DESCRIPTOR": _FACERECOGNITIONRESULT, - "__module__": "google.cloud.vision_v1p4beta1.proto.face_pb2", - "__doc__": """Information about a face’s identity. - - Attributes: - celebrity: - The [Celebrity][google.cloud.vision.v1p4beta1.Celebrity] that - this face was matched to. - confidence: - Recognition confidence. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.FaceRecognitionResult) - }, -) -_sym_db.RegisterMessage(FaceRecognitionResult) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p4beta1/proto/face_pb2_grpc.py b/google/cloud/vision_v1p4beta1/proto/face_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/vision_v1p4beta1/proto/face_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/vision_v1p4beta1/proto/geometry_pb2.py b/google/cloud/vision_v1p4beta1/proto/geometry_pb2.py deleted file mode 100644 index a8a3d04e..00000000 --- a/google/cloud/vision_v1p4beta1/proto/geometry_pb2.py +++ /dev/null @@ -1,373 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p4beta1/proto/geometry.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p4beta1/proto/geometry.proto", - package="google.cloud.vision.v1p4beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p4beta1B\rGeometryProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision\370\001\001\242\002\004GCVN", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n2google/cloud/vision_v1p4beta1/proto/geometry.proto\x12\x1dgoogle.cloud.vision.v1p4beta1\x1a\x1cgoogle/api/annotations.proto"\x1e\n\x06Vertex\x12\t\n\x01x\x18\x01 \x01(\x05\x12\t\n\x01y\x18\x02 \x01(\x05"(\n\x10NormalizedVertex\x12\t\n\x01x\x18\x01 \x01(\x02\x12\t\n\x01y\x18\x02 \x01(\x02"\x95\x01\n\x0c\x42oundingPoly\x12\x37\n\x08vertices\x18\x01 \x03(\x0b\x32%.google.cloud.vision.v1p4beta1.Vertex\x12L\n\x13normalized_vertices\x18\x02 \x03(\x0b\x32/.google.cloud.vision.v1p4beta1.NormalizedVertex"+\n\x08Position\x12\t\n\x01x\x18\x01 \x01(\x02\x12\t\n\x01y\x18\x02 \x01(\x02\x12\t\n\x01z\x18\x03 \x01(\x02\x42\x83\x01\n!com.google.cloud.vision.v1p4beta1B\rGeometryProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision\xf8\x01\x01\xa2\x02\x04GCVNb\x06proto3', - dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,], -) - - -_VERTEX = _descriptor.Descriptor( - name="Vertex", - full_name="google.cloud.vision.v1p4beta1.Vertex", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="x", - full_name="google.cloud.vision.v1p4beta1.Vertex.x", - index=0, - number=1, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="y", - full_name="google.cloud.vision.v1p4beta1.Vertex.y", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=115, - serialized_end=145, -) - - -_NORMALIZEDVERTEX = _descriptor.Descriptor( - name="NormalizedVertex", - full_name="google.cloud.vision.v1p4beta1.NormalizedVertex", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="x", - full_name="google.cloud.vision.v1p4beta1.NormalizedVertex.x", - index=0, - number=1, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="y", - full_name="google.cloud.vision.v1p4beta1.NormalizedVertex.y", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=147, - serialized_end=187, -) - - -_BOUNDINGPOLY = _descriptor.Descriptor( - name="BoundingPoly", - full_name="google.cloud.vision.v1p4beta1.BoundingPoly", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="vertices", - full_name="google.cloud.vision.v1p4beta1.BoundingPoly.vertices", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="normalized_vertices", - full_name="google.cloud.vision.v1p4beta1.BoundingPoly.normalized_vertices", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=190, - serialized_end=339, -) - - -_POSITION = _descriptor.Descriptor( - name="Position", - full_name="google.cloud.vision.v1p4beta1.Position", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="x", - full_name="google.cloud.vision.v1p4beta1.Position.x", - index=0, - number=1, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="y", - full_name="google.cloud.vision.v1p4beta1.Position.y", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="z", - full_name="google.cloud.vision.v1p4beta1.Position.z", - index=2, - number=3, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=341, - serialized_end=384, -) - -_BOUNDINGPOLY.fields_by_name["vertices"].message_type = _VERTEX -_BOUNDINGPOLY.fields_by_name["normalized_vertices"].message_type = _NORMALIZEDVERTEX -DESCRIPTOR.message_types_by_name["Vertex"] = _VERTEX -DESCRIPTOR.message_types_by_name["NormalizedVertex"] = _NORMALIZEDVERTEX -DESCRIPTOR.message_types_by_name["BoundingPoly"] = _BOUNDINGPOLY -DESCRIPTOR.message_types_by_name["Position"] = _POSITION -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Vertex = _reflection.GeneratedProtocolMessageType( - "Vertex", - (_message.Message,), - { - "DESCRIPTOR": _VERTEX, - "__module__": "google.cloud.vision_v1p4beta1.proto.geometry_pb2", - "__doc__": """X coordinate. - - Attributes: - y: - Y coordinate. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.Vertex) - }, -) -_sym_db.RegisterMessage(Vertex) - -NormalizedVertex = _reflection.GeneratedProtocolMessageType( - "NormalizedVertex", - (_message.Message,), - { - "DESCRIPTOR": _NORMALIZEDVERTEX, - "__module__": "google.cloud.vision_v1p4beta1.proto.geometry_pb2", - "__doc__": """X coordinate. - - Attributes: - y: - Y coordinate. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.NormalizedVertex) - }, -) -_sym_db.RegisterMessage(NormalizedVertex) - -BoundingPoly = _reflection.GeneratedProtocolMessageType( - "BoundingPoly", - (_message.Message,), - { - "DESCRIPTOR": _BOUNDINGPOLY, - "__module__": "google.cloud.vision_v1p4beta1.proto.geometry_pb2", - "__doc__": """A bounding polygon for the detected image annotation. - - Attributes: - vertices: - The bounding polygon vertices. - normalized_vertices: - The bounding polygon normalized vertices. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.BoundingPoly) - }, -) -_sym_db.RegisterMessage(BoundingPoly) - -Position = _reflection.GeneratedProtocolMessageType( - "Position", - (_message.Message,), - { - "DESCRIPTOR": _POSITION, - "__module__": "google.cloud.vision_v1p4beta1.proto.geometry_pb2", - "__doc__": """A 3D position in the image, used primarily for Face detection - landmarks. A valid Position must have both x and y coordinates. The - position coordinates are in the same scale as the original image. - - Attributes: - x: - X coordinate. - y: - Y coordinate. - z: - Z coordinate (or depth). - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.Position) - }, -) -_sym_db.RegisterMessage(Position) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p4beta1/proto/geometry_pb2_grpc.py b/google/cloud/vision_v1p4beta1/proto/geometry_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/vision_v1p4beta1/proto/geometry_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/vision_v1p4beta1/proto/image_annotator_pb2.py b/google/cloud/vision_v1p4beta1/proto/image_annotator_pb2.py deleted file mode 100644 index 92ac0789..00000000 --- a/google/cloud/vision_v1p4beta1/proto/image_annotator_pb2.py +++ /dev/null @@ -1,5016 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p4beta1/proto/image_annotator.proto -"""Generated protocol buffer code.""" -from google.protobuf.internal import enum_type_wrapper -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.cloud.vision_v1p4beta1.proto import ( - face_pb2 as google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_face__pb2, -) -from google.cloud.vision_v1p4beta1.proto import ( - geometry_pb2 as google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2, -) -from google.cloud.vision_v1p4beta1.proto import ( - product_search_pb2 as google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__pb2, -) -from google.cloud.vision_v1p4beta1.proto import ( - text_annotation_pb2 as google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_text__annotation__pb2, -) -from google.cloud.vision_v1p4beta1.proto import ( - web_detection_pb2 as google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_web__detection__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2 -from google.type import color_pb2 as google_dot_type_dot_color__pb2 -from google.type import latlng_pb2 as google_dot_type_dot_latlng__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p4beta1/proto/image_annotator.proto", - package="google.cloud.vision.v1p4beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p4beta1B\023ImageAnnotatorProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision\370\001\001\242\002\004GCVN", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n9google/cloud/vision_v1p4beta1/proto/image_annotator.proto\x12\x1dgoogle.cloud.vision.v1p4beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a.google/cloud/vision_v1p4beta1/proto/face.proto\x1a\x32google/cloud/vision_v1p4beta1/proto/geometry.proto\x1a\x38google/cloud/vision_v1p4beta1/proto/product_search.proto\x1a\x39google/cloud/vision_v1p4beta1/proto/text_annotation.proto\x1a\x37google/cloud/vision_v1p4beta1/proto/web_detection.proto\x1a#google/longrunning/operations.proto\x1a google/protobuf/field_mask.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x17google/rpc/status.proto\x1a\x17google/type/color.proto\x1a\x18google/type/latlng.proto"\x8e\x03\n\x07\x46\x65\x61ture\x12\x39\n\x04type\x18\x01 \x01(\x0e\x32+.google.cloud.vision.v1p4beta1.Feature.Type\x12\x13\n\x0bmax_results\x18\x02 \x01(\x05\x12\r\n\x05model\x18\x03 \x01(\t"\xa3\x02\n\x04Type\x12\x14\n\x10TYPE_UNSPECIFIED\x10\x00\x12\x12\n\x0e\x46\x41\x43\x45_DETECTION\x10\x01\x12\x16\n\x12LANDMARK_DETECTION\x10\x02\x12\x12\n\x0eLOGO_DETECTION\x10\x03\x12\x13\n\x0fLABEL_DETECTION\x10\x04\x12\x12\n\x0eTEXT_DETECTION\x10\x05\x12\x1b\n\x17\x44OCUMENT_TEXT_DETECTION\x10\x0b\x12\x19\n\x15SAFE_SEARCH_DETECTION\x10\x06\x12\x14\n\x10IMAGE_PROPERTIES\x10\x07\x12\x0e\n\nCROP_HINTS\x10\t\x12\x11\n\rWEB_DETECTION\x10\n\x12\x12\n\x0ePRODUCT_SEARCH\x10\x0c\x12\x17\n\x13OBJECT_LOCALIZATION\x10\x13"7\n\x0bImageSource\x12\x15\n\rgcs_image_uri\x18\x01 \x01(\t\x12\x11\n\timage_uri\x18\x02 \x01(\t"T\n\x05Image\x12\x0f\n\x07\x63ontent\x18\x01 \x01(\x0c\x12:\n\x06source\x18\x02 \x01(\x0b\x32*.google.cloud.vision.v1p4beta1.ImageSource"\xed\x0e\n\x0e\x46\x61\x63\x65\x41nnotation\x12\x42\n\rbounding_poly\x18\x01 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.BoundingPoly\x12\x45\n\x10\x66\x64_bounding_poly\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.BoundingPoly\x12I\n\tlandmarks\x18\x03 \x03(\x0b\x32\x36.google.cloud.vision.v1p4beta1.FaceAnnotation.Landmark\x12\x12\n\nroll_angle\x18\x04 \x01(\x02\x12\x11\n\tpan_angle\x18\x05 \x01(\x02\x12\x12\n\ntilt_angle\x18\x06 \x01(\x02\x12\x1c\n\x14\x64\x65tection_confidence\x18\x07 \x01(\x02\x12\x1e\n\x16landmarking_confidence\x18\x08 \x01(\x02\x12\x41\n\x0ejoy_likelihood\x18\t \x01(\x0e\x32).google.cloud.vision.v1p4beta1.Likelihood\x12\x44\n\x11sorrow_likelihood\x18\n \x01(\x0e\x32).google.cloud.vision.v1p4beta1.Likelihood\x12\x43\n\x10\x61nger_likelihood\x18\x0b \x01(\x0e\x32).google.cloud.vision.v1p4beta1.Likelihood\x12\x46\n\x13surprise_likelihood\x18\x0c \x01(\x0e\x32).google.cloud.vision.v1p4beta1.Likelihood\x12K\n\x18under_exposed_likelihood\x18\r \x01(\x0e\x32).google.cloud.vision.v1p4beta1.Likelihood\x12\x45\n\x12\x62lurred_likelihood\x18\x0e \x01(\x0e\x32).google.cloud.vision.v1p4beta1.Likelihood\x12\x46\n\x13headwear_likelihood\x18\x0f \x01(\x0e\x32).google.cloud.vision.v1p4beta1.Likelihood\x12P\n\x12recognition_result\x18\x10 \x03(\x0b\x32\x34.google.cloud.vision.v1p4beta1.FaceRecognitionResult\x1a\xc7\x07\n\x08Landmark\x12I\n\x04type\x18\x03 \x01(\x0e\x32;.google.cloud.vision.v1p4beta1.FaceAnnotation.Landmark.Type\x12\x39\n\x08position\x18\x04 \x01(\x0b\x32\'.google.cloud.vision.v1p4beta1.Position"\xb4\x06\n\x04Type\x12\x14\n\x10UNKNOWN_LANDMARK\x10\x00\x12\x0c\n\x08LEFT_EYE\x10\x01\x12\r\n\tRIGHT_EYE\x10\x02\x12\x18\n\x14LEFT_OF_LEFT_EYEBROW\x10\x03\x12\x19\n\x15RIGHT_OF_LEFT_EYEBROW\x10\x04\x12\x19\n\x15LEFT_OF_RIGHT_EYEBROW\x10\x05\x12\x1a\n\x16RIGHT_OF_RIGHT_EYEBROW\x10\x06\x12\x19\n\x15MIDPOINT_BETWEEN_EYES\x10\x07\x12\x0c\n\x08NOSE_TIP\x10\x08\x12\r\n\tUPPER_LIP\x10\t\x12\r\n\tLOWER_LIP\x10\n\x12\x0e\n\nMOUTH_LEFT\x10\x0b\x12\x0f\n\x0bMOUTH_RIGHT\x10\x0c\x12\x10\n\x0cMOUTH_CENTER\x10\r\x12\x15\n\x11NOSE_BOTTOM_RIGHT\x10\x0e\x12\x14\n\x10NOSE_BOTTOM_LEFT\x10\x0f\x12\x16\n\x12NOSE_BOTTOM_CENTER\x10\x10\x12\x19\n\x15LEFT_EYE_TOP_BOUNDARY\x10\x11\x12\x19\n\x15LEFT_EYE_RIGHT_CORNER\x10\x12\x12\x1c\n\x18LEFT_EYE_BOTTOM_BOUNDARY\x10\x13\x12\x18\n\x14LEFT_EYE_LEFT_CORNER\x10\x14\x12\x1a\n\x16RIGHT_EYE_TOP_BOUNDARY\x10\x15\x12\x1a\n\x16RIGHT_EYE_RIGHT_CORNER\x10\x16\x12\x1d\n\x19RIGHT_EYE_BOTTOM_BOUNDARY\x10\x17\x12\x19\n\x15RIGHT_EYE_LEFT_CORNER\x10\x18\x12\x1f\n\x1bLEFT_EYEBROW_UPPER_MIDPOINT\x10\x19\x12 \n\x1cRIGHT_EYEBROW_UPPER_MIDPOINT\x10\x1a\x12\x14\n\x10LEFT_EAR_TRAGION\x10\x1b\x12\x15\n\x11RIGHT_EAR_TRAGION\x10\x1c\x12\x12\n\x0eLEFT_EYE_PUPIL\x10\x1d\x12\x13\n\x0fRIGHT_EYE_PUPIL\x10\x1e\x12\x15\n\x11\x46OREHEAD_GLABELLA\x10\x1f\x12\x11\n\rCHIN_GNATHION\x10 \x12\x14\n\x10\x43HIN_LEFT_GONION\x10!\x12\x15\n\x11\x43HIN_RIGHT_GONION\x10""4\n\x0cLocationInfo\x12$\n\x07lat_lng\x18\x01 \x01(\x0b\x32\x13.google.type.LatLng"=\n\x08Property\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t\x12\x14\n\x0cuint64_value\x18\x03 \x01(\x04"\xc0\x02\n\x10\x45ntityAnnotation\x12\x0b\n\x03mid\x18\x01 \x01(\t\x12\x0e\n\x06locale\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\x12\r\n\x05score\x18\x04 \x01(\x02\x12\x16\n\nconfidence\x18\x05 \x01(\x02\x42\x02\x18\x01\x12\x12\n\ntopicality\x18\x06 \x01(\x02\x12\x42\n\rbounding_poly\x18\x07 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.BoundingPoly\x12>\n\tlocations\x18\x08 \x03(\x0b\x32+.google.cloud.vision.v1p4beta1.LocationInfo\x12;\n\nproperties\x18\t \x03(\x0b\x32\'.google.cloud.vision.v1p4beta1.Property"\xa0\x01\n\x19LocalizedObjectAnnotation\x12\x0b\n\x03mid\x18\x01 \x01(\t\x12\x15\n\rlanguage_code\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\r\n\x05score\x18\x04 \x01(\x02\x12\x42\n\rbounding_poly\x18\x05 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.BoundingPoly"\xbc\x02\n\x14SafeSearchAnnotation\x12\x38\n\x05\x61\x64ult\x18\x01 \x01(\x0e\x32).google.cloud.vision.v1p4beta1.Likelihood\x12\x38\n\x05spoof\x18\x02 \x01(\x0e\x32).google.cloud.vision.v1p4beta1.Likelihood\x12:\n\x07medical\x18\x03 \x01(\x0e\x32).google.cloud.vision.v1p4beta1.Likelihood\x12;\n\x08violence\x18\x04 \x01(\x0e\x32).google.cloud.vision.v1p4beta1.Likelihood\x12\x37\n\x04racy\x18\t \x01(\x0e\x32).google.cloud.vision.v1p4beta1.Likelihood"a\n\x0bLatLongRect\x12(\n\x0bmin_lat_lng\x18\x01 \x01(\x0b\x32\x13.google.type.LatLng\x12(\n\x0bmax_lat_lng\x18\x02 \x01(\x0b\x32\x13.google.type.LatLng"U\n\tColorInfo\x12!\n\x05\x63olor\x18\x01 \x01(\x0b\x32\x12.google.type.Color\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x16\n\x0epixel_fraction\x18\x03 \x01(\x02"T\n\x18\x44ominantColorsAnnotation\x12\x38\n\x06\x63olors\x18\x01 \x03(\x0b\x32(.google.cloud.vision.v1p4beta1.ColorInfo"c\n\x0fImageProperties\x12P\n\x0f\x64ominant_colors\x18\x01 \x01(\x0b\x32\x37.google.cloud.vision.v1p4beta1.DominantColorsAnnotation"\x7f\n\x08\x43ropHint\x12\x42\n\rbounding_poly\x18\x01 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.BoundingPoly\x12\x12\n\nconfidence\x18\x02 \x01(\x02\x12\x1b\n\x13importance_fraction\x18\x03 \x01(\x02"R\n\x13\x43ropHintsAnnotation\x12;\n\ncrop_hints\x18\x01 \x03(\x0b\x32\'.google.cloud.vision.v1p4beta1.CropHint"(\n\x0f\x43ropHintsParams\x12\x15\n\raspect_ratios\x18\x01 \x03(\x02"1\n\x12WebDetectionParams\x12\x1b\n\x13include_geo_results\x18\x02 \x01(\x08"\xaf\x03\n\x0cImageContext\x12\x41\n\rlat_long_rect\x18\x01 \x01(\x0b\x32*.google.cloud.vision.v1p4beta1.LatLongRect\x12\x16\n\x0elanguage_hints\x18\x02 \x03(\t\x12I\n\x11\x63rop_hints_params\x18\x04 \x01(\x0b\x32..google.cloud.vision.v1p4beta1.CropHintsParams\x12U\n\x17\x66\x61\x63\x65_recognition_params\x18\n \x01(\x0b\x32\x34.google.cloud.vision.v1p4beta1.FaceRecognitionParams\x12Q\n\x15product_search_params\x18\x05 \x01(\x0b\x32\x32.google.cloud.vision.v1p4beta1.ProductSearchParams\x12O\n\x14web_detection_params\x18\x06 \x01(\x0b\x32\x31.google.cloud.vision.v1p4beta1.WebDetectionParams"\xc9\x01\n\x14\x41nnotateImageRequest\x12\x33\n\x05image\x18\x01 \x01(\x0b\x32$.google.cloud.vision.v1p4beta1.Image\x12\x38\n\x08\x66\x65\x61tures\x18\x02 \x03(\x0b\x32&.google.cloud.vision.v1p4beta1.Feature\x12\x42\n\rimage_context\x18\x03 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.ImageContext":\n\x16ImageAnnotationContext\x12\x0b\n\x03uri\x18\x01 \x01(\t\x12\x13\n\x0bpage_number\x18\x02 \x01(\x05"\xbf\x08\n\x15\x41nnotateImageResponse\x12G\n\x10\x66\x61\x63\x65_annotations\x18\x01 \x03(\x0b\x32-.google.cloud.vision.v1p4beta1.FaceAnnotation\x12M\n\x14landmark_annotations\x18\x02 \x03(\x0b\x32/.google.cloud.vision.v1p4beta1.EntityAnnotation\x12I\n\x10logo_annotations\x18\x03 \x03(\x0b\x32/.google.cloud.vision.v1p4beta1.EntityAnnotation\x12J\n\x11label_annotations\x18\x04 \x03(\x0b\x32/.google.cloud.vision.v1p4beta1.EntityAnnotation\x12^\n\x1clocalized_object_annotations\x18\x16 \x03(\x0b\x32\x38.google.cloud.vision.v1p4beta1.LocalizedObjectAnnotation\x12I\n\x10text_annotations\x18\x05 \x03(\x0b\x32/.google.cloud.vision.v1p4beta1.EntityAnnotation\x12K\n\x14\x66ull_text_annotation\x18\x0c \x01(\x0b\x32-.google.cloud.vision.v1p4beta1.TextAnnotation\x12S\n\x16safe_search_annotation\x18\x06 \x01(\x0b\x32\x33.google.cloud.vision.v1p4beta1.SafeSearchAnnotation\x12S\n\x1bimage_properties_annotation\x18\x08 \x01(\x0b\x32..google.cloud.vision.v1p4beta1.ImageProperties\x12Q\n\x15\x63rop_hints_annotation\x18\x0b \x01(\x0b\x32\x32.google.cloud.vision.v1p4beta1.CropHintsAnnotation\x12\x42\n\rweb_detection\x18\r \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.WebDetection\x12S\n\x16product_search_results\x18\x0e \x01(\x0b\x32\x33.google.cloud.vision.v1p4beta1.ProductSearchResults\x12!\n\x05\x65rror\x18\t \x01(\x0b\x32\x12.google.rpc.Status\x12\x46\n\x07\x63ontext\x18\x15 \x01(\x0b\x32\x35.google.cloud.vision.v1p4beta1.ImageAnnotationContext"h\n\x1a\x42\x61tchAnnotateImagesRequest\x12J\n\x08requests\x18\x01 \x03(\x0b\x32\x33.google.cloud.vision.v1p4beta1.AnnotateImageRequestB\x03\xe0\x41\x02"f\n\x1b\x42\x61tchAnnotateImagesResponse\x12G\n\tresponses\x18\x01 \x03(\x0b\x32\x34.google.cloud.vision.v1p4beta1.AnnotateImageResponse"\xe4\x01\n\x13\x41nnotateFileRequest\x12@\n\x0cinput_config\x18\x01 \x01(\x0b\x32*.google.cloud.vision.v1p4beta1.InputConfig\x12\x38\n\x08\x66\x65\x61tures\x18\x02 \x03(\x0b\x32&.google.cloud.vision.v1p4beta1.Feature\x12\x42\n\rimage_context\x18\x03 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.ImageContext\x12\r\n\x05pages\x18\x04 \x03(\x05"\xd9\x01\n\x14\x41nnotateFileResponse\x12@\n\x0cinput_config\x18\x01 \x01(\x0b\x32*.google.cloud.vision.v1p4beta1.InputConfig\x12G\n\tresponses\x18\x02 \x03(\x0b\x32\x34.google.cloud.vision.v1p4beta1.AnnotateImageResponse\x12\x13\n\x0btotal_pages\x18\x03 \x01(\x05\x12!\n\x05\x65rror\x18\x04 \x01(\x0b\x32\x12.google.rpc.Status"f\n\x19\x42\x61tchAnnotateFilesRequest\x12I\n\x08requests\x18\x01 \x03(\x0b\x32\x32.google.cloud.vision.v1p4beta1.AnnotateFileRequestB\x03\xe0\x41\x02"d\n\x1a\x42\x61tchAnnotateFilesResponse\x12\x46\n\tresponses\x18\x01 \x03(\x0b\x32\x33.google.cloud.vision.v1p4beta1.AnnotateFileResponse"\x9e\x02\n\x18\x41syncAnnotateFileRequest\x12@\n\x0cinput_config\x18\x01 \x01(\x0b\x32*.google.cloud.vision.v1p4beta1.InputConfig\x12\x38\n\x08\x66\x65\x61tures\x18\x02 \x03(\x0b\x32&.google.cloud.vision.v1p4beta1.Feature\x12\x42\n\rimage_context\x18\x03 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.ImageContext\x12\x42\n\routput_config\x18\x04 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.OutputConfig"_\n\x19\x41syncAnnotateFileResponse\x12\x42\n\routput_config\x18\x01 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.OutputConfig"\xb6\x01\n\x1f\x41syncBatchAnnotateImagesRequest\x12J\n\x08requests\x18\x01 \x03(\x0b\x32\x33.google.cloud.vision.v1p4beta1.AnnotateImageRequestB\x03\xe0\x41\x02\x12G\n\routput_config\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.OutputConfigB\x03\xe0\x41\x02"f\n AsyncBatchAnnotateImagesResponse\x12\x42\n\routput_config\x18\x01 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.OutputConfig"p\n\x1e\x41syncBatchAnnotateFilesRequest\x12N\n\x08requests\x18\x01 \x03(\x0b\x32\x37.google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequestB\x03\xe0\x41\x02"n\n\x1f\x41syncBatchAnnotateFilesResponse\x12K\n\tresponses\x18\x01 \x03(\x0b\x32\x38.google.cloud.vision.v1p4beta1.AsyncAnnotateFileResponse"o\n\x0bInputConfig\x12<\n\ngcs_source\x18\x01 \x01(\x0b\x32(.google.cloud.vision.v1p4beta1.GcsSource\x12\x0f\n\x07\x63ontent\x18\x03 \x01(\x0c\x12\x11\n\tmime_type\x18\x02 \x01(\t"j\n\x0cOutputConfig\x12\x46\n\x0fgcs_destination\x18\x01 \x01(\x0b\x32-.google.cloud.vision.v1p4beta1.GcsDestination\x12\x12\n\nbatch_size\x18\x02 \x01(\x05"\x18\n\tGcsSource\x12\x0b\n\x03uri\x18\x01 \x01(\t"\x1d\n\x0eGcsDestination\x12\x0b\n\x03uri\x18\x01 \x01(\t"\x8f\x02\n\x11OperationMetadata\x12\x45\n\x05state\x18\x01 \x01(\x0e\x32\x36.google.cloud.vision.v1p4beta1.OperationMetadata.State\x12/\n\x0b\x63reate_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"Q\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0b\n\x07\x43REATED\x10\x01\x12\x0b\n\x07RUNNING\x10\x02\x12\x08\n\x04\x44ONE\x10\x03\x12\r\n\tCANCELLED\x10\x04*e\n\nLikelihood\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x11\n\rVERY_UNLIKELY\x10\x01\x12\x0c\n\x08UNLIKELY\x10\x02\x12\x0c\n\x08POSSIBLE\x10\x03\x12\n\n\x06LIKELY\x10\x04\x12\x0f\n\x0bVERY_LIKELY\x10\x05\x32\xf1\x07\n\x0eImageAnnotator\x12\xbe\x01\n\x13\x42\x61tchAnnotateImages\x12\x39.google.cloud.vision.v1p4beta1.BatchAnnotateImagesRequest\x1a:.google.cloud.vision.v1p4beta1.BatchAnnotateImagesResponse"0\x82\xd3\xe4\x93\x02\x1f"\x1a/v1p4beta1/images:annotate:\x01*\xda\x41\x08requests\x12\xba\x01\n\x12\x42\x61tchAnnotateFiles\x12\x38.google.cloud.vision.v1p4beta1.BatchAnnotateFilesRequest\x1a\x39.google.cloud.vision.v1p4beta1.BatchAnnotateFilesResponse"/\x82\xd3\xe4\x93\x02\x1e"\x19/v1p4beta1/files:annotate:\x01*\xda\x41\x08requests\x12\xfc\x01\n\x18\x41syncBatchAnnotateImages\x12>.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateImagesRequest\x1a\x1d.google.longrunning.Operation"\x80\x01\x82\xd3\xe4\x93\x02)"$/v1p4beta1/images:asyncBatchAnnotate:\x01*\xda\x41\x16requests,output_config\xca\x41\x35\n AsyncBatchAnnotateImagesResponse\x12\x11OperationMetadata\x12\xe9\x01\n\x17\x41syncBatchAnnotateFiles\x12=.google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest\x1a\x1d.google.longrunning.Operation"p\x82\xd3\xe4\x93\x02("#/v1p4beta1/files:asyncBatchAnnotate:\x01*\xda\x41\x08requests\xca\x41\x34\n\x1f\x41syncBatchAnnotateFilesResponse\x12\x11OperationMetadata\x1av\xca\x41\x15vision.googleapis.com\xd2\x41[https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-visionB\x89\x01\n!com.google.cloud.vision.v1p4beta1B\x13ImageAnnotatorProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision\xf8\x01\x01\xa2\x02\x04GCVNb\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_face__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_text__annotation__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_web__detection__pb2.DESCRIPTOR, - google_dot_longrunning_dot_operations__pb2.DESCRIPTOR, - google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_rpc_dot_status__pb2.DESCRIPTOR, - google_dot_type_dot_color__pb2.DESCRIPTOR, - google_dot_type_dot_latlng__pb2.DESCRIPTOR, - ], -) - -_LIKELIHOOD = _descriptor.EnumDescriptor( - name="Likelihood", - full_name="google.cloud.vision.v1p4beta1.Likelihood", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNKNOWN", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="VERY_UNLIKELY", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="UNLIKELY", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="POSSIBLE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LIKELY", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="VERY_LIKELY", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=8791, - serialized_end=8892, -) -_sym_db.RegisterEnumDescriptor(_LIKELIHOOD) - -Likelihood = enum_type_wrapper.EnumTypeWrapper(_LIKELIHOOD) -UNKNOWN = 0 -VERY_UNLIKELY = 1 -UNLIKELY = 2 -POSSIBLE = 3 -LIKELY = 4 -VERY_LIKELY = 5 - - -_FEATURE_TYPE = _descriptor.EnumDescriptor( - name="Type", - full_name="google.cloud.vision.v1p4beta1.Feature.Type", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="TYPE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FACE_DETECTION", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LANDMARK_DETECTION", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LOGO_DETECTION", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LABEL_DETECTION", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="TEXT_DETECTION", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DOCUMENT_TEXT_DETECTION", - index=6, - number=11, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SAFE_SEARCH_DETECTION", - index=7, - number=6, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="IMAGE_PROPERTIES", - index=8, - number=7, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CROP_HINTS", - index=9, - number=9, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="WEB_DETECTION", - index=10, - number=10, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="PRODUCT_SEARCH", - index=11, - number=12, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="OBJECT_LOCALIZATION", - index=12, - number=19, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=742, - serialized_end=1033, -) -_sym_db.RegisterEnumDescriptor(_FEATURE_TYPE) - -_FACEANNOTATION_LANDMARK_TYPE = _descriptor.EnumDescriptor( - name="Type", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.Landmark.Type", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNKNOWN_LANDMARK", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_OF_LEFT_EYEBROW", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_OF_LEFT_EYEBROW", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_OF_RIGHT_EYEBROW", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_OF_RIGHT_EYEBROW", - index=6, - number=6, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MIDPOINT_BETWEEN_EYES", - index=7, - number=7, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NOSE_TIP", - index=8, - number=8, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="UPPER_LIP", - index=9, - number=9, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LOWER_LIP", - index=10, - number=10, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MOUTH_LEFT", - index=11, - number=11, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MOUTH_RIGHT", - index=12, - number=12, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="MOUTH_CENTER", - index=13, - number=13, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NOSE_BOTTOM_RIGHT", - index=14, - number=14, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NOSE_BOTTOM_LEFT", - index=15, - number=15, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="NOSE_BOTTOM_CENTER", - index=16, - number=16, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_TOP_BOUNDARY", - index=17, - number=17, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_RIGHT_CORNER", - index=18, - number=18, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_BOTTOM_BOUNDARY", - index=19, - number=19, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_LEFT_CORNER", - index=20, - number=20, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_TOP_BOUNDARY", - index=21, - number=21, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_RIGHT_CORNER", - index=22, - number=22, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_BOTTOM_BOUNDARY", - index=23, - number=23, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_LEFT_CORNER", - index=24, - number=24, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYEBROW_UPPER_MIDPOINT", - index=25, - number=25, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYEBROW_UPPER_MIDPOINT", - index=26, - number=26, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EAR_TRAGION", - index=27, - number=27, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EAR_TRAGION", - index=28, - number=28, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LEFT_EYE_PUPIL", - index=29, - number=29, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RIGHT_EYE_PUPIL", - index=30, - number=30, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FOREHEAD_GLABELLA", - index=31, - number=31, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CHIN_GNATHION", - index=32, - number=32, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CHIN_LEFT_GONION", - index=33, - number=33, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CHIN_RIGHT_GONION", - index=34, - number=34, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=2260, - serialized_end=3080, -) -_sym_db.RegisterEnumDescriptor(_FACEANNOTATION_LANDMARK_TYPE) - -_OPERATIONMETADATA_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.vision.v1p4beta1.OperationMetadata.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CREATED", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RUNNING", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="DONE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLED", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=8708, - serialized_end=8789, -) -_sym_db.RegisterEnumDescriptor(_OPERATIONMETADATA_STATE) - - -_FEATURE = _descriptor.Descriptor( - name="Feature", - full_name="google.cloud.vision.v1p4beta1.Feature", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="type", - full_name="google.cloud.vision.v1p4beta1.Feature.type", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="max_results", - full_name="google.cloud.vision.v1p4beta1.Feature.max_results", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="model", - full_name="google.cloud.vision.v1p4beta1.Feature.model", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_FEATURE_TYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=635, - serialized_end=1033, -) - - -_IMAGESOURCE = _descriptor.Descriptor( - name="ImageSource", - full_name="google.cloud.vision.v1p4beta1.ImageSource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_image_uri", - full_name="google.cloud.vision.v1p4beta1.ImageSource.gcs_image_uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_uri", - full_name="google.cloud.vision.v1p4beta1.ImageSource.image_uri", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1035, - serialized_end=1090, -) - - -_IMAGE = _descriptor.Descriptor( - name="Image", - full_name="google.cloud.vision.v1p4beta1.Image", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="content", - full_name="google.cloud.vision.v1p4beta1.Image.content", - index=0, - number=1, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"", - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="source", - full_name="google.cloud.vision.v1p4beta1.Image.source", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1092, - serialized_end=1176, -) - - -_FACEANNOTATION_LANDMARK = _descriptor.Descriptor( - name="Landmark", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.Landmark", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="type", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.Landmark.type", - index=0, - number=3, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="position", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.Landmark.position", - index=1, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_FACEANNOTATION_LANDMARK_TYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2113, - serialized_end=3080, -) - -_FACEANNOTATION = _descriptor.Descriptor( - name="FaceAnnotation", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.bounding_poly", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="fd_bounding_poly", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.fd_bounding_poly", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="landmarks", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.landmarks", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="roll_angle", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.roll_angle", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="pan_angle", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.pan_angle", - index=4, - number=5, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="tilt_angle", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.tilt_angle", - index=5, - number=6, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="detection_confidence", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.detection_confidence", - index=6, - number=7, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="landmarking_confidence", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.landmarking_confidence", - index=7, - number=8, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="joy_likelihood", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.joy_likelihood", - index=8, - number=9, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="sorrow_likelihood", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.sorrow_likelihood", - index=9, - number=10, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="anger_likelihood", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.anger_likelihood", - index=10, - number=11, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="surprise_likelihood", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.surprise_likelihood", - index=11, - number=12, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="under_exposed_likelihood", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.under_exposed_likelihood", - index=12, - number=13, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="blurred_likelihood", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.blurred_likelihood", - index=13, - number=14, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="headwear_likelihood", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.headwear_likelihood", - index=14, - number=15, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="recognition_result", - full_name="google.cloud.vision.v1p4beta1.FaceAnnotation.recognition_result", - index=15, - number=16, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_FACEANNOTATION_LANDMARK,], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1179, - serialized_end=3080, -) - - -_LOCATIONINFO = _descriptor.Descriptor( - name="LocationInfo", - full_name="google.cloud.vision.v1p4beta1.LocationInfo", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="lat_lng", - full_name="google.cloud.vision.v1p4beta1.LocationInfo.lat_lng", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3082, - serialized_end=3134, -) - - -_PROPERTY = _descriptor.Descriptor( - name="Property", - full_name="google.cloud.vision.v1p4beta1.Property", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p4beta1.Property.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.vision.v1p4beta1.Property.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="uint64_value", - full_name="google.cloud.vision.v1p4beta1.Property.uint64_value", - index=2, - number=3, - type=4, - cpp_type=4, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3136, - serialized_end=3197, -) - - -_ENTITYANNOTATION = _descriptor.Descriptor( - name="EntityAnnotation", - full_name="google.cloud.vision.v1p4beta1.EntityAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="mid", - full_name="google.cloud.vision.v1p4beta1.EntityAnnotation.mid", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="locale", - full_name="google.cloud.vision.v1p4beta1.EntityAnnotation.locale", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.vision.v1p4beta1.EntityAnnotation.description", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p4beta1.EntityAnnotation.score", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p4beta1.EntityAnnotation.confidence", - index=4, - number=5, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\030\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="topicality", - full_name="google.cloud.vision.v1p4beta1.EntityAnnotation.topicality", - index=5, - number=6, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p4beta1.EntityAnnotation.bounding_poly", - index=6, - number=7, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="locations", - full_name="google.cloud.vision.v1p4beta1.EntityAnnotation.locations", - index=7, - number=8, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="properties", - full_name="google.cloud.vision.v1p4beta1.EntityAnnotation.properties", - index=8, - number=9, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3200, - serialized_end=3520, -) - - -_LOCALIZEDOBJECTANNOTATION = _descriptor.Descriptor( - name="LocalizedObjectAnnotation", - full_name="google.cloud.vision.v1p4beta1.LocalizedObjectAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="mid", - full_name="google.cloud.vision.v1p4beta1.LocalizedObjectAnnotation.mid", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="language_code", - full_name="google.cloud.vision.v1p4beta1.LocalizedObjectAnnotation.language_code", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p4beta1.LocalizedObjectAnnotation.name", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p4beta1.LocalizedObjectAnnotation.score", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p4beta1.LocalizedObjectAnnotation.bounding_poly", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3523, - serialized_end=3683, -) - - -_SAFESEARCHANNOTATION = _descriptor.Descriptor( - name="SafeSearchAnnotation", - full_name="google.cloud.vision.v1p4beta1.SafeSearchAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="adult", - full_name="google.cloud.vision.v1p4beta1.SafeSearchAnnotation.adult", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="spoof", - full_name="google.cloud.vision.v1p4beta1.SafeSearchAnnotation.spoof", - index=1, - number=2, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="medical", - full_name="google.cloud.vision.v1p4beta1.SafeSearchAnnotation.medical", - index=2, - number=3, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="violence", - full_name="google.cloud.vision.v1p4beta1.SafeSearchAnnotation.violence", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="racy", - full_name="google.cloud.vision.v1p4beta1.SafeSearchAnnotation.racy", - index=4, - number=9, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3686, - serialized_end=4002, -) - - -_LATLONGRECT = _descriptor.Descriptor( - name="LatLongRect", - full_name="google.cloud.vision.v1p4beta1.LatLongRect", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="min_lat_lng", - full_name="google.cloud.vision.v1p4beta1.LatLongRect.min_lat_lng", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="max_lat_lng", - full_name="google.cloud.vision.v1p4beta1.LatLongRect.max_lat_lng", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4004, - serialized_end=4101, -) - - -_COLORINFO = _descriptor.Descriptor( - name="ColorInfo", - full_name="google.cloud.vision.v1p4beta1.ColorInfo", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="color", - full_name="google.cloud.vision.v1p4beta1.ColorInfo.color", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p4beta1.ColorInfo.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="pixel_fraction", - full_name="google.cloud.vision.v1p4beta1.ColorInfo.pixel_fraction", - index=2, - number=3, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4103, - serialized_end=4188, -) - - -_DOMINANTCOLORSANNOTATION = _descriptor.Descriptor( - name="DominantColorsAnnotation", - full_name="google.cloud.vision.v1p4beta1.DominantColorsAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="colors", - full_name="google.cloud.vision.v1p4beta1.DominantColorsAnnotation.colors", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4190, - serialized_end=4274, -) - - -_IMAGEPROPERTIES = _descriptor.Descriptor( - name="ImageProperties", - full_name="google.cloud.vision.v1p4beta1.ImageProperties", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="dominant_colors", - full_name="google.cloud.vision.v1p4beta1.ImageProperties.dominant_colors", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4276, - serialized_end=4375, -) - - -_CROPHINT = _descriptor.Descriptor( - name="CropHint", - full_name="google.cloud.vision.v1p4beta1.CropHint", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p4beta1.CropHint.bounding_poly", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p4beta1.CropHint.confidence", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="importance_fraction", - full_name="google.cloud.vision.v1p4beta1.CropHint.importance_fraction", - index=2, - number=3, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4377, - serialized_end=4504, -) - - -_CROPHINTSANNOTATION = _descriptor.Descriptor( - name="CropHintsAnnotation", - full_name="google.cloud.vision.v1p4beta1.CropHintsAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="crop_hints", - full_name="google.cloud.vision.v1p4beta1.CropHintsAnnotation.crop_hints", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4506, - serialized_end=4588, -) - - -_CROPHINTSPARAMS = _descriptor.Descriptor( - name="CropHintsParams", - full_name="google.cloud.vision.v1p4beta1.CropHintsParams", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="aspect_ratios", - full_name="google.cloud.vision.v1p4beta1.CropHintsParams.aspect_ratios", - index=0, - number=1, - type=2, - cpp_type=6, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4590, - serialized_end=4630, -) - - -_WEBDETECTIONPARAMS = _descriptor.Descriptor( - name="WebDetectionParams", - full_name="google.cloud.vision.v1p4beta1.WebDetectionParams", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="include_geo_results", - full_name="google.cloud.vision.v1p4beta1.WebDetectionParams.include_geo_results", - index=0, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4632, - serialized_end=4681, -) - - -_IMAGECONTEXT = _descriptor.Descriptor( - name="ImageContext", - full_name="google.cloud.vision.v1p4beta1.ImageContext", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="lat_long_rect", - full_name="google.cloud.vision.v1p4beta1.ImageContext.lat_long_rect", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="language_hints", - full_name="google.cloud.vision.v1p4beta1.ImageContext.language_hints", - index=1, - number=2, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="crop_hints_params", - full_name="google.cloud.vision.v1p4beta1.ImageContext.crop_hints_params", - index=2, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="face_recognition_params", - full_name="google.cloud.vision.v1p4beta1.ImageContext.face_recognition_params", - index=3, - number=10, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_search_params", - full_name="google.cloud.vision.v1p4beta1.ImageContext.product_search_params", - index=4, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="web_detection_params", - full_name="google.cloud.vision.v1p4beta1.ImageContext.web_detection_params", - index=5, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4684, - serialized_end=5115, -) - - -_ANNOTATEIMAGEREQUEST = _descriptor.Descriptor( - name="AnnotateImageRequest", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="image", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageRequest.image", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="features", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageRequest.features", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_context", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageRequest.image_context", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5118, - serialized_end=5319, -) - - -_IMAGEANNOTATIONCONTEXT = _descriptor.Descriptor( - name="ImageAnnotationContext", - full_name="google.cloud.vision.v1p4beta1.ImageAnnotationContext", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="uri", - full_name="google.cloud.vision.v1p4beta1.ImageAnnotationContext.uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_number", - full_name="google.cloud.vision.v1p4beta1.ImageAnnotationContext.page_number", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5321, - serialized_end=5379, -) - - -_ANNOTATEIMAGERESPONSE = _descriptor.Descriptor( - name="AnnotateImageResponse", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="face_annotations", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageResponse.face_annotations", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="landmark_annotations", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageResponse.landmark_annotations", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="logo_annotations", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageResponse.logo_annotations", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="label_annotations", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageResponse.label_annotations", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="localized_object_annotations", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageResponse.localized_object_annotations", - index=4, - number=22, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="text_annotations", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageResponse.text_annotations", - index=5, - number=5, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="full_text_annotation", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageResponse.full_text_annotation", - index=6, - number=12, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="safe_search_annotation", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageResponse.safe_search_annotation", - index=7, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_properties_annotation", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageResponse.image_properties_annotation", - index=8, - number=8, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="crop_hints_annotation", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageResponse.crop_hints_annotation", - index=9, - number=11, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="web_detection", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageResponse.web_detection", - index=10, - number=13, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_search_results", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageResponse.product_search_results", - index=11, - number=14, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="error", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageResponse.error", - index=12, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="context", - full_name="google.cloud.vision.v1p4beta1.AnnotateImageResponse.context", - index=13, - number=21, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=5382, - serialized_end=6469, -) - - -_BATCHANNOTATEIMAGESREQUEST = _descriptor.Descriptor( - name="BatchAnnotateImagesRequest", - full_name="google.cloud.vision.v1p4beta1.BatchAnnotateImagesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="requests", - full_name="google.cloud.vision.v1p4beta1.BatchAnnotateImagesRequest.requests", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6471, - serialized_end=6575, -) - - -_BATCHANNOTATEIMAGESRESPONSE = _descriptor.Descriptor( - name="BatchAnnotateImagesResponse", - full_name="google.cloud.vision.v1p4beta1.BatchAnnotateImagesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="responses", - full_name="google.cloud.vision.v1p4beta1.BatchAnnotateImagesResponse.responses", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6577, - serialized_end=6679, -) - - -_ANNOTATEFILEREQUEST = _descriptor.Descriptor( - name="AnnotateFileRequest", - full_name="google.cloud.vision.v1p4beta1.AnnotateFileRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="input_config", - full_name="google.cloud.vision.v1p4beta1.AnnotateFileRequest.input_config", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="features", - full_name="google.cloud.vision.v1p4beta1.AnnotateFileRequest.features", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_context", - full_name="google.cloud.vision.v1p4beta1.AnnotateFileRequest.image_context", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="pages", - full_name="google.cloud.vision.v1p4beta1.AnnotateFileRequest.pages", - index=3, - number=4, - type=5, - cpp_type=1, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6682, - serialized_end=6910, -) - - -_ANNOTATEFILERESPONSE = _descriptor.Descriptor( - name="AnnotateFileResponse", - full_name="google.cloud.vision.v1p4beta1.AnnotateFileResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="input_config", - full_name="google.cloud.vision.v1p4beta1.AnnotateFileResponse.input_config", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="responses", - full_name="google.cloud.vision.v1p4beta1.AnnotateFileResponse.responses", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="total_pages", - full_name="google.cloud.vision.v1p4beta1.AnnotateFileResponse.total_pages", - index=2, - number=3, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="error", - full_name="google.cloud.vision.v1p4beta1.AnnotateFileResponse.error", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=6913, - serialized_end=7130, -) - - -_BATCHANNOTATEFILESREQUEST = _descriptor.Descriptor( - name="BatchAnnotateFilesRequest", - full_name="google.cloud.vision.v1p4beta1.BatchAnnotateFilesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="requests", - full_name="google.cloud.vision.v1p4beta1.BatchAnnotateFilesRequest.requests", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=7132, - serialized_end=7234, -) - - -_BATCHANNOTATEFILESRESPONSE = _descriptor.Descriptor( - name="BatchAnnotateFilesResponse", - full_name="google.cloud.vision.v1p4beta1.BatchAnnotateFilesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="responses", - full_name="google.cloud.vision.v1p4beta1.BatchAnnotateFilesResponse.responses", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=7236, - serialized_end=7336, -) - - -_ASYNCANNOTATEFILEREQUEST = _descriptor.Descriptor( - name="AsyncAnnotateFileRequest", - full_name="google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="input_config", - full_name="google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest.input_config", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="features", - full_name="google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest.features", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image_context", - full_name="google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest.image_context", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="output_config", - full_name="google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest.output_config", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=7339, - serialized_end=7625, -) - - -_ASYNCANNOTATEFILERESPONSE = _descriptor.Descriptor( - name="AsyncAnnotateFileResponse", - full_name="google.cloud.vision.v1p4beta1.AsyncAnnotateFileResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="output_config", - full_name="google.cloud.vision.v1p4beta1.AsyncAnnotateFileResponse.output_config", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=7627, - serialized_end=7722, -) - - -_ASYNCBATCHANNOTATEIMAGESREQUEST = _descriptor.Descriptor( - name="AsyncBatchAnnotateImagesRequest", - full_name="google.cloud.vision.v1p4beta1.AsyncBatchAnnotateImagesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="requests", - full_name="google.cloud.vision.v1p4beta1.AsyncBatchAnnotateImagesRequest.requests", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="output_config", - full_name="google.cloud.vision.v1p4beta1.AsyncBatchAnnotateImagesRequest.output_config", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=7725, - serialized_end=7907, -) - - -_ASYNCBATCHANNOTATEIMAGESRESPONSE = _descriptor.Descriptor( - name="AsyncBatchAnnotateImagesResponse", - full_name="google.cloud.vision.v1p4beta1.AsyncBatchAnnotateImagesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="output_config", - full_name="google.cloud.vision.v1p4beta1.AsyncBatchAnnotateImagesResponse.output_config", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=7909, - serialized_end=8011, -) - - -_ASYNCBATCHANNOTATEFILESREQUEST = _descriptor.Descriptor( - name="AsyncBatchAnnotateFilesRequest", - full_name="google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="requests", - full_name="google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest.requests", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=8013, - serialized_end=8125, -) - - -_ASYNCBATCHANNOTATEFILESRESPONSE = _descriptor.Descriptor( - name="AsyncBatchAnnotateFilesResponse", - full_name="google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="responses", - full_name="google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesResponse.responses", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=8127, - serialized_end=8237, -) - - -_INPUTCONFIG = _descriptor.Descriptor( - name="InputConfig", - full_name="google.cloud.vision.v1p4beta1.InputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_source", - full_name="google.cloud.vision.v1p4beta1.InputConfig.gcs_source", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="content", - full_name="google.cloud.vision.v1p4beta1.InputConfig.content", - index=1, - number=3, - type=12, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"", - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="mime_type", - full_name="google.cloud.vision.v1p4beta1.InputConfig.mime_type", - index=2, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=8239, - serialized_end=8350, -) - - -_OUTPUTCONFIG = _descriptor.Descriptor( - name="OutputConfig", - full_name="google.cloud.vision.v1p4beta1.OutputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_destination", - full_name="google.cloud.vision.v1p4beta1.OutputConfig.gcs_destination", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="batch_size", - full_name="google.cloud.vision.v1p4beta1.OutputConfig.batch_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=8352, - serialized_end=8458, -) - - -_GCSSOURCE = _descriptor.Descriptor( - name="GcsSource", - full_name="google.cloud.vision.v1p4beta1.GcsSource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="uri", - full_name="google.cloud.vision.v1p4beta1.GcsSource.uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=8460, - serialized_end=8484, -) - - -_GCSDESTINATION = _descriptor.Descriptor( - name="GcsDestination", - full_name="google.cloud.vision.v1p4beta1.GcsDestination", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="uri", - full_name="google.cloud.vision.v1p4beta1.GcsDestination.uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=8486, - serialized_end=8515, -) - - -_OPERATIONMETADATA = _descriptor.Descriptor( - name="OperationMetadata", - full_name="google.cloud.vision.v1p4beta1.OperationMetadata", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.vision.v1p4beta1.OperationMetadata.state", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="create_time", - full_name="google.cloud.vision.v1p4beta1.OperationMetadata.create_time", - index=1, - number=5, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_time", - full_name="google.cloud.vision.v1p4beta1.OperationMetadata.update_time", - index=2, - number=6, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_OPERATIONMETADATA_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=8518, - serialized_end=8789, -) - -_FEATURE.fields_by_name["type"].enum_type = _FEATURE_TYPE -_FEATURE_TYPE.containing_type = _FEATURE -_IMAGE.fields_by_name["source"].message_type = _IMAGESOURCE -_FACEANNOTATION_LANDMARK.fields_by_name[ - "type" -].enum_type = _FACEANNOTATION_LANDMARK_TYPE -_FACEANNOTATION_LANDMARK.fields_by_name[ - "position" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2._POSITION -) -_FACEANNOTATION_LANDMARK.containing_type = _FACEANNOTATION -_FACEANNOTATION_LANDMARK_TYPE.containing_type = _FACEANNOTATION_LANDMARK -_FACEANNOTATION.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_FACEANNOTATION.fields_by_name[ - "fd_bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_FACEANNOTATION.fields_by_name["landmarks"].message_type = _FACEANNOTATION_LANDMARK -_FACEANNOTATION.fields_by_name["joy_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["sorrow_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["anger_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["surprise_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["under_exposed_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["blurred_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name["headwear_likelihood"].enum_type = _LIKELIHOOD -_FACEANNOTATION.fields_by_name[ - "recognition_result" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_face__pb2._FACERECOGNITIONRESULT -) -_LOCATIONINFO.fields_by_name[ - "lat_lng" -].message_type = google_dot_type_dot_latlng__pb2._LATLNG -_ENTITYANNOTATION.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_ENTITYANNOTATION.fields_by_name["locations"].message_type = _LOCATIONINFO -_ENTITYANNOTATION.fields_by_name["properties"].message_type = _PROPERTY -_LOCALIZEDOBJECTANNOTATION.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_SAFESEARCHANNOTATION.fields_by_name["adult"].enum_type = _LIKELIHOOD -_SAFESEARCHANNOTATION.fields_by_name["spoof"].enum_type = _LIKELIHOOD -_SAFESEARCHANNOTATION.fields_by_name["medical"].enum_type = _LIKELIHOOD -_SAFESEARCHANNOTATION.fields_by_name["violence"].enum_type = _LIKELIHOOD -_SAFESEARCHANNOTATION.fields_by_name["racy"].enum_type = _LIKELIHOOD -_LATLONGRECT.fields_by_name[ - "min_lat_lng" -].message_type = google_dot_type_dot_latlng__pb2._LATLNG -_LATLONGRECT.fields_by_name[ - "max_lat_lng" -].message_type = google_dot_type_dot_latlng__pb2._LATLNG -_COLORINFO.fields_by_name["color"].message_type = google_dot_type_dot_color__pb2._COLOR -_DOMINANTCOLORSANNOTATION.fields_by_name["colors"].message_type = _COLORINFO -_IMAGEPROPERTIES.fields_by_name[ - "dominant_colors" -].message_type = _DOMINANTCOLORSANNOTATION -_CROPHINT.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_CROPHINTSANNOTATION.fields_by_name["crop_hints"].message_type = _CROPHINT -_IMAGECONTEXT.fields_by_name["lat_long_rect"].message_type = _LATLONGRECT -_IMAGECONTEXT.fields_by_name["crop_hints_params"].message_type = _CROPHINTSPARAMS -_IMAGECONTEXT.fields_by_name[ - "face_recognition_params" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_face__pb2._FACERECOGNITIONPARAMS -) -_IMAGECONTEXT.fields_by_name[ - "product_search_params" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__pb2._PRODUCTSEARCHPARAMS -) -_IMAGECONTEXT.fields_by_name["web_detection_params"].message_type = _WEBDETECTIONPARAMS -_ANNOTATEIMAGEREQUEST.fields_by_name["image"].message_type = _IMAGE -_ANNOTATEIMAGEREQUEST.fields_by_name["features"].message_type = _FEATURE -_ANNOTATEIMAGEREQUEST.fields_by_name["image_context"].message_type = _IMAGECONTEXT -_ANNOTATEIMAGERESPONSE.fields_by_name["face_annotations"].message_type = _FACEANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "landmark_annotations" -].message_type = _ENTITYANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "logo_annotations" -].message_type = _ENTITYANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "label_annotations" -].message_type = _ENTITYANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "localized_object_annotations" -].message_type = _LOCALIZEDOBJECTANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "text_annotations" -].message_type = _ENTITYANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "full_text_annotation" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_text__annotation__pb2._TEXTANNOTATION -) -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "safe_search_annotation" -].message_type = _SAFESEARCHANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "image_properties_annotation" -].message_type = _IMAGEPROPERTIES -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "crop_hints_annotation" -].message_type = _CROPHINTSANNOTATION -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "web_detection" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_web__detection__pb2._WEBDETECTION -) -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "product_search_results" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__pb2._PRODUCTSEARCHRESULTS -) -_ANNOTATEIMAGERESPONSE.fields_by_name[ - "error" -].message_type = google_dot_rpc_dot_status__pb2._STATUS -_ANNOTATEIMAGERESPONSE.fields_by_name["context"].message_type = _IMAGEANNOTATIONCONTEXT -_BATCHANNOTATEIMAGESREQUEST.fields_by_name[ - "requests" -].message_type = _ANNOTATEIMAGEREQUEST -_BATCHANNOTATEIMAGESRESPONSE.fields_by_name[ - "responses" -].message_type = _ANNOTATEIMAGERESPONSE -_ANNOTATEFILEREQUEST.fields_by_name["input_config"].message_type = _INPUTCONFIG -_ANNOTATEFILEREQUEST.fields_by_name["features"].message_type = _FEATURE -_ANNOTATEFILEREQUEST.fields_by_name["image_context"].message_type = _IMAGECONTEXT -_ANNOTATEFILERESPONSE.fields_by_name["input_config"].message_type = _INPUTCONFIG -_ANNOTATEFILERESPONSE.fields_by_name["responses"].message_type = _ANNOTATEIMAGERESPONSE -_ANNOTATEFILERESPONSE.fields_by_name[ - "error" -].message_type = google_dot_rpc_dot_status__pb2._STATUS -_BATCHANNOTATEFILESREQUEST.fields_by_name[ - "requests" -].message_type = _ANNOTATEFILEREQUEST -_BATCHANNOTATEFILESRESPONSE.fields_by_name[ - "responses" -].message_type = _ANNOTATEFILERESPONSE -_ASYNCANNOTATEFILEREQUEST.fields_by_name["input_config"].message_type = _INPUTCONFIG -_ASYNCANNOTATEFILEREQUEST.fields_by_name["features"].message_type = _FEATURE -_ASYNCANNOTATEFILEREQUEST.fields_by_name["image_context"].message_type = _IMAGECONTEXT -_ASYNCANNOTATEFILEREQUEST.fields_by_name["output_config"].message_type = _OUTPUTCONFIG -_ASYNCANNOTATEFILERESPONSE.fields_by_name["output_config"].message_type = _OUTPUTCONFIG -_ASYNCBATCHANNOTATEIMAGESREQUEST.fields_by_name[ - "requests" -].message_type = _ANNOTATEIMAGEREQUEST -_ASYNCBATCHANNOTATEIMAGESREQUEST.fields_by_name[ - "output_config" -].message_type = _OUTPUTCONFIG -_ASYNCBATCHANNOTATEIMAGESRESPONSE.fields_by_name[ - "output_config" -].message_type = _OUTPUTCONFIG -_ASYNCBATCHANNOTATEFILESREQUEST.fields_by_name[ - "requests" -].message_type = _ASYNCANNOTATEFILEREQUEST -_ASYNCBATCHANNOTATEFILESRESPONSE.fields_by_name[ - "responses" -].message_type = _ASYNCANNOTATEFILERESPONSE -_INPUTCONFIG.fields_by_name["gcs_source"].message_type = _GCSSOURCE -_OUTPUTCONFIG.fields_by_name["gcs_destination"].message_type = _GCSDESTINATION -_OPERATIONMETADATA.fields_by_name["state"].enum_type = _OPERATIONMETADATA_STATE -_OPERATIONMETADATA.fields_by_name[ - "create_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_OPERATIONMETADATA.fields_by_name[ - "update_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_OPERATIONMETADATA_STATE.containing_type = _OPERATIONMETADATA -DESCRIPTOR.message_types_by_name["Feature"] = _FEATURE -DESCRIPTOR.message_types_by_name["ImageSource"] = _IMAGESOURCE -DESCRIPTOR.message_types_by_name["Image"] = _IMAGE -DESCRIPTOR.message_types_by_name["FaceAnnotation"] = _FACEANNOTATION -DESCRIPTOR.message_types_by_name["LocationInfo"] = _LOCATIONINFO -DESCRIPTOR.message_types_by_name["Property"] = _PROPERTY -DESCRIPTOR.message_types_by_name["EntityAnnotation"] = _ENTITYANNOTATION -DESCRIPTOR.message_types_by_name[ - "LocalizedObjectAnnotation" -] = _LOCALIZEDOBJECTANNOTATION -DESCRIPTOR.message_types_by_name["SafeSearchAnnotation"] = _SAFESEARCHANNOTATION -DESCRIPTOR.message_types_by_name["LatLongRect"] = _LATLONGRECT -DESCRIPTOR.message_types_by_name["ColorInfo"] = _COLORINFO -DESCRIPTOR.message_types_by_name["DominantColorsAnnotation"] = _DOMINANTCOLORSANNOTATION -DESCRIPTOR.message_types_by_name["ImageProperties"] = _IMAGEPROPERTIES -DESCRIPTOR.message_types_by_name["CropHint"] = _CROPHINT -DESCRIPTOR.message_types_by_name["CropHintsAnnotation"] = _CROPHINTSANNOTATION -DESCRIPTOR.message_types_by_name["CropHintsParams"] = _CROPHINTSPARAMS -DESCRIPTOR.message_types_by_name["WebDetectionParams"] = _WEBDETECTIONPARAMS -DESCRIPTOR.message_types_by_name["ImageContext"] = _IMAGECONTEXT -DESCRIPTOR.message_types_by_name["AnnotateImageRequest"] = _ANNOTATEIMAGEREQUEST -DESCRIPTOR.message_types_by_name["ImageAnnotationContext"] = _IMAGEANNOTATIONCONTEXT -DESCRIPTOR.message_types_by_name["AnnotateImageResponse"] = _ANNOTATEIMAGERESPONSE -DESCRIPTOR.message_types_by_name[ - "BatchAnnotateImagesRequest" -] = _BATCHANNOTATEIMAGESREQUEST -DESCRIPTOR.message_types_by_name[ - "BatchAnnotateImagesResponse" -] = _BATCHANNOTATEIMAGESRESPONSE -DESCRIPTOR.message_types_by_name["AnnotateFileRequest"] = _ANNOTATEFILEREQUEST -DESCRIPTOR.message_types_by_name["AnnotateFileResponse"] = _ANNOTATEFILERESPONSE -DESCRIPTOR.message_types_by_name[ - "BatchAnnotateFilesRequest" -] = _BATCHANNOTATEFILESREQUEST -DESCRIPTOR.message_types_by_name[ - "BatchAnnotateFilesResponse" -] = _BATCHANNOTATEFILESRESPONSE -DESCRIPTOR.message_types_by_name["AsyncAnnotateFileRequest"] = _ASYNCANNOTATEFILEREQUEST -DESCRIPTOR.message_types_by_name[ - "AsyncAnnotateFileResponse" -] = _ASYNCANNOTATEFILERESPONSE -DESCRIPTOR.message_types_by_name[ - "AsyncBatchAnnotateImagesRequest" -] = _ASYNCBATCHANNOTATEIMAGESREQUEST -DESCRIPTOR.message_types_by_name[ - "AsyncBatchAnnotateImagesResponse" -] = _ASYNCBATCHANNOTATEIMAGESRESPONSE -DESCRIPTOR.message_types_by_name[ - "AsyncBatchAnnotateFilesRequest" -] = _ASYNCBATCHANNOTATEFILESREQUEST -DESCRIPTOR.message_types_by_name[ - "AsyncBatchAnnotateFilesResponse" -] = _ASYNCBATCHANNOTATEFILESRESPONSE -DESCRIPTOR.message_types_by_name["InputConfig"] = _INPUTCONFIG -DESCRIPTOR.message_types_by_name["OutputConfig"] = _OUTPUTCONFIG -DESCRIPTOR.message_types_by_name["GcsSource"] = _GCSSOURCE -DESCRIPTOR.message_types_by_name["GcsDestination"] = _GCSDESTINATION -DESCRIPTOR.message_types_by_name["OperationMetadata"] = _OPERATIONMETADATA -DESCRIPTOR.enum_types_by_name["Likelihood"] = _LIKELIHOOD -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Feature = _reflection.GeneratedProtocolMessageType( - "Feature", - (_message.Message,), - { - "DESCRIPTOR": _FEATURE, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """The type of Google Cloud Vision API detection to perform, and the - maximum number of results to return for that type. Multiple - ``Feature`` objects can be specified in the ``features`` list. - - Attributes: - type: - The feature type. - max_results: - Maximum number of results of this type. Does not apply to - ``TEXT_DETECTION``, ``DOCUMENT_TEXT_DETECTION``, or - ``CROP_HINTS``. - model: - Model to use for the feature. Supported values: - “builtin/stable” (the default if unset) and “builtin/latest”. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.Feature) - }, -) -_sym_db.RegisterMessage(Feature) - -ImageSource = _reflection.GeneratedProtocolMessageType( - "ImageSource", - (_message.Message,), - { - "DESCRIPTOR": _IMAGESOURCE, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """External image source (Google Cloud Storage or web URL image - location). - - Attributes: - gcs_image_uri: - \ **Use ``image_uri`` instead.** The Google Cloud Storage URI - of the form ``gs://bucket_name/object_name``. Object - versioning is not supported. See `Google Cloud Storage Request - URIs `__ - for more info. - image_uri: - The URI of the source image. Can be either: 1. A Google Cloud - Storage URI of the form ``gs://bucket_name/object_name``. - Object versioning is not supported. See `Google Cloud - Storage Request URIs - `__ for - more info. 2. A publicly-accessible image HTTP/HTTPS URL. - When fetching images from HTTP/HTTPS URLs, Google cannot - guarantee that the request will be completed. Your request - may fail if the specified host denies the request (e.g. due - to request throttling or DOS prevention), or if Google - throttles requests to the site for abuse prevention. You - should not depend on externally-hosted images for production - applications. When both ``gcs_image_uri`` and ``image_uri`` - are specified, ``image_uri`` takes precedence. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ImageSource) - }, -) -_sym_db.RegisterMessage(ImageSource) - -Image = _reflection.GeneratedProtocolMessageType( - "Image", - (_message.Message,), - { - "DESCRIPTOR": _IMAGE, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Client image to perform Google Cloud Vision API tasks over. - - Attributes: - content: - Image content, represented as a stream of bytes. Note: As with - all ``bytes`` fields, protobuffers use a pure binary - representation, whereas JSON representations use base64. - source: - Google Cloud Storage image location, or publicly-accessible - image URL. If both ``content`` and ``source`` are provided for - an image, ``content`` takes precedence and is used to perform - the image annotation request. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.Image) - }, -) -_sym_db.RegisterMessage(Image) - -FaceAnnotation = _reflection.GeneratedProtocolMessageType( - "FaceAnnotation", - (_message.Message,), - { - "Landmark": _reflection.GeneratedProtocolMessageType( - "Landmark", - (_message.Message,), - { - "DESCRIPTOR": _FACEANNOTATION_LANDMARK, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """A face-specific landmark (for example, a face feature). - - Attributes: - type: - Face landmark type. - position: - Face landmark position. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.FaceAnnotation.Landmark) - }, - ), - "DESCRIPTOR": _FACEANNOTATION, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """A face annotation object contains the results of face detection. - - Attributes: - bounding_poly: - The bounding polygon around the face. The coordinates of the - bounding box are in the original image’s scale. The bounding - box is computed to “frame” the face in accordance with human - expectations. It is based on the landmarker results. Note that - one or more x and/or y coordinates may not be generated in the - ``BoundingPoly`` (the polygon will be unbounded) if only a - partial face appears in the image to be annotated. - fd_bounding_poly: - The ``fd_bounding_poly`` bounding polygon is tighter than the - ``boundingPoly``, and encloses only the skin part of the face. - Typically, it is used to eliminate the face from any image - analysis that detects the “amount of skin” visible in an - image. It is not based on the landmarker results, only on the - initial face detection, hence the fd (face detection) prefix. - landmarks: - Detected face landmarks. - roll_angle: - Roll angle, which indicates the amount of clockwise/anti- - clockwise rotation of the face relative to the image vertical - about the axis perpendicular to the face. Range [-180,180]. - pan_angle: - Yaw angle, which indicates the leftward/rightward angle that - the face is pointing relative to the vertical plane - perpendicular to the image. Range [-180,180]. - tilt_angle: - Pitch angle, which indicates the upwards/downwards angle that - the face is pointing relative to the image’s horizontal plane. - Range [-180,180]. - detection_confidence: - Detection confidence. Range [0, 1]. - landmarking_confidence: - Face landmarking confidence. Range [0, 1]. - joy_likelihood: - Joy likelihood. - sorrow_likelihood: - Sorrow likelihood. - anger_likelihood: - Anger likelihood. - surprise_likelihood: - Surprise likelihood. - under_exposed_likelihood: - Under-exposed likelihood. - blurred_likelihood: - Blurred likelihood. - headwear_likelihood: - Headwear likelihood. - recognition_result: - Additional recognition information. Only computed if - image_context.face_recognition_params is provided, **and** a - match is found to a - [Celebrity][google.cloud.vision.v1p4beta1.Celebrity] in the - input - [CelebritySet][google.cloud.vision.v1p4beta1.CelebritySet]. - This field is sorted in order of decreasing confidence values. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.FaceAnnotation) - }, -) -_sym_db.RegisterMessage(FaceAnnotation) -_sym_db.RegisterMessage(FaceAnnotation.Landmark) - -LocationInfo = _reflection.GeneratedProtocolMessageType( - "LocationInfo", - (_message.Message,), - { - "DESCRIPTOR": _LOCATIONINFO, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Detected entity location information. - - Attributes: - lat_lng: - lat/long location coordinates. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.LocationInfo) - }, -) -_sym_db.RegisterMessage(LocationInfo) - -Property = _reflection.GeneratedProtocolMessageType( - "Property", - (_message.Message,), - { - "DESCRIPTOR": _PROPERTY, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """A ``Property`` consists of a user-supplied name/value pair. - - Attributes: - name: - Name of the property. - value: - Value of the property. - uint64_value: - Value of numeric properties. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.Property) - }, -) -_sym_db.RegisterMessage(Property) - -EntityAnnotation = _reflection.GeneratedProtocolMessageType( - "EntityAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _ENTITYANNOTATION, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Set of detected entity features. - - Attributes: - mid: - Opaque entity ID. Some IDs may be available in `Google - Knowledge Graph Search API - `__. - locale: - The language code for the locale in which the entity textual - ``description`` is expressed. - description: - Entity textual description, expressed in its ``locale`` - language. - score: - Overall score of the result. Range [0, 1]. - confidence: - \ **Deprecated. Use ``score`` instead.** The accuracy of the - entity detection in an image. For example, for an image in - which the “Eiffel Tower” entity is detected, this field - represents the confidence that there is a tower in the query - image. Range [0, 1]. - topicality: - The relevancy of the ICA (Image Content Annotation) label to - the image. For example, the relevancy of “tower” is likely - higher to an image containing the detected “Eiffel Tower” than - to an image containing a detected distant towering building, - even though the confidence that there is a tower in each image - may be the same. Range [0, 1]. - bounding_poly: - Image region to which this entity belongs. Not produced for - ``LABEL_DETECTION`` features. - locations: - The location information for the detected entity. Multiple - ``LocationInfo`` elements can be present because one location - may indicate the location of the scene in the image, and - another location may indicate the location of the place where - the image was taken. Location information is usually present - for landmarks. - properties: - Some entities may have optional user-supplied ``Property`` - (name/value) fields, such a score or string that qualifies the - entity. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.EntityAnnotation) - }, -) -_sym_db.RegisterMessage(EntityAnnotation) - -LocalizedObjectAnnotation = _reflection.GeneratedProtocolMessageType( - "LocalizedObjectAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _LOCALIZEDOBJECTANNOTATION, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Set of detected objects with bounding boxes. - - Attributes: - mid: - Object ID that should align with EntityAnnotation mid. - language_code: - The BCP-47 language code, such as “en-US” or “sr-Latn”. For - more information, see http://www.unicode.org/reports/tr35/#Uni - code_locale_identifier. - name: - Object name, expressed in its ``language_code`` language. - score: - Score of the result. Range [0, 1]. - bounding_poly: - Image region to which this object belongs. This must be - populated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.LocalizedObjectAnnotation) - }, -) -_sym_db.RegisterMessage(LocalizedObjectAnnotation) - -SafeSearchAnnotation = _reflection.GeneratedProtocolMessageType( - "SafeSearchAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _SAFESEARCHANNOTATION, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Set of features pertaining to the image, computed by computer vision - methods over safe-search verticals (for example, adult, spoof, - medical, violence). - - Attributes: - adult: - Represents the adult content likelihood for the image. Adult - content may contain elements such as nudity, pornographic - images or cartoons, or sexual activities. - spoof: - Spoof likelihood. The likelihood that an modification was made - to the image’s canonical version to make it appear funny or - offensive. - medical: - Likelihood that this is a medical image. - violence: - Likelihood that this image contains violent content. - racy: - Likelihood that the request image contains racy content. Racy - content may include (but is not limited to) skimpy or sheer - clothing, strategically covered nudity, lewd or provocative - poses, or close-ups of sensitive body areas. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.SafeSearchAnnotation) - }, -) -_sym_db.RegisterMessage(SafeSearchAnnotation) - -LatLongRect = _reflection.GeneratedProtocolMessageType( - "LatLongRect", - (_message.Message,), - { - "DESCRIPTOR": _LATLONGRECT, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Rectangle determined by min and max ``LatLng`` pairs. - - Attributes: - min_lat_lng: - Min lat/long pair. - max_lat_lng: - Max lat/long pair. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.LatLongRect) - }, -) -_sym_db.RegisterMessage(LatLongRect) - -ColorInfo = _reflection.GeneratedProtocolMessageType( - "ColorInfo", - (_message.Message,), - { - "DESCRIPTOR": _COLORINFO, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Color information consists of RGB channels, score, and the fraction of - the image that the color occupies in the image. - - Attributes: - color: - RGB components of the color. - score: - Image-specific score for this color. Value in range [0, 1]. - pixel_fraction: - The fraction of pixels the color occupies in the image. Value - in range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ColorInfo) - }, -) -_sym_db.RegisterMessage(ColorInfo) - -DominantColorsAnnotation = _reflection.GeneratedProtocolMessageType( - "DominantColorsAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _DOMINANTCOLORSANNOTATION, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Set of dominant colors and their corresponding scores. - - Attributes: - colors: - RGB color values with their score and pixel fraction. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.DominantColorsAnnotation) - }, -) -_sym_db.RegisterMessage(DominantColorsAnnotation) - -ImageProperties = _reflection.GeneratedProtocolMessageType( - "ImageProperties", - (_message.Message,), - { - "DESCRIPTOR": _IMAGEPROPERTIES, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Stores image properties, such as dominant colors. - - Attributes: - dominant_colors: - If present, dominant colors completed successfully. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ImageProperties) - }, -) -_sym_db.RegisterMessage(ImageProperties) - -CropHint = _reflection.GeneratedProtocolMessageType( - "CropHint", - (_message.Message,), - { - "DESCRIPTOR": _CROPHINT, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Single crop hint that is used to generate a new crop when serving an - image. - - Attributes: - bounding_poly: - The bounding polygon for the crop region. The coordinates of - the bounding box are in the original image’s scale. - confidence: - Confidence of this being a salient region. Range [0, 1]. - importance_fraction: - Fraction of importance of this salient region with respect to - the original image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.CropHint) - }, -) -_sym_db.RegisterMessage(CropHint) - -CropHintsAnnotation = _reflection.GeneratedProtocolMessageType( - "CropHintsAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _CROPHINTSANNOTATION, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Set of crop hints that are used to generate new crops when serving - images. - - Attributes: - crop_hints: - Crop hint results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.CropHintsAnnotation) - }, -) -_sym_db.RegisterMessage(CropHintsAnnotation) - -CropHintsParams = _reflection.GeneratedProtocolMessageType( - "CropHintsParams", - (_message.Message,), - { - "DESCRIPTOR": _CROPHINTSPARAMS, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Parameters for crop hints annotation request. - - Attributes: - aspect_ratios: - Aspect ratios in floats, representing the ratio of the width - to the height of the image. For example, if the desired aspect - ratio is 4/3, the corresponding float value should be 1.33333. - If not specified, the best possible crop is returned. The - number of provided aspect ratios is limited to a maximum of - 16; any aspect ratios provided after the 16th are ignored. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.CropHintsParams) - }, -) -_sym_db.RegisterMessage(CropHintsParams) - -WebDetectionParams = _reflection.GeneratedProtocolMessageType( - "WebDetectionParams", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTIONPARAMS, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Parameters for web detection request. - - Attributes: - include_geo_results: - Whether to include results derived from the geo information in - the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.WebDetectionParams) - }, -) -_sym_db.RegisterMessage(WebDetectionParams) - -ImageContext = _reflection.GeneratedProtocolMessageType( - "ImageContext", - (_message.Message,), - { - "DESCRIPTOR": _IMAGECONTEXT, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Image context and/or feature-specific parameters. - - Attributes: - lat_long_rect: - Not used. - language_hints: - List of languages to use for TEXT_DETECTION. In most cases, an - empty value yields the best results since it enables automatic - language detection. For languages based on the Latin alphabet, - setting ``language_hints`` is not needed. In rare cases, when - the language of the text in the image is known, setting a hint - will help get better results (although it will be a - significant hindrance if the hint is wrong). Text detection - returns an error if one or more of the specified languages is - not one of the `supported languages - `__. - crop_hints_params: - Parameters for crop hints annotation request. - face_recognition_params: - Parameters for face recognition. - product_search_params: - Parameters for product search. - web_detection_params: - Parameters for web detection. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ImageContext) - }, -) -_sym_db.RegisterMessage(ImageContext) - -AnnotateImageRequest = _reflection.GeneratedProtocolMessageType( - "AnnotateImageRequest", - (_message.Message,), - { - "DESCRIPTOR": _ANNOTATEIMAGEREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Request for performing Google Cloud Vision API tasks over a user- - provided image, with user-requested features, and with context - information. - - Attributes: - image: - The image to be processed. - features: - Requested features. - image_context: - Additional context that may accompany the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.AnnotateImageRequest) - }, -) -_sym_db.RegisterMessage(AnnotateImageRequest) - -ImageAnnotationContext = _reflection.GeneratedProtocolMessageType( - "ImageAnnotationContext", - (_message.Message,), - { - "DESCRIPTOR": _IMAGEANNOTATIONCONTEXT, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """If an image was produced from a file (e.g. a PDF), this message gives - information about the source of that image. - - Attributes: - uri: - The URI of the file used to produce the image. - page_number: - If the file was a PDF or TIFF, this field gives the page - number within the file used to produce the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ImageAnnotationContext) - }, -) -_sym_db.RegisterMessage(ImageAnnotationContext) - -AnnotateImageResponse = _reflection.GeneratedProtocolMessageType( - "AnnotateImageResponse", - (_message.Message,), - { - "DESCRIPTOR": _ANNOTATEIMAGERESPONSE, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Response to an image annotation request. - - Attributes: - face_annotations: - If present, face detection has completed successfully. - landmark_annotations: - If present, landmark detection has completed successfully. - logo_annotations: - If present, logo detection has completed successfully. - label_annotations: - If present, label detection has completed successfully. - localized_object_annotations: - If present, localized object detection has completed - successfully. This will be sorted descending by confidence - score. - text_annotations: - If present, text (OCR) detection has completed successfully. - full_text_annotation: - If present, text (OCR) detection or document (OCR) text - detection has completed successfully. This annotation provides - the structural hierarchy for the OCR detected text. - safe_search_annotation: - If present, safe-search annotation has completed successfully. - image_properties_annotation: - If present, image properties were extracted successfully. - crop_hints_annotation: - If present, crop hints have completed successfully. - web_detection: - If present, web detection has completed successfully. - product_search_results: - If present, product search has completed successfully. - error: - If set, represents the error message for the operation. Note - that filled-in image annotations are guaranteed to be correct, - even when ``error`` is set. - context: - If present, contextual information is needed to understand - where this image comes from. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.AnnotateImageResponse) - }, -) -_sym_db.RegisterMessage(AnnotateImageResponse) - -BatchAnnotateImagesRequest = _reflection.GeneratedProtocolMessageType( - "BatchAnnotateImagesRequest", - (_message.Message,), - { - "DESCRIPTOR": _BATCHANNOTATEIMAGESREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Multiple image annotation requests are batched into a single service - call. - - Attributes: - requests: - Required. Individual image annotation requests for this batch. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.BatchAnnotateImagesRequest) - }, -) -_sym_db.RegisterMessage(BatchAnnotateImagesRequest) - -BatchAnnotateImagesResponse = _reflection.GeneratedProtocolMessageType( - "BatchAnnotateImagesResponse", - (_message.Message,), - { - "DESCRIPTOR": _BATCHANNOTATEIMAGESRESPONSE, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Response to a batch image annotation request. - - Attributes: - responses: - Individual responses to image annotation requests within the - batch. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.BatchAnnotateImagesResponse) - }, -) -_sym_db.RegisterMessage(BatchAnnotateImagesResponse) - -AnnotateFileRequest = _reflection.GeneratedProtocolMessageType( - "AnnotateFileRequest", - (_message.Message,), - { - "DESCRIPTOR": _ANNOTATEFILEREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """A request to annotate one single file, e.g. a PDF, TIFF or GIF file. - - Attributes: - input_config: - Required. Information about the input file. - features: - Required. Requested features. - image_context: - Additional context that may accompany the image(s) in the - file. - pages: - Pages of the file to perform image annotation. Pages starts - from 1, we assume the first page of the file is page 1. At - most 5 pages are supported per request. Pages can be negative. - Page 1 means the first page. Page 2 means the second page. - Page -1 means the last page. Page -2 means the second to the - last page. If the file is GIF instead of PDF or TIFF, page - refers to GIF frames. If this field is empty, by default the - service performs image annotation for the first 5 pages of the - file. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.AnnotateFileRequest) - }, -) -_sym_db.RegisterMessage(AnnotateFileRequest) - -AnnotateFileResponse = _reflection.GeneratedProtocolMessageType( - "AnnotateFileResponse", - (_message.Message,), - { - "DESCRIPTOR": _ANNOTATEFILERESPONSE, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Response to a single file annotation request. A file may contain one - or more images, which individually have their own responses. - - Attributes: - input_config: - Information about the file for which this response is - generated. - responses: - Individual responses to images found within the file. This - field will be empty if the ``error`` field is set. - total_pages: - This field gives the total number of pages in the file. - error: - If set, represents the error message for the failed request. - The ``responses`` field will not be set in this case. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.AnnotateFileResponse) - }, -) -_sym_db.RegisterMessage(AnnotateFileResponse) - -BatchAnnotateFilesRequest = _reflection.GeneratedProtocolMessageType( - "BatchAnnotateFilesRequest", - (_message.Message,), - { - "DESCRIPTOR": _BATCHANNOTATEFILESREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """A list of requests to annotate files using the BatchAnnotateFiles API. - - Attributes: - requests: - Required. The list of file annotation requests. Right now we - support only one AnnotateFileRequest in - BatchAnnotateFilesRequest. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.BatchAnnotateFilesRequest) - }, -) -_sym_db.RegisterMessage(BatchAnnotateFilesRequest) - -BatchAnnotateFilesResponse = _reflection.GeneratedProtocolMessageType( - "BatchAnnotateFilesResponse", - (_message.Message,), - { - "DESCRIPTOR": _BATCHANNOTATEFILESRESPONSE, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """A list of file annotation responses. - - Attributes: - responses: - The list of file annotation responses, each response - corresponding to each AnnotateFileRequest in - BatchAnnotateFilesRequest. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.BatchAnnotateFilesResponse) - }, -) -_sym_db.RegisterMessage(BatchAnnotateFilesResponse) - -AsyncAnnotateFileRequest = _reflection.GeneratedProtocolMessageType( - "AsyncAnnotateFileRequest", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCANNOTATEFILEREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """An offline file annotation request. - - Attributes: - input_config: - Required. Information about the input file. - features: - Required. Requested features. - image_context: - Additional context that may accompany the image(s) in the - file. - output_config: - Required. The desired output location and metadata - (e.g. format). - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.AsyncAnnotateFileRequest) - }, -) -_sym_db.RegisterMessage(AsyncAnnotateFileRequest) - -AsyncAnnotateFileResponse = _reflection.GeneratedProtocolMessageType( - "AsyncAnnotateFileResponse", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCANNOTATEFILERESPONSE, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """The response for a single offline file annotation request. - - Attributes: - output_config: - The output location and metadata from - AsyncAnnotateFileRequest. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.AsyncAnnotateFileResponse) - }, -) -_sym_db.RegisterMessage(AsyncAnnotateFileResponse) - -AsyncBatchAnnotateImagesRequest = _reflection.GeneratedProtocolMessageType( - "AsyncBatchAnnotateImagesRequest", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCBATCHANNOTATEIMAGESREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Request for async image annotation for a list of images. - - Attributes: - requests: - Required. Individual image annotation requests for this batch. - output_config: - Required. The desired output location and metadata - (e.g. format). - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.AsyncBatchAnnotateImagesRequest) - }, -) -_sym_db.RegisterMessage(AsyncBatchAnnotateImagesRequest) - -AsyncBatchAnnotateImagesResponse = _reflection.GeneratedProtocolMessageType( - "AsyncBatchAnnotateImagesResponse", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCBATCHANNOTATEIMAGESRESPONSE, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Response to an async batch image annotation request. - - Attributes: - output_config: - The output location and metadata from - AsyncBatchAnnotateImagesRequest. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.AsyncBatchAnnotateImagesResponse) - }, -) -_sym_db.RegisterMessage(AsyncBatchAnnotateImagesResponse) - -AsyncBatchAnnotateFilesRequest = _reflection.GeneratedProtocolMessageType( - "AsyncBatchAnnotateFilesRequest", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCBATCHANNOTATEFILESREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Multiple async file annotation requests are batched into a single - service call. - - Attributes: - requests: - Required. Individual async file annotation requests for this - batch. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesRequest) - }, -) -_sym_db.RegisterMessage(AsyncBatchAnnotateFilesRequest) - -AsyncBatchAnnotateFilesResponse = _reflection.GeneratedProtocolMessageType( - "AsyncBatchAnnotateFilesResponse", - (_message.Message,), - { - "DESCRIPTOR": _ASYNCBATCHANNOTATEFILESRESPONSE, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Response to an async batch file annotation request. - - Attributes: - responses: - The list of file annotation responses, one for each request in - AsyncBatchAnnotateFilesRequest. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.AsyncBatchAnnotateFilesResponse) - }, -) -_sym_db.RegisterMessage(AsyncBatchAnnotateFilesResponse) - -InputConfig = _reflection.GeneratedProtocolMessageType( - "InputConfig", - (_message.Message,), - { - "DESCRIPTOR": _INPUTCONFIG, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """The desired input location and metadata. - - Attributes: - gcs_source: - The Google Cloud Storage location to read the input from. - content: - File content, represented as a stream of bytes. Note: As with - all ``bytes`` fields, protobuffers use a pure binary - representation, whereas JSON representations use base64. - Currently, this field only works for BatchAnnotateFiles - requests. It does not work for AsyncBatchAnnotateFiles - requests. - mime_type: - The type of the file. Currently only “application/pdf”, - “image/tiff” and “image/gif” are supported. Wildcards are not - supported. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.InputConfig) - }, -) -_sym_db.RegisterMessage(InputConfig) - -OutputConfig = _reflection.GeneratedProtocolMessageType( - "OutputConfig", - (_message.Message,), - { - "DESCRIPTOR": _OUTPUTCONFIG, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """The desired output location and metadata. - - Attributes: - gcs_destination: - The Google Cloud Storage location to write the output(s) to. - batch_size: - The max number of response protos to put into each output JSON - file on Google Cloud Storage. The valid range is [1, 100]. If - not specified, the default value is 20. For example, for one - pdf file with 100 pages, 100 response protos will be - generated. If ``batch_size`` = 20, then 5 json files each - containing 20 response protos will be written under the prefix - ``gcs_destination``.\ ``uri``. Currently, batch_size only - applies to GcsDestination, with potential future support for - other output configurations. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.OutputConfig) - }, -) -_sym_db.RegisterMessage(OutputConfig) - -GcsSource = _reflection.GeneratedProtocolMessageType( - "GcsSource", - (_message.Message,), - { - "DESCRIPTOR": _GCSSOURCE, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """The Google Cloud Storage location where the input will be read from. - - Attributes: - uri: - Google Cloud Storage URI for the input file. This must only be - a Google Cloud Storage object. Wildcards are not currently - supported. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.GcsSource) - }, -) -_sym_db.RegisterMessage(GcsSource) - -GcsDestination = _reflection.GeneratedProtocolMessageType( - "GcsDestination", - (_message.Message,), - { - "DESCRIPTOR": _GCSDESTINATION, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """The Google Cloud Storage location where the output will be written to. - - Attributes: - uri: - Google Cloud Storage URI prefix where the results will be - stored. Results will be in JSON format and preceded by its - corresponding input URI prefix. This field can either - represent a gcs file prefix or gcs directory. In either case, - the uri should be unique because in order to get all of the - output files, you will need to do a wildcard gcs search on the - uri prefix you provide. Examples: - File Prefix: - gs://bucket-name/here/filenameprefix The output files will - be created in gs://bucket-name/here/ and the names of the - output files will begin with “filenameprefix”. - - Directory Prefix: gs://bucket-name/some/location/ The output - files will be created in gs://bucket-name/some/location/ - and the names of the output files could be anything because - there was no filename prefix specified. If multiple - outputs, each response is still AnnotateFileResponse, each of - which contains some subset of the full list of - AnnotateImageResponse. Multiple outputs can happen if, for - example, the output JSON is too large and overflows into - multiple sharded files. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.GcsDestination) - }, -) -_sym_db.RegisterMessage(GcsDestination) - -OperationMetadata = _reflection.GeneratedProtocolMessageType( - "OperationMetadata", - (_message.Message,), - { - "DESCRIPTOR": _OPERATIONMETADATA, - "__module__": "google.cloud.vision_v1p4beta1.proto.image_annotator_pb2", - "__doc__": """Contains metadata for the BatchAnnotateImages operation. - - Attributes: - state: - Current state of the batch operation. - create_time: - The time when the batch request was received. - update_time: - The time when the operation result was last updated. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.OperationMetadata) - }, -) -_sym_db.RegisterMessage(OperationMetadata) - - -DESCRIPTOR._options = None -_ENTITYANNOTATION.fields_by_name["confidence"]._options = None -_BATCHANNOTATEIMAGESREQUEST.fields_by_name["requests"]._options = None -_BATCHANNOTATEFILESREQUEST.fields_by_name["requests"]._options = None -_ASYNCBATCHANNOTATEIMAGESREQUEST.fields_by_name["requests"]._options = None -_ASYNCBATCHANNOTATEIMAGESREQUEST.fields_by_name["output_config"]._options = None -_ASYNCBATCHANNOTATEFILESREQUEST.fields_by_name["requests"]._options = None - -_IMAGEANNOTATOR = _descriptor.ServiceDescriptor( - name="ImageAnnotator", - full_name="google.cloud.vision.v1p4beta1.ImageAnnotator", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\025vision.googleapis.com\322A[https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-vision", - create_key=_descriptor._internal_create_key, - serialized_start=8895, - serialized_end=9904, - methods=[ - _descriptor.MethodDescriptor( - name="BatchAnnotateImages", - full_name="google.cloud.vision.v1p4beta1.ImageAnnotator.BatchAnnotateImages", - index=0, - containing_service=None, - input_type=_BATCHANNOTATEIMAGESREQUEST, - output_type=_BATCHANNOTATEIMAGESRESPONSE, - serialized_options=b'\202\323\344\223\002\037"\032/v1p4beta1/images:annotate:\001*\332A\010requests', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="BatchAnnotateFiles", - full_name="google.cloud.vision.v1p4beta1.ImageAnnotator.BatchAnnotateFiles", - index=1, - containing_service=None, - input_type=_BATCHANNOTATEFILESREQUEST, - output_type=_BATCHANNOTATEFILESRESPONSE, - serialized_options=b'\202\323\344\223\002\036"\031/v1p4beta1/files:annotate:\001*\332A\010requests', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="AsyncBatchAnnotateImages", - full_name="google.cloud.vision.v1p4beta1.ImageAnnotator.AsyncBatchAnnotateImages", - index=2, - containing_service=None, - input_type=_ASYNCBATCHANNOTATEIMAGESREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002)"$/v1p4beta1/images:asyncBatchAnnotate:\001*\332A\026requests,output_config\312A5\n AsyncBatchAnnotateImagesResponse\022\021OperationMetadata', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="AsyncBatchAnnotateFiles", - full_name="google.cloud.vision.v1p4beta1.ImageAnnotator.AsyncBatchAnnotateFiles", - index=3, - containing_service=None, - input_type=_ASYNCBATCHANNOTATEFILESREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002("#/v1p4beta1/files:asyncBatchAnnotate:\001*\332A\010requests\312A4\n\037AsyncBatchAnnotateFilesResponse\022\021OperationMetadata', - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_IMAGEANNOTATOR) - -DESCRIPTOR.services_by_name["ImageAnnotator"] = _IMAGEANNOTATOR - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p4beta1/proto/image_annotator_pb2_grpc.py b/google/cloud/vision_v1p4beta1/proto/image_annotator_pb2_grpc.py deleted file mode 100644 index ebfedef4..00000000 --- a/google/cloud/vision_v1p4beta1/proto/image_annotator_pb2_grpc.py +++ /dev/null @@ -1,243 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.vision_v1p4beta1.proto import ( - image_annotator_pb2 as google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) - - -class ImageAnnotatorStub(object): - """Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.BatchAnnotateImages = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateImages", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesResponse.FromString, - ) - self.BatchAnnotateFiles = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateFiles", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateFilesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateFilesResponse.FromString, - ) - self.AsyncBatchAnnotateImages = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateImages", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.AsyncBatchAnnotateImagesRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - self.AsyncBatchAnnotateFiles = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateFiles", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.AsyncBatchAnnotateFilesRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - - -class ImageAnnotatorServicer(object): - """Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - def BatchAnnotateImages(self, request, context): - """Run image detection and annotation for a batch of images. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def BatchAnnotateFiles(self, request, context): - """Service that performs image detection and annotation for a batch of files. - Now only "application/pdf", "image/tiff" and "image/gif" are supported. - - This service will extract at most 5 (customers can specify which 5 in - AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each - file provided and perform detection and annotation for each image - extracted. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def AsyncBatchAnnotateImages(self, request, context): - """Run asynchronous image detection and annotation for a list of images. - - Progress and results can be retrieved through the - `google.longrunning.Operations` interface. - `Operation.metadata` contains `OperationMetadata` (metadata). - `Operation.response` contains `AsyncBatchAnnotateImagesResponse` (results). - - This service will write image annotation outputs to json files in customer - GCS bucket, each json file containing BatchAnnotateImagesResponse proto. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def AsyncBatchAnnotateFiles(self, request, context): - """Run asynchronous image detection and annotation for a list of generic - files, such as PDF files, which may contain multiple pages and multiple - images per page. Progress and results can be retrieved through the - `google.longrunning.Operations` interface. - `Operation.metadata` contains `OperationMetadata` (metadata). - `Operation.response` contains `AsyncBatchAnnotateFilesResponse` (results). - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_ImageAnnotatorServicer_to_server(servicer, server): - rpc_method_handlers = { - "BatchAnnotateImages": grpc.unary_unary_rpc_method_handler( - servicer.BatchAnnotateImages, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesResponse.SerializeToString, - ), - "BatchAnnotateFiles": grpc.unary_unary_rpc_method_handler( - servicer.BatchAnnotateFiles, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateFilesRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateFilesResponse.SerializeToString, - ), - "AsyncBatchAnnotateImages": grpc.unary_unary_rpc_method_handler( - servicer.AsyncBatchAnnotateImages, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.AsyncBatchAnnotateImagesRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - "AsyncBatchAnnotateFiles": grpc.unary_unary_rpc_method_handler( - servicer.AsyncBatchAnnotateFiles, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.AsyncBatchAnnotateFilesRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.vision.v1p4beta1.ImageAnnotator", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class ImageAnnotator(object): - """Service that performs Google Cloud Vision API detection tasks over client - images, such as face, landmark, logo, label, and text detection. The - ImageAnnotator service returns detected entities from the images. - """ - - @staticmethod - def BatchAnnotateImages( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateImages", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateImagesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def BatchAnnotateFiles( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateFiles", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateFilesRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.BatchAnnotateFilesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def AsyncBatchAnnotateImages( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateImages", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.AsyncBatchAnnotateImagesRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def AsyncBatchAnnotateFiles( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateFiles", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_image__annotator__pb2.AsyncBatchAnnotateFilesRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/vision_v1p4beta1/proto/product_search_pb2.py b/google/cloud/vision_v1p4beta1/proto/product_search_pb2.py deleted file mode 100644 index ca773d67..00000000 --- a/google/cloud/vision_v1p4beta1/proto/product_search_pb2.py +++ /dev/null @@ -1,654 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p4beta1/proto/product_search.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.vision_v1p4beta1.proto import ( - geometry_pb2 as google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2, -) -from google.cloud.vision_v1p4beta1.proto import ( - product_search_service_pb2 as google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2, -) -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p4beta1/proto/product_search.proto", - package="google.cloud.vision.v1p4beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p4beta1B\022ProductSearchProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision\370\001\001\242\002\004GCVN", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n8google/cloud/vision_v1p4beta1/proto/product_search.proto\x12\x1dgoogle.cloud.vision.v1p4beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x19google/api/resource.proto\x1a\x32google/cloud/vision_v1p4beta1/proto/geometry.proto\x1a@google/cloud/vision_v1p4beta1/proto/product_search_service.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xc1\x01\n\x13ProductSearchParams\x12\x42\n\rbounding_poly\x18\t \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.BoundingPoly\x12:\n\x0bproduct_set\x18\x06 \x01(\tB%\xfa\x41"\n vision.googleapis.com/ProductSet\x12\x1a\n\x12product_categories\x18\x07 \x03(\t\x12\x0e\n\x06\x66ilter\x18\x08 \x01(\t"\xb2\x05\n\x14ProductSearchResults\x12.\n\nindex_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12K\n\x07results\x18\x05 \x03(\x0b\x32:.google.cloud.vision.v1p4beta1.ProductSearchResults.Result\x12\x62\n\x17product_grouped_results\x18\x06 \x03(\x0b\x32\x41.google.cloud.vision.v1p4beta1.ProductSearchResults.GroupedResult\x1a_\n\x06Result\x12\x37\n\x07product\x18\x01 \x01(\x0b\x32&.google.cloud.vision.v1p4beta1.Product\x12\r\n\x05score\x18\x02 \x01(\x02\x12\r\n\x05image\x18\x03 \x01(\t\x1aS\n\x10ObjectAnnotation\x12\x0b\n\x03mid\x18\x01 \x01(\t\x12\x15\n\rlanguage_code\x18\x02 \x01(\t\x12\x0c\n\x04name\x18\x03 \x01(\t\x12\r\n\x05score\x18\x04 \x01(\x02\x1a\x82\x02\n\rGroupedResult\x12\x42\n\rbounding_poly\x18\x01 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.BoundingPoly\x12K\n\x07results\x18\x02 \x03(\x0b\x32:.google.cloud.vision.v1p4beta1.ProductSearchResults.Result\x12`\n\x12object_annotations\x18\x03 \x03(\x0b\x32\x44.google.cloud.vision.v1p4beta1.ProductSearchResults.ObjectAnnotationB\x88\x01\n!com.google.cloud.vision.v1p4beta1B\x12ProductSearchProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision\xf8\x01\x01\xa2\x02\x04GCVNb\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - ], -) - - -_PRODUCTSEARCHPARAMS = _descriptor.Descriptor( - name="ProductSearchParams", - full_name="google.cloud.vision.v1p4beta1.ProductSearchParams", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p4beta1.ProductSearchParams.bounding_poly", - index=0, - number=9, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_set", - full_name="google.cloud.vision.v1p4beta1.ProductSearchParams.product_set", - index=1, - number=6, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\372A"\n vision.googleapis.com/ProductSet', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_categories", - full_name="google.cloud.vision.v1p4beta1.ProductSearchParams.product_categories", - index=2, - number=7, - type=9, - cpp_type=9, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="filter", - full_name="google.cloud.vision.v1p4beta1.ProductSearchParams.filter", - index=3, - number=8, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=300, - serialized_end=493, -) - - -_PRODUCTSEARCHRESULTS_RESULT = _descriptor.Descriptor( - name="Result", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults.Result", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="product", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults.Result.product", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults.Result.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="image", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults.Result.image", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=745, - serialized_end=840, -) - -_PRODUCTSEARCHRESULTS_OBJECTANNOTATION = _descriptor.Descriptor( - name="ObjectAnnotation", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults.ObjectAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="mid", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults.ObjectAnnotation.mid", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="language_code", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults.ObjectAnnotation.language_code", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults.ObjectAnnotation.name", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults.ObjectAnnotation.score", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=842, - serialized_end=925, -) - -_PRODUCTSEARCHRESULTS_GROUPEDRESULT = _descriptor.Descriptor( - name="GroupedResult", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults.GroupedResult", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="bounding_poly", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults.GroupedResult.bounding_poly", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="results", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults.GroupedResult.results", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="object_annotations", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults.GroupedResult.object_annotations", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=928, - serialized_end=1186, -) - -_PRODUCTSEARCHRESULTS = _descriptor.Descriptor( - name="ProductSearchResults", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="index_time", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults.index_time", - index=0, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="results", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults.results", - index=1, - number=5, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_grouped_results", - full_name="google.cloud.vision.v1p4beta1.ProductSearchResults.product_grouped_results", - index=2, - number=6, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _PRODUCTSEARCHRESULTS_RESULT, - _PRODUCTSEARCHRESULTS_OBJECTANNOTATION, - _PRODUCTSEARCHRESULTS_GROUPEDRESULT, - ], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=496, - serialized_end=1186, -) - -_PRODUCTSEARCHPARAMS.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_PRODUCTSEARCHRESULTS_RESULT.fields_by_name[ - "product" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2._PRODUCT -) -_PRODUCTSEARCHRESULTS_RESULT.containing_type = _PRODUCTSEARCHRESULTS -_PRODUCTSEARCHRESULTS_OBJECTANNOTATION.containing_type = _PRODUCTSEARCHRESULTS -_PRODUCTSEARCHRESULTS_GROUPEDRESULT.fields_by_name[ - "bounding_poly" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_PRODUCTSEARCHRESULTS_GROUPEDRESULT.fields_by_name[ - "results" -].message_type = _PRODUCTSEARCHRESULTS_RESULT -_PRODUCTSEARCHRESULTS_GROUPEDRESULT.fields_by_name[ - "object_annotations" -].message_type = _PRODUCTSEARCHRESULTS_OBJECTANNOTATION -_PRODUCTSEARCHRESULTS_GROUPEDRESULT.containing_type = _PRODUCTSEARCHRESULTS -_PRODUCTSEARCHRESULTS.fields_by_name[ - "index_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_PRODUCTSEARCHRESULTS.fields_by_name[ - "results" -].message_type = _PRODUCTSEARCHRESULTS_RESULT -_PRODUCTSEARCHRESULTS.fields_by_name[ - "product_grouped_results" -].message_type = _PRODUCTSEARCHRESULTS_GROUPEDRESULT -DESCRIPTOR.message_types_by_name["ProductSearchParams"] = _PRODUCTSEARCHPARAMS -DESCRIPTOR.message_types_by_name["ProductSearchResults"] = _PRODUCTSEARCHRESULTS -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -ProductSearchParams = _reflection.GeneratedProtocolMessageType( - "ProductSearchParams", - (_message.Message,), - { - "DESCRIPTOR": _PRODUCTSEARCHPARAMS, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_pb2", - "__doc__": """Parameters for a product search request. - - Attributes: - bounding_poly: - The bounding polygon around the area of interest in the image. - If it is not specified, system discretion will be applied. - product_set: - The resource name of a - [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] to be - searched for similar images. Format is: ``projects/PROJECT_ID - /locations/LOC_ID/productSets/PRODUCT_SET_ID``. - product_categories: - The list of product categories to search in. Currently, we - only consider the first category, and either “homegoods-v2”, - “apparel-v2”, “toys-v2”, “packagedgoods-v1”, or “general-v1” - should be specified. The legacy categories “homegoods”, - “apparel”, and “toys” are still supported but will be - deprecated. For new products, please use “homegoods-v2”, - “apparel-v2”, or “toys-v2” for better product search accuracy. - It is recommended to migrate existing products to these - categories as well. - filter: - The filtering expression. This can be used to restrict search - results based on Product labels. We currently support an AND - of OR of key-value expressions, where each expression within - an OR must have the same key. An ‘=’ should be used to connect - the key and value. For example, “(color = red OR color = - blue) AND brand = Google” is acceptable, but “(color = red OR - brand = Google)” is not acceptable. “color: red” is not - acceptable because it uses a ‘:’ instead of an ‘=’. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ProductSearchParams) - }, -) -_sym_db.RegisterMessage(ProductSearchParams) - -ProductSearchResults = _reflection.GeneratedProtocolMessageType( - "ProductSearchResults", - (_message.Message,), - { - "Result": _reflection.GeneratedProtocolMessageType( - "Result", - (_message.Message,), - { - "DESCRIPTOR": _PRODUCTSEARCHRESULTS_RESULT, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_pb2", - "__doc__": """Information about a product. - - Attributes: - product: - The Product. - score: - A confidence level on the match, ranging from 0 (no - confidence) to 1 (full confidence). - image: - The resource name of the image from the product that is the - closest match to the query. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ProductSearchResults.Result) - }, - ), - "ObjectAnnotation": _reflection.GeneratedProtocolMessageType( - "ObjectAnnotation", - (_message.Message,), - { - "DESCRIPTOR": _PRODUCTSEARCHRESULTS_OBJECTANNOTATION, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_pb2", - "__doc__": """Prediction for what the object in the bounding box is. - - Attributes: - mid: - Object ID that should align with EntityAnnotation mid. - language_code: - The BCP-47 language code, such as “en-US” or “sr-Latn”. For - more information, see http://www.unicode.org/reports/tr35/#Uni - code_locale_identifier. - name: - Object name, expressed in its ``language_code`` language. - score: - Score of the result. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ProductSearchResults.ObjectAnnotation) - }, - ), - "GroupedResult": _reflection.GeneratedProtocolMessageType( - "GroupedResult", - (_message.Message,), - { - "DESCRIPTOR": _PRODUCTSEARCHRESULTS_GROUPEDRESULT, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_pb2", - "__doc__": """Information about the products similar to a single product in a query - image. - - Attributes: - bounding_poly: - The bounding polygon around the product detected in the query - image. - results: - List of results, one for each product match. - object_annotations: - List of generic predictions for the object in the bounding - box. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ProductSearchResults.GroupedResult) - }, - ), - "DESCRIPTOR": _PRODUCTSEARCHRESULTS, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_pb2", - "__doc__": """Results for a product search request. - - Attributes: - index_time: - Timestamp of the index which provided these results. Products - added to the product set and products removed from the product - set after this time are not reflected in the current results. - results: - List of results, one for each product match. - product_grouped_results: - List of results grouped by products detected in the query - image. Each entry corresponds to one bounding polygon in the - query image, and contains the matching products specific to - that region. There may be duplicate product matches in the - union of all the per-product results. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ProductSearchResults) - }, -) -_sym_db.RegisterMessage(ProductSearchResults) -_sym_db.RegisterMessage(ProductSearchResults.Result) -_sym_db.RegisterMessage(ProductSearchResults.ObjectAnnotation) -_sym_db.RegisterMessage(ProductSearchResults.GroupedResult) - - -DESCRIPTOR._options = None -_PRODUCTSEARCHPARAMS.fields_by_name["product_set"]._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p4beta1/proto/product_search_pb2_grpc.py b/google/cloud/vision_v1p4beta1/proto/product_search_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/vision_v1p4beta1/proto/product_search_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/vision_v1p4beta1/proto/product_search_service_pb2.py b/google/cloud/vision_v1p4beta1/proto/product_search_service_pb2.py deleted file mode 100644 index 0323a4fe..00000000 --- a/google/cloud/vision_v1p4beta1/proto/product_search_service_pb2.py +++ /dev/null @@ -1,3367 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p4beta1/proto/product_search_service.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.api import client_pb2 as google_dot_api_dot_client__pb2 -from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 -from google.cloud.vision_v1p4beta1.proto import ( - geometry_pb2 as google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 -from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 -from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p4beta1/proto/product_search_service.proto", - package="google.cloud.vision.v1p4beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p4beta1B\031ProductSearchServiceProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision\370\001\001\242\002\004GCVN", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n@google/cloud/vision_v1p4beta1/proto/product_search_service.proto\x12\x1dgoogle.cloud.vision.v1p4beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x32google/cloud/vision_v1p4beta1/proto/geometry.proto\x1a#google/longrunning/operations.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x17google/rpc/status.proto"\xb2\x02\n\x07Product\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\x12\x1d\n\x10product_category\x18\x04 \x01(\tB\x03\xe0\x41\x05\x12G\n\x0eproduct_labels\x18\x05 \x03(\x0b\x32/.google.cloud.vision.v1p4beta1.Product.KeyValue\x1a&\n\x08KeyValue\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:^\xea\x41[\n\x1dvision.googleapis.com/Product\x12:projects/{project}/locations/{location}/products/{product}"\xfd\x01\n\nProductSet\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x02 \x01(\t\x12\x33\n\nindex_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x03\x12,\n\x0bindex_error\x18\x04 \x01(\x0b\x32\x12.google.rpc.StatusB\x03\xe0\x41\x03:h\xea\x41\x65\n vision.googleapis.com/ProductSet\x12\x41projects/{project}/locations/{location}/productSets/{product_set}"\x85\x02\n\x0eReferenceImage\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x10\n\x03uri\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12H\n\x0e\x62ounding_polys\x18\x03 \x03(\x0b\x32+.google.cloud.vision.v1p4beta1.BoundingPolyB\x03\xe0\x41\x01:\x88\x01\xea\x41\x84\x01\n$vision.googleapis.com/ReferenceImage\x12\\projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}"\xa3\x01\n\x14\x43reateProductRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12<\n\x07product\x18\x02 \x01(\x0b\x32&.google.cloud.vision.v1p4beta1.ProductB\x03\xe0\x41\x02\x12\x12\n\nproduct_id\x18\x03 \x01(\t"w\n\x13ListProductsRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t"i\n\x14ListProductsResponse\x12\x38\n\x08products\x18\x01 \x03(\x0b\x32&.google.cloud.vision.v1p4beta1.Product\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"H\n\x11GetProductRequest\x12\x33\n\x04name\x18\x01 \x01(\tB%\xe0\x41\x02\xfa\x41\x1f\n\x1dvision.googleapis.com/Product"\x85\x01\n\x14UpdateProductRequest\x12<\n\x07product\x18\x01 \x01(\x0b\x32&.google.cloud.vision.v1p4beta1.ProductB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"K\n\x14\x44\x65leteProductRequest\x12\x33\n\x04name\x18\x01 \x01(\tB%\xe0\x41\x02\xfa\x41\x1f\n\x1dvision.googleapis.com/Product"\xb1\x01\n\x17\x43reateProductSetRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12\x43\n\x0bproduct_set\x18\x02 \x01(\x0b\x32).google.cloud.vision.v1p4beta1.ProductSetB\x03\xe0\x41\x02\x12\x16\n\x0eproduct_set_id\x18\x03 \x01(\t"z\n\x16ListProductSetsRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t"s\n\x17ListProductSetsResponse\x12?\n\x0cproduct_sets\x18\x01 \x03(\x0b\x32).google.cloud.vision.v1p4beta1.ProductSet\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"N\n\x14GetProductSetRequest\x12\x36\n\x04name\x18\x01 \x01(\tB(\xe0\x41\x02\xfa\x41"\n vision.googleapis.com/ProductSet"\x8f\x01\n\x17UpdateProductSetRequest\x12\x43\n\x0bproduct_set\x18\x01 \x01(\x0b\x32).google.cloud.vision.v1p4beta1.ProductSetB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"Q\n\x17\x44\x65leteProductSetRequest\x12\x36\n\x04name\x18\x01 \x01(\tB(\xe0\x41\x02\xfa\x41"\n vision.googleapis.com/ProductSet"\xbd\x01\n\x1b\x43reateReferenceImageRequest\x12\x35\n\x06parent\x18\x01 \x01(\tB%\xe0\x41\x02\xfa\x41\x1f\n\x1dvision.googleapis.com/Product\x12K\n\x0freference_image\x18\x02 \x01(\x0b\x32-.google.cloud.vision.v1p4beta1.ReferenceImageB\x03\xe0\x41\x02\x12\x1a\n\x12reference_image_id\x18\x03 \x01(\t"z\n\x1aListReferenceImagesRequest\x12\x35\n\x06parent\x18\x01 \x01(\tB%\xe0\x41\x02\xfa\x41\x1f\n\x1dvision.googleapis.com/Product\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t"\x92\x01\n\x1bListReferenceImagesResponse\x12G\n\x10reference_images\x18\x01 \x03(\x0b\x32-.google.cloud.vision.v1p4beta1.ReferenceImage\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t"V\n\x18GetReferenceImageRequest\x12:\n\x04name\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$vision.googleapis.com/ReferenceImage"Y\n\x1b\x44\x65leteReferenceImageRequest\x12:\n\x04name\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$vision.googleapis.com/ReferenceImage"\x8f\x01\n\x1d\x41\x64\x64ProductToProductSetRequest\x12\x36\n\x04name\x18\x01 \x01(\tB(\xe0\x41\x02\xfa\x41"\n vision.googleapis.com/ProductSet\x12\x36\n\x07product\x18\x02 \x01(\tB%\xe0\x41\x02\xfa\x41\x1f\n\x1dvision.googleapis.com/Product"\x94\x01\n"RemoveProductFromProductSetRequest\x12\x36\n\x04name\x18\x01 \x01(\tB(\xe0\x41\x02\xfa\x41"\n vision.googleapis.com/ProductSet\x12\x36\n\x07product\x18\x02 \x01(\tB%\xe0\x41\x02\xfa\x41\x1f\n\x1dvision.googleapis.com/Product"\x80\x01\n\x1fListProductsInProductSetRequest\x12\x36\n\x04name\x18\x01 \x01(\tB(\xe0\x41\x02\xfa\x41"\n vision.googleapis.com/ProductSet\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t"u\n ListProductsInProductSetResponse\x12\x38\n\x08products\x18\x01 \x03(\x0b\x32&.google.cloud.vision.v1p4beta1.Product\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"2\n\x1aImportProductSetsGcsSource\x12\x14\n\x0c\x63sv_file_uri\x18\x01 \x01(\t"y\n\x1cImportProductSetsInputConfig\x12O\n\ngcs_source\x18\x01 \x01(\x0b\x32\x39.google.cloud.vision.v1p4beta1.ImportProductSetsGcsSourceH\x00\x42\x08\n\x06source"\xad\x01\n\x18ImportProductSetsRequest\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12V\n\x0cinput_config\x18\x02 \x01(\x0b\x32;.google.cloud.vision.v1p4beta1.ImportProductSetsInputConfigB\x03\xe0\x41\x02"\x8a\x01\n\x19ImportProductSetsResponse\x12G\n\x10reference_images\x18\x01 \x03(\x0b\x32-.google.cloud.vision.v1p4beta1.ReferenceImage\x12$\n\x08statuses\x18\x02 \x03(\x0b\x32\x12.google.rpc.Status"\x9e\x02\n\x16\x42\x61tchOperationMetadata\x12J\n\x05state\x18\x01 \x01(\x0e\x32;.google.cloud.vision.v1p4beta1.BatchOperationMetadata.State\x12/\n\x0bsubmit_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x08\x65nd_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp"Y\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0e\n\nPROCESSING\x10\x01\x12\x0e\n\nSUCCESSFUL\x10\x02\x12\n\n\x06\x46\x41ILED\x10\x03\x12\r\n\tCANCELLED\x10\x04"/\n\x15ProductSetPurgeConfig\x12\x16\n\x0eproduct_set_id\x18\x01 \x01(\t"\xe6\x01\n\x14PurgeProductsRequest\x12X\n\x18product_set_purge_config\x18\x02 \x01(\x0b\x32\x34.google.cloud.vision.v1p4beta1.ProductSetPurgeConfigH\x00\x12 \n\x16\x64\x65lete_orphan_products\x18\x03 \x01(\x08H\x00\x12\x39\n\x06parent\x18\x01 \x01(\tB)\xe0\x41\x02\xfa\x41#\n!locations.googleapis.com/Location\x12\r\n\x05\x66orce\x18\x04 \x01(\x08\x42\x08\n\x06target2\xd2 \n\rProductSearch\x12\xe6\x01\n\x10\x43reateProductSet\x12\x36.google.cloud.vision.v1p4beta1.CreateProductSetRequest\x1a).google.cloud.vision.v1p4beta1.ProductSet"o\x82\xd3\xe4\x93\x02\x45"6/v1p4beta1/{parent=projects/*/locations/*}/productSets:\x0bproduct_set\xda\x41!parent,product_set,product_set_id\x12\xc9\x01\n\x0fListProductSets\x12\x35.google.cloud.vision.v1p4beta1.ListProductSetsRequest\x1a\x36.google.cloud.vision.v1p4beta1.ListProductSetsResponse"G\x82\xd3\xe4\x93\x02\x38\x12\x36/v1p4beta1/{parent=projects/*/locations/*}/productSets\xda\x41\x06parent\x12\xb6\x01\n\rGetProductSet\x12\x33.google.cloud.vision.v1p4beta1.GetProductSetRequest\x1a).google.cloud.vision.v1p4beta1.ProductSet"E\x82\xd3\xe4\x93\x02\x38\x12\x36/v1p4beta1/{name=projects/*/locations/*/productSets/*}\xda\x41\x04name\x12\xe8\x01\n\x10UpdateProductSet\x12\x36.google.cloud.vision.v1p4beta1.UpdateProductSetRequest\x1a).google.cloud.vision.v1p4beta1.ProductSet"q\x82\xd3\xe4\x93\x02Q2B/v1p4beta1/{product_set.name=projects/*/locations/*/productSets/*}:\x0bproduct_set\xda\x41\x17product_set,update_mask\x12\xa9\x01\n\x10\x44\x65leteProductSet\x12\x36.google.cloud.vision.v1p4beta1.DeleteProductSetRequest\x1a\x16.google.protobuf.Empty"E\x82\xd3\xe4\x93\x02\x38*6/v1p4beta1/{name=projects/*/locations/*/productSets/*}\xda\x41\x04name\x12\xce\x01\n\rCreateProduct\x12\x33.google.cloud.vision.v1p4beta1.CreateProductRequest\x1a&.google.cloud.vision.v1p4beta1.Product"`\x82\xd3\xe4\x93\x02>"3/v1p4beta1/{parent=projects/*/locations/*}/products:\x07product\xda\x41\x19parent,product,product_id\x12\xbd\x01\n\x0cListProducts\x12\x32.google.cloud.vision.v1p4beta1.ListProductsRequest\x1a\x33.google.cloud.vision.v1p4beta1.ListProductsResponse"D\x82\xd3\xe4\x93\x02\x35\x12\x33/v1p4beta1/{parent=projects/*/locations/*}/products\xda\x41\x06parent\x12\xaa\x01\n\nGetProduct\x12\x30.google.cloud.vision.v1p4beta1.GetProductRequest\x1a&.google.cloud.vision.v1p4beta1.Product"B\x82\xd3\xe4\x93\x02\x35\x12\x33/v1p4beta1/{name=projects/*/locations/*/products/*}\xda\x41\x04name\x12\xd0\x01\n\rUpdateProduct\x12\x33.google.cloud.vision.v1p4beta1.UpdateProductRequest\x1a&.google.cloud.vision.v1p4beta1.Product"b\x82\xd3\xe4\x93\x02\x46\x32;/v1p4beta1/{product.name=projects/*/locations/*/products/*}:\x07product\xda\x41\x13product,update_mask\x12\xa0\x01\n\rDeleteProduct\x12\x33.google.cloud.vision.v1p4beta1.DeleteProductRequest\x1a\x16.google.protobuf.Empty"B\x82\xd3\xe4\x93\x02\x35*3/v1p4beta1/{name=projects/*/locations/*/products/*}\xda\x41\x04name\x12\x8e\x02\n\x14\x43reateReferenceImage\x12:.google.cloud.vision.v1p4beta1.CreateReferenceImageRequest\x1a-.google.cloud.vision.v1p4beta1.ReferenceImage"\x8a\x01\x82\xd3\xe4\x93\x02X"E/v1p4beta1/{parent=projects/*/locations/*/products/*}/referenceImages:\x0freference_image\xda\x41)parent,reference_image,reference_image_id\x12\xc0\x01\n\x14\x44\x65leteReferenceImage\x12:.google.cloud.vision.v1p4beta1.DeleteReferenceImageRequest\x1a\x16.google.protobuf.Empty"T\x82\xd3\xe4\x93\x02G*E/v1p4beta1/{name=projects/*/locations/*/products/*/referenceImages/*}\xda\x41\x04name\x12\xe4\x01\n\x13ListReferenceImages\x12\x39.google.cloud.vision.v1p4beta1.ListReferenceImagesRequest\x1a:.google.cloud.vision.v1p4beta1.ListReferenceImagesResponse"V\x82\xd3\xe4\x93\x02G\x12\x45/v1p4beta1/{parent=projects/*/locations/*/products/*}/referenceImages\xda\x41\x06parent\x12\xd1\x01\n\x11GetReferenceImage\x12\x37.google.cloud.vision.v1p4beta1.GetReferenceImageRequest\x1a-.google.cloud.vision.v1p4beta1.ReferenceImage"T\x82\xd3\xe4\x93\x02G\x12\x45/v1p4beta1/{name=projects/*/locations/*/products/*/referenceImages/*}\xda\x41\x04name\x12\xcb\x01\n\x16\x41\x64\x64ProductToProductSet\x12<.google.cloud.vision.v1p4beta1.AddProductToProductSetRequest\x1a\x16.google.protobuf.Empty"[\x82\xd3\xe4\x93\x02\x46"A/v1p4beta1/{name=projects/*/locations/*/productSets/*}:addProduct:\x01*\xda\x41\x0cname,product\x12\xd8\x01\n\x1bRemoveProductFromProductSet\x12\x41.google.cloud.vision.v1p4beta1.RemoveProductFromProductSetRequest\x1a\x16.google.protobuf.Empty"^\x82\xd3\xe4\x93\x02I"D/v1p4beta1/{name=projects/*/locations/*/productSets/*}:removeProduct:\x01*\xda\x41\x0cname,product\x12\xeb\x01\n\x18ListProductsInProductSet\x12>.google.cloud.vision.v1p4beta1.ListProductsInProductSetRequest\x1a?.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse"N\x82\xd3\xe4\x93\x02\x41\x12?/v1p4beta1/{name=projects/*/locations/*/productSets/*}/products\xda\x41\x04name\x12\x82\x02\n\x11ImportProductSets\x12\x37.google.cloud.vision.v1p4beta1.ImportProductSetsRequest\x1a\x1d.google.longrunning.Operation"\x94\x01\x82\xd3\xe4\x93\x02\x42"=/v1p4beta1/{parent=projects/*/locations/*}/productSets:import:\x01*\xda\x41\x13parent,input_config\xca\x41\x33\n\x19ImportProductSetsResponse\x12\x16\x42\x61tchOperationMetadata\x12\xe4\x01\n\rPurgeProducts\x12\x33.google.cloud.vision.v1p4beta1.PurgeProductsRequest\x1a\x1d.google.longrunning.Operation"\x7f\x82\xd3\xe4\x93\x02>"9/v1p4beta1/{parent=projects/*/locations/*}/products:purge:\x01*\xda\x41\x06parent\xca\x41/\n\x15google.protobuf.Empty\x12\x16\x42\x61tchOperationMetadata\x1av\xca\x41\x15vision.googleapis.com\xd2\x41[https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-visionB\x8f\x01\n!com.google.cloud.vision.v1p4beta1B\x19ProductSearchServiceProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision\xf8\x01\x01\xa2\x02\x04GCVNb\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_api_dot_client__pb2.DESCRIPTOR, - google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2.DESCRIPTOR, - google_dot_longrunning_dot_operations__pb2.DESCRIPTOR, - google_dot_protobuf_dot_empty__pb2.DESCRIPTOR, - google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR, - google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_rpc_dot_status__pb2.DESCRIPTOR, - ], -) - - -_BATCHOPERATIONMETADATA_STATE = _descriptor.EnumDescriptor( - name="State", - full_name="google.cloud.vision.v1p4beta1.BatchOperationMetadata.State", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="STATE_UNSPECIFIED", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="PROCESSING", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SUCCESSFUL", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="FAILED", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="CANCELLED", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=4545, - serialized_end=4634, -) -_sym_db.RegisterEnumDescriptor(_BATCHOPERATIONMETADATA_STATE) - - -_PRODUCT_KEYVALUE = _descriptor.Descriptor( - name="KeyValue", - full_name="google.cloud.vision.v1p4beta1.Product.KeyValue", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="key", - full_name="google.cloud.vision.v1p4beta1.Product.KeyValue.key", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="value", - full_name="google.cloud.vision.v1p4beta1.Product.KeyValue.value", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=597, - serialized_end=635, -) - -_PRODUCT = _descriptor.Descriptor( - name="Product", - full_name="google.cloud.vision.v1p4beta1.Product", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p4beta1.Product.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="display_name", - full_name="google.cloud.vision.v1p4beta1.Product.display_name", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.vision.v1p4beta1.Product.description", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_category", - full_name="google.cloud.vision.v1p4beta1.Product.product_category", - index=3, - number=4, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\005", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_labels", - full_name="google.cloud.vision.v1p4beta1.Product.product_labels", - index=4, - number=5, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[_PRODUCT_KEYVALUE,], - enum_types=[], - serialized_options=b"\352A[\n\035vision.googleapis.com/Product\022:projects/{project}/locations/{location}/products/{product}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=425, - serialized_end=731, -) - - -_PRODUCTSET = _descriptor.Descriptor( - name="ProductSet", - full_name="google.cloud.vision.v1p4beta1.ProductSet", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p4beta1.ProductSet.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="display_name", - full_name="google.cloud.vision.v1p4beta1.ProductSet.display_name", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="index_time", - full_name="google.cloud.vision.v1p4beta1.ProductSet.index_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="index_error", - full_name="google.cloud.vision.v1p4beta1.ProductSet.index_error", - index=3, - number=4, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\003", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"\352Ae\n vision.googleapis.com/ProductSet\022Aprojects/{project}/locations/{location}/productSets/{product_set}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=734, - serialized_end=987, -) - - -_REFERENCEIMAGE = _descriptor.Descriptor( - name="ReferenceImage", - full_name="google.cloud.vision.v1p4beta1.ReferenceImage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p4beta1.ReferenceImage.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="uri", - full_name="google.cloud.vision.v1p4beta1.ReferenceImage.uri", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_polys", - full_name="google.cloud.vision.v1p4beta1.ReferenceImage.bounding_polys", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\001", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=b"\352A\204\001\n$vision.googleapis.com/ReferenceImage\022\\projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}", - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=990, - serialized_end=1251, -) - - -_CREATEPRODUCTREQUEST = _descriptor.Descriptor( - name="CreateProductRequest", - full_name="google.cloud.vision.v1p4beta1.CreateProductRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.vision.v1p4beta1.CreateProductRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product", - full_name="google.cloud.vision.v1p4beta1.CreateProductRequest.product", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_id", - full_name="google.cloud.vision.v1p4beta1.CreateProductRequest.product_id", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1254, - serialized_end=1417, -) - - -_LISTPRODUCTSREQUEST = _descriptor.Descriptor( - name="ListProductsRequest", - full_name="google.cloud.vision.v1p4beta1.ListProductsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.vision.v1p4beta1.ListProductsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.vision.v1p4beta1.ListProductsRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.vision.v1p4beta1.ListProductsRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1419, - serialized_end=1538, -) - - -_LISTPRODUCTSRESPONSE = _descriptor.Descriptor( - name="ListProductsResponse", - full_name="google.cloud.vision.v1p4beta1.ListProductsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="products", - full_name="google.cloud.vision.v1p4beta1.ListProductsResponse.products", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.vision.v1p4beta1.ListProductsResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1540, - serialized_end=1645, -) - - -_GETPRODUCTREQUEST = _descriptor.Descriptor( - name="GetProductRequest", - full_name="google.cloud.vision.v1p4beta1.GetProductRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p4beta1.GetProductRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A\037\n\035vision.googleapis.com/Product", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1647, - serialized_end=1719, -) - - -_UPDATEPRODUCTREQUEST = _descriptor.Descriptor( - name="UpdateProductRequest", - full_name="google.cloud.vision.v1p4beta1.UpdateProductRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="product", - full_name="google.cloud.vision.v1p4beta1.UpdateProductRequest.product", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.vision.v1p4beta1.UpdateProductRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1722, - serialized_end=1855, -) - - -_DELETEPRODUCTREQUEST = _descriptor.Descriptor( - name="DeleteProductRequest", - full_name="google.cloud.vision.v1p4beta1.DeleteProductRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p4beta1.DeleteProductRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A\037\n\035vision.googleapis.com/Product", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1857, - serialized_end=1932, -) - - -_CREATEPRODUCTSETREQUEST = _descriptor.Descriptor( - name="CreateProductSetRequest", - full_name="google.cloud.vision.v1p4beta1.CreateProductSetRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.vision.v1p4beta1.CreateProductSetRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_set", - full_name="google.cloud.vision.v1p4beta1.CreateProductSetRequest.product_set", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product_set_id", - full_name="google.cloud.vision.v1p4beta1.CreateProductSetRequest.product_set_id", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1935, - serialized_end=2112, -) - - -_LISTPRODUCTSETSREQUEST = _descriptor.Descriptor( - name="ListProductSetsRequest", - full_name="google.cloud.vision.v1p4beta1.ListProductSetsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.vision.v1p4beta1.ListProductSetsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.vision.v1p4beta1.ListProductSetsRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.vision.v1p4beta1.ListProductSetsRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2114, - serialized_end=2236, -) - - -_LISTPRODUCTSETSRESPONSE = _descriptor.Descriptor( - name="ListProductSetsResponse", - full_name="google.cloud.vision.v1p4beta1.ListProductSetsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="product_sets", - full_name="google.cloud.vision.v1p4beta1.ListProductSetsResponse.product_sets", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.vision.v1p4beta1.ListProductSetsResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2238, - serialized_end=2353, -) - - -_GETPRODUCTSETREQUEST = _descriptor.Descriptor( - name="GetProductSetRequest", - full_name="google.cloud.vision.v1p4beta1.GetProductSetRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p4beta1.GetProductSetRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A"\n vision.googleapis.com/ProductSet', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2355, - serialized_end=2433, -) - - -_UPDATEPRODUCTSETREQUEST = _descriptor.Descriptor( - name="UpdateProductSetRequest", - full_name="google.cloud.vision.v1p4beta1.UpdateProductSetRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="product_set", - full_name="google.cloud.vision.v1p4beta1.UpdateProductSetRequest.product_set", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="update_mask", - full_name="google.cloud.vision.v1p4beta1.UpdateProductSetRequest.update_mask", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2436, - serialized_end=2579, -) - - -_DELETEPRODUCTSETREQUEST = _descriptor.Descriptor( - name="DeleteProductSetRequest", - full_name="google.cloud.vision.v1p4beta1.DeleteProductSetRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p4beta1.DeleteProductSetRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A"\n vision.googleapis.com/ProductSet', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2581, - serialized_end=2662, -) - - -_CREATEREFERENCEIMAGEREQUEST = _descriptor.Descriptor( - name="CreateReferenceImageRequest", - full_name="google.cloud.vision.v1p4beta1.CreateReferenceImageRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.vision.v1p4beta1.CreateReferenceImageRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A\037\n\035vision.googleapis.com/Product", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="reference_image", - full_name="google.cloud.vision.v1p4beta1.CreateReferenceImageRequest.reference_image", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="reference_image_id", - full_name="google.cloud.vision.v1p4beta1.CreateReferenceImageRequest.reference_image_id", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2665, - serialized_end=2854, -) - - -_LISTREFERENCEIMAGESREQUEST = _descriptor.Descriptor( - name="ListReferenceImagesRequest", - full_name="google.cloud.vision.v1p4beta1.ListReferenceImagesRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.vision.v1p4beta1.ListReferenceImagesRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A\037\n\035vision.googleapis.com/Product", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.vision.v1p4beta1.ListReferenceImagesRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.vision.v1p4beta1.ListReferenceImagesRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2856, - serialized_end=2978, -) - - -_LISTREFERENCEIMAGESRESPONSE = _descriptor.Descriptor( - name="ListReferenceImagesResponse", - full_name="google.cloud.vision.v1p4beta1.ListReferenceImagesResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="reference_images", - full_name="google.cloud.vision.v1p4beta1.ListReferenceImagesResponse.reference_images", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.vision.v1p4beta1.ListReferenceImagesResponse.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.vision.v1p4beta1.ListReferenceImagesResponse.next_page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=2981, - serialized_end=3127, -) - - -_GETREFERENCEIMAGEREQUEST = _descriptor.Descriptor( - name="GetReferenceImageRequest", - full_name="google.cloud.vision.v1p4beta1.GetReferenceImageRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p4beta1.GetReferenceImageRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A&\n$vision.googleapis.com/ReferenceImage", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3129, - serialized_end=3215, -) - - -_DELETEREFERENCEIMAGEREQUEST = _descriptor.Descriptor( - name="DeleteReferenceImageRequest", - full_name="google.cloud.vision.v1p4beta1.DeleteReferenceImageRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p4beta1.DeleteReferenceImageRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A&\n$vision.googleapis.com/ReferenceImage", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3217, - serialized_end=3306, -) - - -_ADDPRODUCTTOPRODUCTSETREQUEST = _descriptor.Descriptor( - name="AddProductToProductSetRequest", - full_name="google.cloud.vision.v1p4beta1.AddProductToProductSetRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p4beta1.AddProductToProductSetRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A"\n vision.googleapis.com/ProductSet', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product", - full_name="google.cloud.vision.v1p4beta1.AddProductToProductSetRequest.product", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A\037\n\035vision.googleapis.com/Product", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3309, - serialized_end=3452, -) - - -_REMOVEPRODUCTFROMPRODUCTSETREQUEST = _descriptor.Descriptor( - name="RemoveProductFromProductSetRequest", - full_name="google.cloud.vision.v1p4beta1.RemoveProductFromProductSetRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p4beta1.RemoveProductFromProductSetRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A"\n vision.googleapis.com/ProductSet', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="product", - full_name="google.cloud.vision.v1p4beta1.RemoveProductFromProductSetRequest.product", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A\037\n\035vision.googleapis.com/Product", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3455, - serialized_end=3603, -) - - -_LISTPRODUCTSINPRODUCTSETREQUEST = _descriptor.Descriptor( - name="ListProductsInProductSetRequest", - full_name="google.cloud.vision.v1p4beta1.ListProductsInProductSetRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="name", - full_name="google.cloud.vision.v1p4beta1.ListProductsInProductSetRequest.name", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b'\340A\002\372A"\n vision.googleapis.com/ProductSet', - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_size", - full_name="google.cloud.vision.v1p4beta1.ListProductsInProductSetRequest.page_size", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_token", - full_name="google.cloud.vision.v1p4beta1.ListProductsInProductSetRequest.page_token", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3606, - serialized_end=3734, -) - - -_LISTPRODUCTSINPRODUCTSETRESPONSE = _descriptor.Descriptor( - name="ListProductsInProductSetResponse", - full_name="google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="products", - full_name="google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse.products", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="next_page_token", - full_name="google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse.next_page_token", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3736, - serialized_end=3853, -) - - -_IMPORTPRODUCTSETSGCSSOURCE = _descriptor.Descriptor( - name="ImportProductSetsGcsSource", - full_name="google.cloud.vision.v1p4beta1.ImportProductSetsGcsSource", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="csv_file_uri", - full_name="google.cloud.vision.v1p4beta1.ImportProductSetsGcsSource.csv_file_uri", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=3855, - serialized_end=3905, -) - - -_IMPORTPRODUCTSETSINPUTCONFIG = _descriptor.Descriptor( - name="ImportProductSetsInputConfig", - full_name="google.cloud.vision.v1p4beta1.ImportProductSetsInputConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="gcs_source", - full_name="google.cloud.vision.v1p4beta1.ImportProductSetsInputConfig.gcs_source", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="source", - full_name="google.cloud.vision.v1p4beta1.ImportProductSetsInputConfig.source", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=3907, - serialized_end=4028, -) - - -_IMPORTPRODUCTSETSREQUEST = _descriptor.Descriptor( - name="ImportProductSetsRequest", - full_name="google.cloud.vision.v1p4beta1.ImportProductSetsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.vision.v1p4beta1.ImportProductSetsRequest.parent", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="input_config", - full_name="google.cloud.vision.v1p4beta1.ImportProductSetsRequest.input_config", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4031, - serialized_end=4204, -) - - -_IMPORTPRODUCTSETSRESPONSE = _descriptor.Descriptor( - name="ImportProductSetsResponse", - full_name="google.cloud.vision.v1p4beta1.ImportProductSetsResponse", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="reference_images", - full_name="google.cloud.vision.v1p4beta1.ImportProductSetsResponse.reference_images", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="statuses", - full_name="google.cloud.vision.v1p4beta1.ImportProductSetsResponse.statuses", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4207, - serialized_end=4345, -) - - -_BATCHOPERATIONMETADATA = _descriptor.Descriptor( - name="BatchOperationMetadata", - full_name="google.cloud.vision.v1p4beta1.BatchOperationMetadata", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="state", - full_name="google.cloud.vision.v1p4beta1.BatchOperationMetadata.state", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="submit_time", - full_name="google.cloud.vision.v1p4beta1.BatchOperationMetadata.submit_time", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="end_time", - full_name="google.cloud.vision.v1p4beta1.BatchOperationMetadata.end_time", - index=2, - number=3, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_BATCHOPERATIONMETADATA_STATE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4348, - serialized_end=4634, -) - - -_PRODUCTSETPURGECONFIG = _descriptor.Descriptor( - name="ProductSetPurgeConfig", - full_name="google.cloud.vision.v1p4beta1.ProductSetPurgeConfig", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="product_set_id", - full_name="google.cloud.vision.v1p4beta1.ProductSetPurgeConfig.product_set_id", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=4636, - serialized_end=4683, -) - - -_PURGEPRODUCTSREQUEST = _descriptor.Descriptor( - name="PurgeProductsRequest", - full_name="google.cloud.vision.v1p4beta1.PurgeProductsRequest", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="product_set_purge_config", - full_name="google.cloud.vision.v1p4beta1.PurgeProductsRequest.product_set_purge_config", - index=0, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="delete_orphan_products", - full_name="google.cloud.vision.v1p4beta1.PurgeProductsRequest.delete_orphan_products", - index=1, - number=3, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="parent", - full_name="google.cloud.vision.v1p4beta1.PurgeProductsRequest.parent", - index=2, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=b"\340A\002\372A#\n!locations.googleapis.com/Location", - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="force", - full_name="google.cloud.vision.v1p4beta1.PurgeProductsRequest.force", - index=3, - number=4, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[ - _descriptor.OneofDescriptor( - name="target", - full_name="google.cloud.vision.v1p4beta1.PurgeProductsRequest.target", - index=0, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[], - ), - ], - serialized_start=4686, - serialized_end=4916, -) - -_PRODUCT_KEYVALUE.containing_type = _PRODUCT -_PRODUCT.fields_by_name["product_labels"].message_type = _PRODUCT_KEYVALUE -_PRODUCTSET.fields_by_name[ - "index_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_PRODUCTSET.fields_by_name[ - "index_error" -].message_type = google_dot_rpc_dot_status__pb2._STATUS -_REFERENCEIMAGE.fields_by_name[ - "bounding_polys" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_CREATEPRODUCTREQUEST.fields_by_name["product"].message_type = _PRODUCT -_LISTPRODUCTSRESPONSE.fields_by_name["products"].message_type = _PRODUCT -_UPDATEPRODUCTREQUEST.fields_by_name["product"].message_type = _PRODUCT -_UPDATEPRODUCTREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_CREATEPRODUCTSETREQUEST.fields_by_name["product_set"].message_type = _PRODUCTSET -_LISTPRODUCTSETSRESPONSE.fields_by_name["product_sets"].message_type = _PRODUCTSET -_UPDATEPRODUCTSETREQUEST.fields_by_name["product_set"].message_type = _PRODUCTSET -_UPDATEPRODUCTSETREQUEST.fields_by_name[ - "update_mask" -].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK -_CREATEREFERENCEIMAGEREQUEST.fields_by_name[ - "reference_image" -].message_type = _REFERENCEIMAGE -_LISTREFERENCEIMAGESRESPONSE.fields_by_name[ - "reference_images" -].message_type = _REFERENCEIMAGE -_LISTPRODUCTSINPRODUCTSETRESPONSE.fields_by_name["products"].message_type = _PRODUCT -_IMPORTPRODUCTSETSINPUTCONFIG.fields_by_name[ - "gcs_source" -].message_type = _IMPORTPRODUCTSETSGCSSOURCE -_IMPORTPRODUCTSETSINPUTCONFIG.oneofs_by_name["source"].fields.append( - _IMPORTPRODUCTSETSINPUTCONFIG.fields_by_name["gcs_source"] -) -_IMPORTPRODUCTSETSINPUTCONFIG.fields_by_name[ - "gcs_source" -].containing_oneof = _IMPORTPRODUCTSETSINPUTCONFIG.oneofs_by_name["source"] -_IMPORTPRODUCTSETSREQUEST.fields_by_name[ - "input_config" -].message_type = _IMPORTPRODUCTSETSINPUTCONFIG -_IMPORTPRODUCTSETSRESPONSE.fields_by_name[ - "reference_images" -].message_type = _REFERENCEIMAGE -_IMPORTPRODUCTSETSRESPONSE.fields_by_name[ - "statuses" -].message_type = google_dot_rpc_dot_status__pb2._STATUS -_BATCHOPERATIONMETADATA.fields_by_name[ - "state" -].enum_type = _BATCHOPERATIONMETADATA_STATE -_BATCHOPERATIONMETADATA.fields_by_name[ - "submit_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_BATCHOPERATIONMETADATA.fields_by_name[ - "end_time" -].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP -_BATCHOPERATIONMETADATA_STATE.containing_type = _BATCHOPERATIONMETADATA -_PURGEPRODUCTSREQUEST.fields_by_name[ - "product_set_purge_config" -].message_type = _PRODUCTSETPURGECONFIG -_PURGEPRODUCTSREQUEST.oneofs_by_name["target"].fields.append( - _PURGEPRODUCTSREQUEST.fields_by_name["product_set_purge_config"] -) -_PURGEPRODUCTSREQUEST.fields_by_name[ - "product_set_purge_config" -].containing_oneof = _PURGEPRODUCTSREQUEST.oneofs_by_name["target"] -_PURGEPRODUCTSREQUEST.oneofs_by_name["target"].fields.append( - _PURGEPRODUCTSREQUEST.fields_by_name["delete_orphan_products"] -) -_PURGEPRODUCTSREQUEST.fields_by_name[ - "delete_orphan_products" -].containing_oneof = _PURGEPRODUCTSREQUEST.oneofs_by_name["target"] -DESCRIPTOR.message_types_by_name["Product"] = _PRODUCT -DESCRIPTOR.message_types_by_name["ProductSet"] = _PRODUCTSET -DESCRIPTOR.message_types_by_name["ReferenceImage"] = _REFERENCEIMAGE -DESCRIPTOR.message_types_by_name["CreateProductRequest"] = _CREATEPRODUCTREQUEST -DESCRIPTOR.message_types_by_name["ListProductsRequest"] = _LISTPRODUCTSREQUEST -DESCRIPTOR.message_types_by_name["ListProductsResponse"] = _LISTPRODUCTSRESPONSE -DESCRIPTOR.message_types_by_name["GetProductRequest"] = _GETPRODUCTREQUEST -DESCRIPTOR.message_types_by_name["UpdateProductRequest"] = _UPDATEPRODUCTREQUEST -DESCRIPTOR.message_types_by_name["DeleteProductRequest"] = _DELETEPRODUCTREQUEST -DESCRIPTOR.message_types_by_name["CreateProductSetRequest"] = _CREATEPRODUCTSETREQUEST -DESCRIPTOR.message_types_by_name["ListProductSetsRequest"] = _LISTPRODUCTSETSREQUEST -DESCRIPTOR.message_types_by_name["ListProductSetsResponse"] = _LISTPRODUCTSETSRESPONSE -DESCRIPTOR.message_types_by_name["GetProductSetRequest"] = _GETPRODUCTSETREQUEST -DESCRIPTOR.message_types_by_name["UpdateProductSetRequest"] = _UPDATEPRODUCTSETREQUEST -DESCRIPTOR.message_types_by_name["DeleteProductSetRequest"] = _DELETEPRODUCTSETREQUEST -DESCRIPTOR.message_types_by_name[ - "CreateReferenceImageRequest" -] = _CREATEREFERENCEIMAGEREQUEST -DESCRIPTOR.message_types_by_name[ - "ListReferenceImagesRequest" -] = _LISTREFERENCEIMAGESREQUEST -DESCRIPTOR.message_types_by_name[ - "ListReferenceImagesResponse" -] = _LISTREFERENCEIMAGESRESPONSE -DESCRIPTOR.message_types_by_name["GetReferenceImageRequest"] = _GETREFERENCEIMAGEREQUEST -DESCRIPTOR.message_types_by_name[ - "DeleteReferenceImageRequest" -] = _DELETEREFERENCEIMAGEREQUEST -DESCRIPTOR.message_types_by_name[ - "AddProductToProductSetRequest" -] = _ADDPRODUCTTOPRODUCTSETREQUEST -DESCRIPTOR.message_types_by_name[ - "RemoveProductFromProductSetRequest" -] = _REMOVEPRODUCTFROMPRODUCTSETREQUEST -DESCRIPTOR.message_types_by_name[ - "ListProductsInProductSetRequest" -] = _LISTPRODUCTSINPRODUCTSETREQUEST -DESCRIPTOR.message_types_by_name[ - "ListProductsInProductSetResponse" -] = _LISTPRODUCTSINPRODUCTSETRESPONSE -DESCRIPTOR.message_types_by_name[ - "ImportProductSetsGcsSource" -] = _IMPORTPRODUCTSETSGCSSOURCE -DESCRIPTOR.message_types_by_name[ - "ImportProductSetsInputConfig" -] = _IMPORTPRODUCTSETSINPUTCONFIG -DESCRIPTOR.message_types_by_name["ImportProductSetsRequest"] = _IMPORTPRODUCTSETSREQUEST -DESCRIPTOR.message_types_by_name[ - "ImportProductSetsResponse" -] = _IMPORTPRODUCTSETSRESPONSE -DESCRIPTOR.message_types_by_name["BatchOperationMetadata"] = _BATCHOPERATIONMETADATA -DESCRIPTOR.message_types_by_name["ProductSetPurgeConfig"] = _PRODUCTSETPURGECONFIG -DESCRIPTOR.message_types_by_name["PurgeProductsRequest"] = _PURGEPRODUCTSREQUEST -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -Product = _reflection.GeneratedProtocolMessageType( - "Product", - (_message.Message,), - { - "KeyValue": _reflection.GeneratedProtocolMessageType( - "KeyValue", - (_message.Message,), - { - "DESCRIPTOR": _PRODUCT_KEYVALUE, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """A product label represented as a key-value pair. - - Attributes: - key: - The key of the label attached to the product. Cannot be empty - and cannot exceed 128 bytes. - value: - The value of the label attached to the product. Cannot be - empty and cannot exceed 128 bytes. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.Product.KeyValue) - }, - ), - "DESCRIPTOR": _PRODUCT, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """A Product contains ReferenceImages. - - Attributes: - name: - The resource name of the product. Format is: - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. - This field is ignored when creating a product. - display_name: - The user-provided name for this Product. Must not be empty. - Must be at most 4096 characters long. - description: - User-provided metadata to be stored with this product. Must be - at most 4096 characters long. - product_category: - Immutable. The category for the product identified by the - reference image. This should be either “homegoods-v2”, - “apparel-v2”, or “toys-v2”. The legacy categories “homegoods”, - “apparel”, and “toys” are still supported, but these should - not be used for new products. - product_labels: - Key-value pairs that can be attached to a product. At query - time, constraints can be specified based on the - product_labels. Note that integer values can be provided as - strings, e.g. “1199”. Only strings with integer values can - match a range-based restriction which is to be supported soon. - Multiple values can be assigned to the same key. One product - may have up to 500 product_labels. Notice that the total - number of distinct product_labels over all products in one - ProductSet cannot exceed 1M, otherwise the product search - pipeline will refuse to work for that ProductSet. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.Product) - }, -) -_sym_db.RegisterMessage(Product) -_sym_db.RegisterMessage(Product.KeyValue) - -ProductSet = _reflection.GeneratedProtocolMessageType( - "ProductSet", - (_message.Message,), - { - "DESCRIPTOR": _PRODUCTSET, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """A ProductSet contains Products. A ProductSet can contain a maximum of - 1 million reference images. If the limit is exceeded, periodic - indexing will fail. - - Attributes: - name: - The resource name of the ProductSet. Format is: ``projects/PR - OJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID``. This - field is ignored when creating a ProductSet. - display_name: - The user-provided name for this ProductSet. Must not be empty. - Must be at most 4096 characters long. - index_time: - Output only. The time at which this ProductSet was last - indexed. Query results will reflect all updates before this - time. If this ProductSet has never been indexed, this - timestamp is the default value “1970-01-01T00:00:00Z”. This - field is ignored when creating a ProductSet. - index_error: - Output only. If there was an error with indexing the product - set, the field is populated. This field is ignored when - creating a ProductSet. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ProductSet) - }, -) -_sym_db.RegisterMessage(ProductSet) - -ReferenceImage = _reflection.GeneratedProtocolMessageType( - "ReferenceImage", - (_message.Message,), - { - "DESCRIPTOR": _REFERENCEIMAGE, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """A ``ReferenceImage`` represents a product image and its associated - metadata, such as bounding boxes. - - Attributes: - name: - The resource name of the reference image. Format is: ``proje - cts/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceI - mages/IMAGE_ID``. This field is ignored when creating a - reference image. - uri: - Required. The Google Cloud Storage URI of the reference image. - The URI must start with ``gs://``. - bounding_polys: - Optional. Bounding polygons around the areas of interest in - the reference image. If this field is empty, the system will - try to detect regions of interest. At most 10 bounding - polygons will be used. The provided shape is converted into a - non-rotated rectangle. Once converted, the small edge of the - rectangle must be greater than or equal to 300 pixels. The - aspect ratio must be 1:4 or less (i.e. 1:3 is ok; 1:5 is not). - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ReferenceImage) - }, -) -_sym_db.RegisterMessage(ReferenceImage) - -CreateProductRequest = _reflection.GeneratedProtocolMessageType( - "CreateProductRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATEPRODUCTREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``CreateProduct`` method. - - Attributes: - parent: - Required. The project in which the Product should be created. - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - product: - Required. The product to create. - product_id: - A user-supplied resource id for this Product. If set, the - server will attempt to use this value as the resource id. If - it is already in use, an error is returned with code - ALREADY_EXISTS. Must be at most 128 characters long. It cannot - contain the character ``/``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.CreateProductRequest) - }, -) -_sym_db.RegisterMessage(CreateProductRequest) - -ListProductsRequest = _reflection.GeneratedProtocolMessageType( - "ListProductsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTPRODUCTSREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``ListProducts`` method. - - Attributes: - parent: - Required. The project OR ProductSet from which Products should - be listed. Format: ``projects/PROJECT_ID/locations/LOC_ID`` - page_size: - The maximum number of items to return. Default 10, maximum - 100. - page_token: - The next_page_token returned from a previous List request, if - any. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ListProductsRequest) - }, -) -_sym_db.RegisterMessage(ListProductsRequest) - -ListProductsResponse = _reflection.GeneratedProtocolMessageType( - "ListProductsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTPRODUCTSRESPONSE, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Response message for the ``ListProducts`` method. - - Attributes: - products: - List of products. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results in the list. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ListProductsResponse) - }, -) -_sym_db.RegisterMessage(ListProductsResponse) - -GetProductRequest = _reflection.GeneratedProtocolMessageType( - "GetProductRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETPRODUCTREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``GetProduct`` method. - - Attributes: - name: - Required. Resource name of the Product to get. Format is: - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.GetProductRequest) - }, -) -_sym_db.RegisterMessage(GetProductRequest) - -UpdateProductRequest = _reflection.GeneratedProtocolMessageType( - "UpdateProductRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATEPRODUCTREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``UpdateProduct`` method. - - Attributes: - product: - Required. The Product resource which replaces the one on the - server. product.name is immutable. - update_mask: - The [FieldMask][google.protobuf.FieldMask] that specifies - which fields to update. If update_mask isn’t specified, all - mutable fields are to be updated. Valid mask paths include - ``product_labels``, ``display_name``, and ``description``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.UpdateProductRequest) - }, -) -_sym_db.RegisterMessage(UpdateProductRequest) - -DeleteProductRequest = _reflection.GeneratedProtocolMessageType( - "DeleteProductRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETEPRODUCTREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``DeleteProduct`` method. - - Attributes: - name: - Required. Resource name of product to delete. Format is: - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.DeleteProductRequest) - }, -) -_sym_db.RegisterMessage(DeleteProductRequest) - -CreateProductSetRequest = _reflection.GeneratedProtocolMessageType( - "CreateProductSetRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATEPRODUCTSETREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``CreateProductSet`` method. - - Attributes: - parent: - Required. The project in which the ProductSet should be - created. Format is ``projects/PROJECT_ID/locations/LOC_ID``. - product_set: - Required. The ProductSet to create. - product_set_id: - A user-supplied resource id for this ProductSet. If set, the - server will attempt to use this value as the resource id. If - it is already in use, an error is returned with code - ALREADY_EXISTS. Must be at most 128 characters long. It cannot - contain the character ``/``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.CreateProductSetRequest) - }, -) -_sym_db.RegisterMessage(CreateProductSetRequest) - -ListProductSetsRequest = _reflection.GeneratedProtocolMessageType( - "ListProductSetsRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTPRODUCTSETSREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``ListProductSets`` method. - - Attributes: - parent: - Required. The project from which ProductSets should be listed. - Format is ``projects/PROJECT_ID/locations/LOC_ID``. - page_size: - The maximum number of items to return. Default 10, maximum - 100. - page_token: - The next_page_token returned from a previous List request, if - any. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ListProductSetsRequest) - }, -) -_sym_db.RegisterMessage(ListProductSetsRequest) - -ListProductSetsResponse = _reflection.GeneratedProtocolMessageType( - "ListProductSetsResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTPRODUCTSETSRESPONSE, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Response message for the ``ListProductSets`` method. - - Attributes: - product_sets: - List of ProductSets. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results in the list. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ListProductSetsResponse) - }, -) -_sym_db.RegisterMessage(ListProductSetsResponse) - -GetProductSetRequest = _reflection.GeneratedProtocolMessageType( - "GetProductSetRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETPRODUCTSETREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``GetProductSet`` method. - - Attributes: - name: - Required. Resource name of the ProductSet to get. Format is: - ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET - _ID`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.GetProductSetRequest) - }, -) -_sym_db.RegisterMessage(GetProductSetRequest) - -UpdateProductSetRequest = _reflection.GeneratedProtocolMessageType( - "UpdateProductSetRequest", - (_message.Message,), - { - "DESCRIPTOR": _UPDATEPRODUCTSETREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``UpdateProductSet`` method. - - Attributes: - product_set: - Required. The ProductSet resource which replaces the one on - the server. - update_mask: - The [FieldMask][google.protobuf.FieldMask] that specifies - which fields to update. If update_mask isn’t specified, all - mutable fields are to be updated. Valid mask path is - ``display_name``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.UpdateProductSetRequest) - }, -) -_sym_db.RegisterMessage(UpdateProductSetRequest) - -DeleteProductSetRequest = _reflection.GeneratedProtocolMessageType( - "DeleteProductSetRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETEPRODUCTSETREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``DeleteProductSet`` method. - - Attributes: - name: - Required. Resource name of the ProductSet to delete. Format - is: ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT - _SET_ID`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.DeleteProductSetRequest) - }, -) -_sym_db.RegisterMessage(DeleteProductSetRequest) - -CreateReferenceImageRequest = _reflection.GeneratedProtocolMessageType( - "CreateReferenceImageRequest", - (_message.Message,), - { - "DESCRIPTOR": _CREATEREFERENCEIMAGEREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``CreateReferenceImage`` method. - - Attributes: - parent: - Required. Resource name of the product in which to create the - reference image. Format is - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. - reference_image: - Required. The reference image to create. If an image ID is - specified, it is ignored. - reference_image_id: - A user-supplied resource id for the ReferenceImage to be - added. If set, the server will attempt to use this value as - the resource id. If it is already in use, an error is returned - with code ALREADY_EXISTS. Must be at most 128 characters long. - It cannot contain the character ``/``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.CreateReferenceImageRequest) - }, -) -_sym_db.RegisterMessage(CreateReferenceImageRequest) - -ListReferenceImagesRequest = _reflection.GeneratedProtocolMessageType( - "ListReferenceImagesRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTREFERENCEIMAGESREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``ListReferenceImages`` method. - - Attributes: - parent: - Required. Resource name of the product containing the - reference images. Format is - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. - page_size: - The maximum number of items to return. Default 10, maximum - 100. - page_token: - A token identifying a page of results to be returned. This is - the value of ``nextPageToken`` returned in a previous - reference image list request. Defaults to the first page if - not specified. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ListReferenceImagesRequest) - }, -) -_sym_db.RegisterMessage(ListReferenceImagesRequest) - -ListReferenceImagesResponse = _reflection.GeneratedProtocolMessageType( - "ListReferenceImagesResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTREFERENCEIMAGESRESPONSE, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Response message for the ``ListReferenceImages`` method. - - Attributes: - reference_images: - The list of reference images. - page_size: - The maximum number of items to return. Default 10, maximum - 100. - next_page_token: - The next_page_token returned from a previous List request, if - any. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ListReferenceImagesResponse) - }, -) -_sym_db.RegisterMessage(ListReferenceImagesResponse) - -GetReferenceImageRequest = _reflection.GeneratedProtocolMessageType( - "GetReferenceImageRequest", - (_message.Message,), - { - "DESCRIPTOR": _GETREFERENCEIMAGEREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``GetReferenceImage`` method. - - Attributes: - name: - Required. The resource name of the ReferenceImage to get. - Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PR - ODUCT_ID/referenceImages/IMAGE_ID``. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.GetReferenceImageRequest) - }, -) -_sym_db.RegisterMessage(GetReferenceImageRequest) - -DeleteReferenceImageRequest = _reflection.GeneratedProtocolMessageType( - "DeleteReferenceImageRequest", - (_message.Message,), - { - "DESCRIPTOR": _DELETEREFERENCEIMAGEREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``DeleteReferenceImage`` method. - - Attributes: - name: - Required. The resource name of the reference image to delete. - Format is: ``projects/PROJECT_ID/locations/LOC_ID/products/PR - ODUCT_ID/referenceImages/IMAGE_ID`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.DeleteReferenceImageRequest) - }, -) -_sym_db.RegisterMessage(DeleteReferenceImageRequest) - -AddProductToProductSetRequest = _reflection.GeneratedProtocolMessageType( - "AddProductToProductSetRequest", - (_message.Message,), - { - "DESCRIPTOR": _ADDPRODUCTTOPRODUCTSETREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``AddProductToProductSet`` method. - - Attributes: - name: - Required. The resource name for the ProductSet to modify. - Format is: ``projects/PROJECT_ID/locations/LOC_ID/productSets/ - PRODUCT_SET_ID`` - product: - Required. The resource name for the Product to be added to - this ProductSet. Format is: - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.AddProductToProductSetRequest) - }, -) -_sym_db.RegisterMessage(AddProductToProductSetRequest) - -RemoveProductFromProductSetRequest = _reflection.GeneratedProtocolMessageType( - "RemoveProductFromProductSetRequest", - (_message.Message,), - { - "DESCRIPTOR": _REMOVEPRODUCTFROMPRODUCTSETREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``RemoveProductFromProductSet`` method. - - Attributes: - name: - Required. The resource name for the ProductSet to modify. - Format is: ``projects/PROJECT_ID/locations/LOC_ID/productSets/ - PRODUCT_SET_ID`` - product: - Required. The resource name for the Product to be removed from - this ProductSet. Format is: - ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.RemoveProductFromProductSetRequest) - }, -) -_sym_db.RegisterMessage(RemoveProductFromProductSetRequest) - -ListProductsInProductSetRequest = _reflection.GeneratedProtocolMessageType( - "ListProductsInProductSetRequest", - (_message.Message,), - { - "DESCRIPTOR": _LISTPRODUCTSINPRODUCTSETREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``ListProductsInProductSet`` method. - - Attributes: - name: - Required. The ProductSet resource for which to retrieve - Products. Format is: ``projects/PROJECT_ID/locations/LOC_ID/p - roductSets/PRODUCT_SET_ID`` - page_size: - The maximum number of items to return. Default 10, maximum - 100. - page_token: - The next_page_token returned from a previous List request, if - any. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ListProductsInProductSetRequest) - }, -) -_sym_db.RegisterMessage(ListProductsInProductSetRequest) - -ListProductsInProductSetResponse = _reflection.GeneratedProtocolMessageType( - "ListProductsInProductSetResponse", - (_message.Message,), - { - "DESCRIPTOR": _LISTPRODUCTSINPRODUCTSETRESPONSE, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Response message for the ``ListProductsInProductSet`` method. - - Attributes: - products: - The list of Products. - next_page_token: - Token to retrieve the next page of results, or empty if there - are no more results in the list. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse) - }, -) -_sym_db.RegisterMessage(ListProductsInProductSetResponse) - -ImportProductSetsGcsSource = _reflection.GeneratedProtocolMessageType( - "ImportProductSetsGcsSource", - (_message.Message,), - { - "DESCRIPTOR": _IMPORTPRODUCTSETSGCSSOURCE, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """The Google Cloud Storage location for a csv file which preserves a - list of ImportProductSetRequests in each line. - - Attributes: - csv_file_uri: - The Google Cloud Storage URI of the input csv file. The URI - must start with ``gs://``. The format of the input csv file - should be one image per line. In each line, there are 8 - columns. 1. image-uri 2. image-id 3. product-set-id 4. - product-id 5. product-category 6. product-display-name 7. - labels 8. bounding-poly The ``image-uri``, ``product-set- - id``, ``product-id``, and ``product-category`` columns are - required. All other columns are optional. If the - ``ProductSet`` or ``Product`` specified by the ``product-set- - id`` and ``product-id`` values does not exist, then the system - will create a new ``ProductSet`` or ``Product`` for the image. - In this case, the ``product-display-name`` column refers to [d - isplay_name][google.cloud.vision.v1p4beta1.Product.display_nam - e], the ``product-category`` column refers to [product_categor - y][google.cloud.vision.v1p4beta1.Product.product_category], - and the ``labels`` column refers to [product_labels][google.cl - oud.vision.v1p4beta1.Product.product_labels]. The ``image- - id`` column is optional but must be unique if provided. If it - is empty, the system will automatically assign a unique id to - the image. The ``product-display-name`` column is optional. - If it is empty, the system sets the [display_name][google.clou - d.vision.v1p4beta1.Product.display_name] field for the product - to a space (" "). You can update the ``display_name`` later by - using the API. If a ``Product`` with the specified ``product- - id`` already exists, then the system ignores the ``product- - display-name``, ``product-category``, and ``labels`` columns. - The ``labels`` column (optional) is a line containing a list - of comma-separated key-value pairs, in the following format: - :: "key_1=value_1,key_2=value_2,...,key_n=value_n" The - ``bounding-poly`` column (optional) identifies one region of - interest from the image in the same manner as - ``CreateReferenceImage``. If you do not specify the - ``bounding-poly`` column, then the system will try to detect - regions of interest automatically. At most one ``bounding- - poly`` column is allowed per line. If the image contains - multiple regions of interest, add a line to the CSV file that - includes the same product information, and the ``bounding- - poly`` values for each region of interest. The ``bounding- - poly`` column must contain an even number of comma-separated - numbers, in the format “p1_x,p1_y,p2_x,p2_y,…,pn_x,pn_y”. Use - non-negative integers for absolute bounding polygons, and - float values in [0, 1] for normalized bounding polygons. The - system will resize the image if the image resolution is too - large to process (larger than 20MP). - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ImportProductSetsGcsSource) - }, -) -_sym_db.RegisterMessage(ImportProductSetsGcsSource) - -ImportProductSetsInputConfig = _reflection.GeneratedProtocolMessageType( - "ImportProductSetsInputConfig", - (_message.Message,), - { - "DESCRIPTOR": _IMPORTPRODUCTSETSINPUTCONFIG, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """The input content for the ``ImportProductSets`` method. - - Attributes: - source: - The source of the input. - gcs_source: - The Google Cloud Storage location for a csv file which - preserves a list of ImportProductSetRequests in each line. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ImportProductSetsInputConfig) - }, -) -_sym_db.RegisterMessage(ImportProductSetsInputConfig) - -ImportProductSetsRequest = _reflection.GeneratedProtocolMessageType( - "ImportProductSetsRequest", - (_message.Message,), - { - "DESCRIPTOR": _IMPORTPRODUCTSETSREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``ImportProductSets`` method. - - Attributes: - parent: - Required. The project in which the ProductSets should be - imported. Format is ``projects/PROJECT_ID/locations/LOC_ID``. - input_config: - Required. The input content for the list of requests. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ImportProductSetsRequest) - }, -) -_sym_db.RegisterMessage(ImportProductSetsRequest) - -ImportProductSetsResponse = _reflection.GeneratedProtocolMessageType( - "ImportProductSetsResponse", - (_message.Message,), - { - "DESCRIPTOR": _IMPORTPRODUCTSETSRESPONSE, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Response message for the ``ImportProductSets`` method. This message - is returned by the [google.longrunning.Operations.GetOperation][google - .longrunning.Operations.GetOperation] method in the returned [google.l - ongrunning.Operation.response][google.longrunning.Operation.response] - field. - - Attributes: - reference_images: - The list of reference_images that are imported successfully. - statuses: - The rpc status for each ImportProductSet request, including - both successes and errors. The number of statuses here - matches the number of lines in the csv file, and statuses[i] - stores the success or failure status of processing the i-th - line of the csv, starting from line 0. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ImportProductSetsResponse) - }, -) -_sym_db.RegisterMessage(ImportProductSetsResponse) - -BatchOperationMetadata = _reflection.GeneratedProtocolMessageType( - "BatchOperationMetadata", - (_message.Message,), - { - "DESCRIPTOR": _BATCHOPERATIONMETADATA, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Metadata for the batch operations such as the current state. This is - included in the ``metadata`` field of the ``Operation`` returned by - the ``GetOperation`` call of the ``google::longrunning::Operations`` - service. - - Attributes: - state: - The current state of the batch operation. - submit_time: - The time when the batch request was submitted to the server. - end_time: - The time when the batch request is finished and [google.longru - nning.Operation.done][google.longrunning.Operation.done] is - set to true. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.BatchOperationMetadata) - }, -) -_sym_db.RegisterMessage(BatchOperationMetadata) - -ProductSetPurgeConfig = _reflection.GeneratedProtocolMessageType( - "ProductSetPurgeConfig", - (_message.Message,), - { - "DESCRIPTOR": _PRODUCTSETPURGECONFIG, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Config to control which ProductSet contains the Products to be - deleted. - - Attributes: - product_set_id: - The ProductSet that contains the Products to delete. If a - Product is a member of product_set_id in addition to other - ProductSets, the Product will still be deleted. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ProductSetPurgeConfig) - }, -) -_sym_db.RegisterMessage(ProductSetPurgeConfig) - -PurgeProductsRequest = _reflection.GeneratedProtocolMessageType( - "PurgeProductsRequest", - (_message.Message,), - { - "DESCRIPTOR": _PURGEPRODUCTSREQUEST, - "__module__": "google.cloud.vision_v1p4beta1.proto.product_search_service_pb2", - "__doc__": """Request message for the ``PurgeProducts`` method. - - Attributes: - target: - The Products to delete. - product_set_purge_config: - Specify which ProductSet contains the Products to be deleted. - delete_orphan_products: - If delete_orphan_products is true, all Products that are not - in any ProductSet will be deleted. - parent: - Required. The project and location in which the Products - should be deleted. Format is - ``projects/PROJECT_ID/locations/LOC_ID``. - force: - The default value is false. Override this value to true to - actually perform the purge. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.PurgeProductsRequest) - }, -) -_sym_db.RegisterMessage(PurgeProductsRequest) - - -DESCRIPTOR._options = None -_PRODUCT.fields_by_name["product_category"]._options = None -_PRODUCT._options = None -_PRODUCTSET.fields_by_name["index_time"]._options = None -_PRODUCTSET.fields_by_name["index_error"]._options = None -_PRODUCTSET._options = None -_REFERENCEIMAGE.fields_by_name["uri"]._options = None -_REFERENCEIMAGE.fields_by_name["bounding_polys"]._options = None -_REFERENCEIMAGE._options = None -_CREATEPRODUCTREQUEST.fields_by_name["parent"]._options = None -_CREATEPRODUCTREQUEST.fields_by_name["product"]._options = None -_LISTPRODUCTSREQUEST.fields_by_name["parent"]._options = None -_GETPRODUCTREQUEST.fields_by_name["name"]._options = None -_UPDATEPRODUCTREQUEST.fields_by_name["product"]._options = None -_DELETEPRODUCTREQUEST.fields_by_name["name"]._options = None -_CREATEPRODUCTSETREQUEST.fields_by_name["parent"]._options = None -_CREATEPRODUCTSETREQUEST.fields_by_name["product_set"]._options = None -_LISTPRODUCTSETSREQUEST.fields_by_name["parent"]._options = None -_GETPRODUCTSETREQUEST.fields_by_name["name"]._options = None -_UPDATEPRODUCTSETREQUEST.fields_by_name["product_set"]._options = None -_DELETEPRODUCTSETREQUEST.fields_by_name["name"]._options = None -_CREATEREFERENCEIMAGEREQUEST.fields_by_name["parent"]._options = None -_CREATEREFERENCEIMAGEREQUEST.fields_by_name["reference_image"]._options = None -_LISTREFERENCEIMAGESREQUEST.fields_by_name["parent"]._options = None -_GETREFERENCEIMAGEREQUEST.fields_by_name["name"]._options = None -_DELETEREFERENCEIMAGEREQUEST.fields_by_name["name"]._options = None -_ADDPRODUCTTOPRODUCTSETREQUEST.fields_by_name["name"]._options = None -_ADDPRODUCTTOPRODUCTSETREQUEST.fields_by_name["product"]._options = None -_REMOVEPRODUCTFROMPRODUCTSETREQUEST.fields_by_name["name"]._options = None -_REMOVEPRODUCTFROMPRODUCTSETREQUEST.fields_by_name["product"]._options = None -_LISTPRODUCTSINPRODUCTSETREQUEST.fields_by_name["name"]._options = None -_IMPORTPRODUCTSETSREQUEST.fields_by_name["parent"]._options = None -_IMPORTPRODUCTSETSREQUEST.fields_by_name["input_config"]._options = None -_PURGEPRODUCTSREQUEST.fields_by_name["parent"]._options = None - -_PRODUCTSEARCH = _descriptor.ServiceDescriptor( - name="ProductSearch", - full_name="google.cloud.vision.v1p4beta1.ProductSearch", - file=DESCRIPTOR, - index=0, - serialized_options=b"\312A\025vision.googleapis.com\322A[https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/cloud-vision", - create_key=_descriptor._internal_create_key, - serialized_start=4919, - serialized_end=9097, - methods=[ - _descriptor.MethodDescriptor( - name="CreateProductSet", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.CreateProductSet", - index=0, - containing_service=None, - input_type=_CREATEPRODUCTSETREQUEST, - output_type=_PRODUCTSET, - serialized_options=b'\202\323\344\223\002E"6/v1p4beta1/{parent=projects/*/locations/*}/productSets:\013product_set\332A!parent,product_set,product_set_id', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListProductSets", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.ListProductSets", - index=1, - containing_service=None, - input_type=_LISTPRODUCTSETSREQUEST, - output_type=_LISTPRODUCTSETSRESPONSE, - serialized_options=b"\202\323\344\223\0028\0226/v1p4beta1/{parent=projects/*/locations/*}/productSets\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetProductSet", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.GetProductSet", - index=2, - containing_service=None, - input_type=_GETPRODUCTSETREQUEST, - output_type=_PRODUCTSET, - serialized_options=b"\202\323\344\223\0028\0226/v1p4beta1/{name=projects/*/locations/*/productSets/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateProductSet", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.UpdateProductSet", - index=3, - containing_service=None, - input_type=_UPDATEPRODUCTSETREQUEST, - output_type=_PRODUCTSET, - serialized_options=b"\202\323\344\223\002Q2B/v1p4beta1/{product_set.name=projects/*/locations/*/productSets/*}:\013product_set\332A\027product_set,update_mask", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteProductSet", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.DeleteProductSet", - index=4, - containing_service=None, - input_type=_DELETEPRODUCTSETREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\0028*6/v1p4beta1/{name=projects/*/locations/*/productSets/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateProduct", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.CreateProduct", - index=5, - containing_service=None, - input_type=_CREATEPRODUCTREQUEST, - output_type=_PRODUCT, - serialized_options=b'\202\323\344\223\002>"3/v1p4beta1/{parent=projects/*/locations/*}/products:\007product\332A\031parent,product,product_id', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListProducts", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.ListProducts", - index=6, - containing_service=None, - input_type=_LISTPRODUCTSREQUEST, - output_type=_LISTPRODUCTSRESPONSE, - serialized_options=b"\202\323\344\223\0025\0223/v1p4beta1/{parent=projects/*/locations/*}/products\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetProduct", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.GetProduct", - index=7, - containing_service=None, - input_type=_GETPRODUCTREQUEST, - output_type=_PRODUCT, - serialized_options=b"\202\323\344\223\0025\0223/v1p4beta1/{name=projects/*/locations/*/products/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="UpdateProduct", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.UpdateProduct", - index=8, - containing_service=None, - input_type=_UPDATEPRODUCTREQUEST, - output_type=_PRODUCT, - serialized_options=b"\202\323\344\223\002F2;/v1p4beta1/{product.name=projects/*/locations/*/products/*}:\007product\332A\023product,update_mask", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteProduct", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.DeleteProduct", - index=9, - containing_service=None, - input_type=_DELETEPRODUCTREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\0025*3/v1p4beta1/{name=projects/*/locations/*/products/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="CreateReferenceImage", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.CreateReferenceImage", - index=10, - containing_service=None, - input_type=_CREATEREFERENCEIMAGEREQUEST, - output_type=_REFERENCEIMAGE, - serialized_options=b'\202\323\344\223\002X"E/v1p4beta1/{parent=projects/*/locations/*/products/*}/referenceImages:\017reference_image\332A)parent,reference_image,reference_image_id', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="DeleteReferenceImage", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.DeleteReferenceImage", - index=11, - containing_service=None, - input_type=_DELETEREFERENCEIMAGEREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b"\202\323\344\223\002G*E/v1p4beta1/{name=projects/*/locations/*/products/*/referenceImages/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListReferenceImages", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.ListReferenceImages", - index=12, - containing_service=None, - input_type=_LISTREFERENCEIMAGESREQUEST, - output_type=_LISTREFERENCEIMAGESRESPONSE, - serialized_options=b"\202\323\344\223\002G\022E/v1p4beta1/{parent=projects/*/locations/*/products/*}/referenceImages\332A\006parent", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="GetReferenceImage", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.GetReferenceImage", - index=13, - containing_service=None, - input_type=_GETREFERENCEIMAGEREQUEST, - output_type=_REFERENCEIMAGE, - serialized_options=b"\202\323\344\223\002G\022E/v1p4beta1/{name=projects/*/locations/*/products/*/referenceImages/*}\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="AddProductToProductSet", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.AddProductToProductSet", - index=14, - containing_service=None, - input_type=_ADDPRODUCTTOPRODUCTSETREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b'\202\323\344\223\002F"A/v1p4beta1/{name=projects/*/locations/*/productSets/*}:addProduct:\001*\332A\014name,product', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="RemoveProductFromProductSet", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.RemoveProductFromProductSet", - index=15, - containing_service=None, - input_type=_REMOVEPRODUCTFROMPRODUCTSETREQUEST, - output_type=google_dot_protobuf_dot_empty__pb2._EMPTY, - serialized_options=b'\202\323\344\223\002I"D/v1p4beta1/{name=projects/*/locations/*/productSets/*}:removeProduct:\001*\332A\014name,product', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ListProductsInProductSet", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.ListProductsInProductSet", - index=16, - containing_service=None, - input_type=_LISTPRODUCTSINPRODUCTSETREQUEST, - output_type=_LISTPRODUCTSINPRODUCTSETRESPONSE, - serialized_options=b"\202\323\344\223\002A\022?/v1p4beta1/{name=projects/*/locations/*/productSets/*}/products\332A\004name", - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="ImportProductSets", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.ImportProductSets", - index=17, - containing_service=None, - input_type=_IMPORTPRODUCTSETSREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002B"=/v1p4beta1/{parent=projects/*/locations/*}/productSets:import:\001*\332A\023parent,input_config\312A3\n\031ImportProductSetsResponse\022\026BatchOperationMetadata', - create_key=_descriptor._internal_create_key, - ), - _descriptor.MethodDescriptor( - name="PurgeProducts", - full_name="google.cloud.vision.v1p4beta1.ProductSearch.PurgeProducts", - index=18, - containing_service=None, - input_type=_PURGEPRODUCTSREQUEST, - output_type=google_dot_longrunning_dot_operations__pb2._OPERATION, - serialized_options=b'\202\323\344\223\002>"9/v1p4beta1/{parent=projects/*/locations/*}/products:purge:\001*\332A\006parent\312A/\n\025google.protobuf.Empty\022\026BatchOperationMetadata', - create_key=_descriptor._internal_create_key, - ), - ], -) -_sym_db.RegisterServiceDescriptor(_PRODUCTSEARCH) - -DESCRIPTOR.services_by_name["ProductSearch"] = _PRODUCTSEARCH - -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p4beta1/proto/product_search_service_pb2_grpc.py b/google/cloud/vision_v1p4beta1/proto/product_search_service_pb2_grpc.py deleted file mode 100644 index 542268e6..00000000 --- a/google/cloud/vision_v1p4beta1/proto/product_search_service_pb2_grpc.py +++ /dev/null @@ -1,1067 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc - -from google.cloud.vision_v1p4beta1.proto import ( - product_search_service_pb2 as google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2, -) -from google.longrunning import ( - operations_pb2 as google_dot_longrunning_dot_operations__pb2, -) -from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 - - -class ProductSearchStub(object): - """Manages Products and ProductSets of reference images for use in product - search. It uses the following resource model: - - - The API has a collection of - [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, named - `projects/*/locations/*/productSets/*`, which acts as a way to put different - products into groups to limit identification. - - In parallel, - - - The API has a collection of - [Product][google.cloud.vision.v1p4beta1.Product] resources, named - `projects/*/locations/*/products/*` - - - Each [Product][google.cloud.vision.v1p4beta1.Product] has a collection of - [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] resources, - named - `projects/*/locations/*/products/*/referenceImages/*` - """ - - def __init__(self, channel): - """Constructor. - - Args: - channel: A grpc.Channel. - """ - self.CreateProductSet = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/CreateProductSet", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.CreateProductSetRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - ) - self.ListProductSets = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/ListProductSets", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductSetsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductSetsResponse.FromString, - ) - self.GetProductSet = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/GetProductSet", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.GetProductSetRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - ) - self.UpdateProductSet = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/UpdateProductSet", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.UpdateProductSetRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - ) - self.DeleteProductSet = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteProductSet", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.DeleteProductSetRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.CreateProduct = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/CreateProduct", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.CreateProductRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.Product.FromString, - ) - self.ListProducts = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/ListProducts", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductsRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductsResponse.FromString, - ) - self.GetProduct = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/GetProduct", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.GetProductRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.Product.FromString, - ) - self.UpdateProduct = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/UpdateProduct", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.UpdateProductRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.Product.FromString, - ) - self.DeleteProduct = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteProduct", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.DeleteProductRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.CreateReferenceImage = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/CreateReferenceImage", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.CreateReferenceImageRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ReferenceImage.FromString, - ) - self.DeleteReferenceImage = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteReferenceImage", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.DeleteReferenceImageRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.ListReferenceImages = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/ListReferenceImages", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesResponse.FromString, - ) - self.GetReferenceImage = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/GetReferenceImage", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.GetReferenceImageRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ReferenceImage.FromString, - ) - self.AddProductToProductSet = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/AddProductToProductSet", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.AddProductToProductSetRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.RemoveProductFromProductSet = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/RemoveProductFromProductSet", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.RemoveProductFromProductSetRequest.SerializeToString, - response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, - ) - self.ListProductsInProductSet = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/ListProductsInProductSet", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetRequest.SerializeToString, - response_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetResponse.FromString, - ) - self.ImportProductSets = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/ImportProductSets", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ImportProductSetsRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - self.PurgeProducts = channel.unary_unary( - "/google.cloud.vision.v1p4beta1.ProductSearch/PurgeProducts", - request_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.PurgeProductsRequest.SerializeToString, - response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, - ) - - -class ProductSearchServicer(object): - """Manages Products and ProductSets of reference images for use in product - search. It uses the following resource model: - - - The API has a collection of - [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, named - `projects/*/locations/*/productSets/*`, which acts as a way to put different - products into groups to limit identification. - - In parallel, - - - The API has a collection of - [Product][google.cloud.vision.v1p4beta1.Product] resources, named - `projects/*/locations/*/products/*` - - - Each [Product][google.cloud.vision.v1p4beta1.Product] has a collection of - [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] resources, - named - `projects/*/locations/*/products/*/referenceImages/*` - """ - - def CreateProductSet(self, request, context): - """Creates and returns a new ProductSet resource. - - Possible errors: - - * Returns INVALID_ARGUMENT if display_name is missing, or is longer than - 4096 characters. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListProductSets(self, request, context): - """Lists ProductSets in an unspecified order. - - Possible errors: - - * Returns INVALID_ARGUMENT if page_size is greater than 100, or less - than 1. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetProductSet(self, request, context): - """Gets information associated with a ProductSet. - - Possible errors: - - * Returns NOT_FOUND if the ProductSet does not exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateProductSet(self, request, context): - """Makes changes to a ProductSet resource. - Only display_name can be updated currently. - - Possible errors: - - * Returns NOT_FOUND if the ProductSet does not exist. - * Returns INVALID_ARGUMENT if display_name is present in update_mask but - missing from the request or longer than 4096 characters. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteProductSet(self, request, context): - """Permanently deletes a ProductSet. Products and ReferenceImages in the - ProductSet are not deleted. - - The actual image files are not deleted from Google Cloud Storage. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateProduct(self, request, context): - """Creates and returns a new product resource. - - Possible errors: - - * Returns INVALID_ARGUMENT if display_name is missing or longer than 4096 - characters. - * Returns INVALID_ARGUMENT if description is longer than 4096 characters. - * Returns INVALID_ARGUMENT if product_category is missing or invalid. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListProducts(self, request, context): - """Lists products in an unspecified order. - - Possible errors: - - * Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetProduct(self, request, context): - """Gets information associated with a Product. - - Possible errors: - - * Returns NOT_FOUND if the Product does not exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def UpdateProduct(self, request, context): - """Makes changes to a Product resource. - Only the `display_name`, `description`, and `labels` fields can be updated - right now. - - If labels are updated, the change will not be reflected in queries until - the next index time. - - Possible errors: - - * Returns NOT_FOUND if the Product does not exist. - * Returns INVALID_ARGUMENT if display_name is present in update_mask but is - missing from the request or longer than 4096 characters. - * Returns INVALID_ARGUMENT if description is present in update_mask but is - longer than 4096 characters. - * Returns INVALID_ARGUMENT if product_category is present in update_mask. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteProduct(self, request, context): - """Permanently deletes a product and its reference images. - - Metadata of the product and all its images will be deleted right away, but - search queries against ProductSets containing the product may still work - until all related caches are refreshed. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def CreateReferenceImage(self, request, context): - """Creates and returns a new ReferenceImage resource. - - The `bounding_poly` field is optional. If `bounding_poly` is not specified, - the system will try to detect regions of interest in the image that are - compatible with the product_category on the parent product. If it is - specified, detection is ALWAYS skipped. The system converts polygons into - non-rotated rectangles. - - Note that the pipeline will resize the image if the image resolution is too - large to process (above 50MP). - - Possible errors: - - * Returns INVALID_ARGUMENT if the image_uri is missing or longer than 4096 - characters. - * Returns INVALID_ARGUMENT if the product does not exist. - * Returns INVALID_ARGUMENT if bounding_poly is not provided, and nothing - compatible with the parent product's product_category is detected. - * Returns INVALID_ARGUMENT if bounding_poly contains more than 10 polygons. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def DeleteReferenceImage(self, request, context): - """Permanently deletes a reference image. - - The image metadata will be deleted right away, but search queries - against ProductSets containing the image may still work until all related - caches are refreshed. - - The actual image files are not deleted from Google Cloud Storage. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListReferenceImages(self, request, context): - """Lists reference images. - - Possible errors: - - * Returns NOT_FOUND if the parent product does not exist. - * Returns INVALID_ARGUMENT if the page_size is greater than 100, or less - than 1. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def GetReferenceImage(self, request, context): - """Gets information associated with a ReferenceImage. - - Possible errors: - - * Returns NOT_FOUND if the specified image does not exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def AddProductToProductSet(self, request, context): - """Adds a Product to the specified ProductSet. If the Product is already - present, no change is made. - - One Product can be added to at most 100 ProductSets. - - Possible errors: - - * Returns NOT_FOUND if the Product or the ProductSet doesn't exist. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def RemoveProductFromProductSet(self, request, context): - """Removes a Product from the specified ProductSet. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ListProductsInProductSet(self, request, context): - """Lists the Products in a ProductSet, in an unspecified order. If the - ProductSet does not exist, the products field of the response will be - empty. - - Possible errors: - - * Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def ImportProductSets(self, request, context): - """Asynchronous API that imports a list of reference images to specified - product sets based on a list of image information. - - The [google.longrunning.Operation][google.longrunning.Operation] API can be - used to keep track of the progress and results of the request. - `Operation.metadata` contains `BatchOperationMetadata`. (progress) - `Operation.response` contains `ImportProductSetsResponse`. (results) - - The input source of this method is a csv file on Google Cloud Storage. - For the format of the csv file please see - [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1p4beta1.ImportProductSetsGcsSource.csv_file_uri]. - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - def PurgeProducts(self, request, context): - """Asynchronous API to delete all Products in a ProductSet or all Products - that are in no ProductSet. - - If a Product is a member of the specified ProductSet in addition to other - ProductSets, the Product will still be deleted. - - It is recommended to not delete the specified ProductSet until after this - operation has completed. It is also recommended to not add any of the - Products involved in the batch delete to a new ProductSet while this - operation is running because those Products may still end up deleted. - - It's not possible to undo the PurgeProducts operation. Therefore, it is - recommended to keep the csv files used in ImportProductSets (if that was - how you originally built the Product Set) before starting PurgeProducts, in - case you need to re-import the data after deletion. - - If the plan is to purge all of the Products from a ProductSet and then - re-use the empty ProductSet to re-import new Products into the empty - ProductSet, you must wait until the PurgeProducts operation has finished - for that ProductSet. - - The [google.longrunning.Operation][google.longrunning.Operation] API can be - used to keep track of the progress and results of the request. - `Operation.metadata` contains `BatchOperationMetadata`. (progress) - """ - context.set_code(grpc.StatusCode.UNIMPLEMENTED) - context.set_details("Method not implemented!") - raise NotImplementedError("Method not implemented!") - - -def add_ProductSearchServicer_to_server(servicer, server): - rpc_method_handlers = { - "CreateProductSet": grpc.unary_unary_rpc_method_handler( - servicer.CreateProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.CreateProductSetRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ProductSet.SerializeToString, - ), - "ListProductSets": grpc.unary_unary_rpc_method_handler( - servicer.ListProductSets, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductSetsRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductSetsResponse.SerializeToString, - ), - "GetProductSet": grpc.unary_unary_rpc_method_handler( - servicer.GetProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.GetProductSetRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ProductSet.SerializeToString, - ), - "UpdateProductSet": grpc.unary_unary_rpc_method_handler( - servicer.UpdateProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.UpdateProductSetRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ProductSet.SerializeToString, - ), - "DeleteProductSet": grpc.unary_unary_rpc_method_handler( - servicer.DeleteProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.DeleteProductSetRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "CreateProduct": grpc.unary_unary_rpc_method_handler( - servicer.CreateProduct, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.CreateProductRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.Product.SerializeToString, - ), - "ListProducts": grpc.unary_unary_rpc_method_handler( - servicer.ListProducts, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductsRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductsResponse.SerializeToString, - ), - "GetProduct": grpc.unary_unary_rpc_method_handler( - servicer.GetProduct, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.GetProductRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.Product.SerializeToString, - ), - "UpdateProduct": grpc.unary_unary_rpc_method_handler( - servicer.UpdateProduct, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.UpdateProductRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.Product.SerializeToString, - ), - "DeleteProduct": grpc.unary_unary_rpc_method_handler( - servicer.DeleteProduct, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.DeleteProductRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "CreateReferenceImage": grpc.unary_unary_rpc_method_handler( - servicer.CreateReferenceImage, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.CreateReferenceImageRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ReferenceImage.SerializeToString, - ), - "DeleteReferenceImage": grpc.unary_unary_rpc_method_handler( - servicer.DeleteReferenceImage, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.DeleteReferenceImageRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "ListReferenceImages": grpc.unary_unary_rpc_method_handler( - servicer.ListReferenceImages, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesResponse.SerializeToString, - ), - "GetReferenceImage": grpc.unary_unary_rpc_method_handler( - servicer.GetReferenceImage, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.GetReferenceImageRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ReferenceImage.SerializeToString, - ), - "AddProductToProductSet": grpc.unary_unary_rpc_method_handler( - servicer.AddProductToProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.AddProductToProductSetRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "RemoveProductFromProductSet": grpc.unary_unary_rpc_method_handler( - servicer.RemoveProductFromProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.RemoveProductFromProductSetRequest.FromString, - response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, - ), - "ListProductsInProductSet": grpc.unary_unary_rpc_method_handler( - servicer.ListProductsInProductSet, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetRequest.FromString, - response_serializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetResponse.SerializeToString, - ), - "ImportProductSets": grpc.unary_unary_rpc_method_handler( - servicer.ImportProductSets, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ImportProductSetsRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - "PurgeProducts": grpc.unary_unary_rpc_method_handler( - servicer.PurgeProducts, - request_deserializer=google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.PurgeProductsRequest.FromString, - response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, - ), - } - generic_handler = grpc.method_handlers_generic_handler( - "google.cloud.vision.v1p4beta1.ProductSearch", rpc_method_handlers - ) - server.add_generic_rpc_handlers((generic_handler,)) - - -# This class is part of an EXPERIMENTAL API. -class ProductSearch(object): - """Manages Products and ProductSets of reference images for use in product - search. It uses the following resource model: - - - The API has a collection of - [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, named - `projects/*/locations/*/productSets/*`, which acts as a way to put different - products into groups to limit identification. - - In parallel, - - - The API has a collection of - [Product][google.cloud.vision.v1p4beta1.Product] resources, named - `projects/*/locations/*/products/*` - - - Each [Product][google.cloud.vision.v1p4beta1.Product] has a collection of - [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] resources, - named - `projects/*/locations/*/products/*/referenceImages/*` - """ - - @staticmethod - def CreateProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/CreateProductSet", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.CreateProductSetRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListProductSets( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/ListProductSets", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductSetsRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductSetsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/GetProductSet", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.GetProductSetRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/UpdateProductSet", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.UpdateProductSetRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ProductSet.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteProductSet", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.DeleteProductSetRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def CreateProduct( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/CreateProduct", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.CreateProductRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.Product.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListProducts( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/ListProducts", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductsRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductsResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetProduct( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/GetProduct", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.GetProductRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.Product.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def UpdateProduct( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/UpdateProduct", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.UpdateProductRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.Product.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteProduct( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteProduct", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.DeleteProductRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def CreateReferenceImage( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/CreateReferenceImage", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.CreateReferenceImageRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ReferenceImage.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def DeleteReferenceImage( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteReferenceImage", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.DeleteReferenceImageRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListReferenceImages( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/ListReferenceImages", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListReferenceImagesResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def GetReferenceImage( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/GetReferenceImage", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.GetReferenceImageRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ReferenceImage.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def AddProductToProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/AddProductToProductSet", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.AddProductToProductSetRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def RemoveProductFromProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/RemoveProductFromProductSet", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.RemoveProductFromProductSetRequest.SerializeToString, - google_dot_protobuf_dot_empty__pb2.Empty.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ListProductsInProductSet( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/ListProductsInProductSet", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetRequest.SerializeToString, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ListProductsInProductSetResponse.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def ImportProductSets( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/ImportProductSets", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.ImportProductSetsRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) - - @staticmethod - def PurgeProducts( - request, - target, - options=(), - channel_credentials=None, - call_credentials=None, - compression=None, - wait_for_ready=None, - timeout=None, - metadata=None, - ): - return grpc.experimental.unary_unary( - request, - target, - "/google.cloud.vision.v1p4beta1.ProductSearch/PurgeProducts", - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_product__search__service__pb2.PurgeProductsRequest.SerializeToString, - google_dot_longrunning_dot_operations__pb2.Operation.FromString, - options, - channel_credentials, - call_credentials, - compression, - wait_for_ready, - timeout, - metadata, - ) diff --git a/google/cloud/vision_v1p4beta1/proto/text_annotation_pb2.py b/google/cloud/vision_v1p4beta1/proto/text_annotation_pb2.py deleted file mode 100644 index f5446f09..00000000 --- a/google/cloud/vision_v1p4beta1/proto/text_annotation_pb2.py +++ /dev/null @@ -1,1224 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p4beta1/proto/text_annotation.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 -from google.cloud.vision_v1p4beta1.proto import ( - geometry_pb2 as google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2, -) - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p4beta1/proto/text_annotation.proto", - package="google.cloud.vision.v1p4beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p4beta1B\023TextAnnotationProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision\370\001\001\242\002\004GCVN", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n9google/cloud/vision_v1p4beta1/proto/text_annotation.proto\x12\x1dgoogle.cloud.vision.v1p4beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x32google/cloud/vision_v1p4beta1/proto/geometry.proto"\xb2\x04\n\x0eTextAnnotation\x12\x32\n\x05pages\x18\x01 \x03(\x0b\x32#.google.cloud.vision.v1p4beta1.Page\x12\x0c\n\x04text\x18\x02 \x01(\t\x1a=\n\x10\x44\x65tectedLanguage\x12\x15\n\rlanguage_code\x18\x01 \x01(\t\x12\x12\n\nconfidence\x18\x02 \x01(\x02\x1a\xdc\x01\n\rDetectedBreak\x12S\n\x04type\x18\x01 \x01(\x0e\x32\x45.google.cloud.vision.v1p4beta1.TextAnnotation.DetectedBreak.BreakType\x12\x11\n\tis_prefix\x18\x02 \x01(\x08"c\n\tBreakType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\t\n\x05SPACE\x10\x01\x12\x0e\n\nSURE_SPACE\x10\x02\x12\x12\n\x0e\x45OL_SURE_SPACE\x10\x03\x12\n\n\x06HYPHEN\x10\x04\x12\x0e\n\nLINE_BREAK\x10\x05\x1a\xbf\x01\n\x0cTextProperty\x12Z\n\x12\x64\x65tected_languages\x18\x01 \x03(\x0b\x32>.google.cloud.vision.v1p4beta1.TextAnnotation.DetectedLanguage\x12S\n\x0e\x64\x65tected_break\x18\x02 \x01(\x0b\x32;.google.cloud.vision.v1p4beta1.TextAnnotation.DetectedBreak"\xbd\x01\n\x04Page\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty\x12\r\n\x05width\x18\x02 \x01(\x05\x12\x0e\n\x06height\x18\x03 \x01(\x05\x12\x34\n\x06\x62locks\x18\x04 \x03(\x0b\x32$.google.cloud.vision.v1p4beta1.Block\x12\x12\n\nconfidence\x18\x05 \x01(\x02"\x82\x03\n\x05\x42lock\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty\x12\x41\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.BoundingPoly\x12<\n\nparagraphs\x18\x03 \x03(\x0b\x32(.google.cloud.vision.v1p4beta1.Paragraph\x12\x42\n\nblock_type\x18\x04 \x01(\x0e\x32..google.cloud.vision.v1p4beta1.Block.BlockType\x12\x12\n\nconfidence\x18\x05 \x01(\x02"R\n\tBlockType\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x08\n\x04TEXT\x10\x01\x12\t\n\x05TABLE\x10\x02\x12\x0b\n\x07PICTURE\x10\x03\x12\t\n\x05RULER\x10\x04\x12\x0b\n\x07\x42\x41RCODE\x10\x05"\xe4\x01\n\tParagraph\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty\x12\x41\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.BoundingPoly\x12\x32\n\x05words\x18\x03 \x03(\x0b\x32#.google.cloud.vision.v1p4beta1.Word\x12\x12\n\nconfidence\x18\x04 \x01(\x02"\xe3\x01\n\x04Word\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty\x12\x41\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.BoundingPoly\x12\x36\n\x07symbols\x18\x03 \x03(\x0b\x32%.google.cloud.vision.v1p4beta1.Symbol\x12\x12\n\nconfidence\x18\x04 \x01(\x02"\xbb\x01\n\x06Symbol\x12L\n\x08property\x18\x01 \x01(\x0b\x32:.google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty\x12\x41\n\x0c\x62ounding_box\x18\x02 \x01(\x0b\x32+.google.cloud.vision.v1p4beta1.BoundingPoly\x12\x0c\n\x04text\x18\x03 \x01(\t\x12\x12\n\nconfidence\x18\x04 \x01(\x02\x42\x89\x01\n!com.google.cloud.vision.v1p4beta1B\x13TextAnnotationProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision\xf8\x01\x01\xa2\x02\x04GCVNb\x06proto3', - dependencies=[ - google_dot_api_dot_annotations__pb2.DESCRIPTOR, - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2.DESCRIPTOR, - ], -) - - -_TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE = _descriptor.EnumDescriptor( - name="BreakType", - full_name="google.cloud.vision.v1p4beta1.TextAnnotation.DetectedBreak.BreakType", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNKNOWN", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SPACE", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="SURE_SPACE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="EOL_SURE_SPACE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="HYPHEN", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="LINE_BREAK", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=444, - serialized_end=543, -) -_sym_db.RegisterEnumDescriptor(_TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE) - -_BLOCK_BLOCKTYPE = _descriptor.EnumDescriptor( - name="BlockType", - full_name="google.cloud.vision.v1p4beta1.Block.BlockType", - filename=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - values=[ - _descriptor.EnumValueDescriptor( - name="UNKNOWN", - index=0, - number=0, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="TEXT", - index=1, - number=1, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="TABLE", - index=2, - number=2, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="PICTURE", - index=3, - number=3, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="RULER", - index=4, - number=4, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - _descriptor.EnumValueDescriptor( - name="BARCODE", - index=5, - number=5, - serialized_options=None, - type=None, - create_key=_descriptor._internal_create_key, - ), - ], - containing_type=None, - serialized_options=None, - serialized_start=1236, - serialized_end=1318, -) -_sym_db.RegisterEnumDescriptor(_BLOCK_BLOCKTYPE) - - -_TEXTANNOTATION_DETECTEDLANGUAGE = _descriptor.Descriptor( - name="DetectedLanguage", - full_name="google.cloud.vision.v1p4beta1.TextAnnotation.DetectedLanguage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="language_code", - full_name="google.cloud.vision.v1p4beta1.TextAnnotation.DetectedLanguage.language_code", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p4beta1.TextAnnotation.DetectedLanguage.confidence", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=259, - serialized_end=320, -) - -_TEXTANNOTATION_DETECTEDBREAK = _descriptor.Descriptor( - name="DetectedBreak", - full_name="google.cloud.vision.v1p4beta1.TextAnnotation.DetectedBreak", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="type", - full_name="google.cloud.vision.v1p4beta1.TextAnnotation.DetectedBreak.type", - index=0, - number=1, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="is_prefix", - full_name="google.cloud.vision.v1p4beta1.TextAnnotation.DetectedBreak.is_prefix", - index=1, - number=2, - type=8, - cpp_type=7, - label=1, - has_default_value=False, - default_value=False, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=323, - serialized_end=543, -) - -_TEXTANNOTATION_TEXTPROPERTY = _descriptor.Descriptor( - name="TextProperty", - full_name="google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="detected_languages", - full_name="google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty.detected_languages", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="detected_break", - full_name="google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty.detected_break", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=546, - serialized_end=737, -) - -_TEXTANNOTATION = _descriptor.Descriptor( - name="TextAnnotation", - full_name="google.cloud.vision.v1p4beta1.TextAnnotation", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="pages", - full_name="google.cloud.vision.v1p4beta1.TextAnnotation.pages", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="text", - full_name="google.cloud.vision.v1p4beta1.TextAnnotation.text", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _TEXTANNOTATION_DETECTEDLANGUAGE, - _TEXTANNOTATION_DETECTEDBREAK, - _TEXTANNOTATION_TEXTPROPERTY, - ], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=175, - serialized_end=737, -) - - -_PAGE = _descriptor.Descriptor( - name="Page", - full_name="google.cloud.vision.v1p4beta1.Page", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p4beta1.Page.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="width", - full_name="google.cloud.vision.v1p4beta1.Page.width", - index=1, - number=2, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="height", - full_name="google.cloud.vision.v1p4beta1.Page.height", - index=2, - number=3, - type=5, - cpp_type=1, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="blocks", - full_name="google.cloud.vision.v1p4beta1.Page.blocks", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p4beta1.Page.confidence", - index=4, - number=5, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=740, - serialized_end=929, -) - - -_BLOCK = _descriptor.Descriptor( - name="Block", - full_name="google.cloud.vision.v1p4beta1.Block", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p4beta1.Block.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_box", - full_name="google.cloud.vision.v1p4beta1.Block.bounding_box", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="paragraphs", - full_name="google.cloud.vision.v1p4beta1.Block.paragraphs", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="block_type", - full_name="google.cloud.vision.v1p4beta1.Block.block_type", - index=3, - number=4, - type=14, - cpp_type=8, - label=1, - has_default_value=False, - default_value=0, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p4beta1.Block.confidence", - index=4, - number=5, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[_BLOCK_BLOCKTYPE,], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=932, - serialized_end=1318, -) - - -_PARAGRAPH = _descriptor.Descriptor( - name="Paragraph", - full_name="google.cloud.vision.v1p4beta1.Paragraph", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p4beta1.Paragraph.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_box", - full_name="google.cloud.vision.v1p4beta1.Paragraph.bounding_box", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="words", - full_name="google.cloud.vision.v1p4beta1.Paragraph.words", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p4beta1.Paragraph.confidence", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1321, - serialized_end=1549, -) - - -_WORD = _descriptor.Descriptor( - name="Word", - full_name="google.cloud.vision.v1p4beta1.Word", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p4beta1.Word.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_box", - full_name="google.cloud.vision.v1p4beta1.Word.bounding_box", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="symbols", - full_name="google.cloud.vision.v1p4beta1.Word.symbols", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p4beta1.Word.confidence", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1552, - serialized_end=1779, -) - - -_SYMBOL = _descriptor.Descriptor( - name="Symbol", - full_name="google.cloud.vision.v1p4beta1.Symbol", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="property", - full_name="google.cloud.vision.v1p4beta1.Symbol.property", - index=0, - number=1, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="bounding_box", - full_name="google.cloud.vision.v1p4beta1.Symbol.bounding_box", - index=1, - number=2, - type=11, - cpp_type=10, - label=1, - has_default_value=False, - default_value=None, - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="text", - full_name="google.cloud.vision.v1p4beta1.Symbol.text", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="confidence", - full_name="google.cloud.vision.v1p4beta1.Symbol.confidence", - index=3, - number=4, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=1782, - serialized_end=1969, -) - -_TEXTANNOTATION_DETECTEDLANGUAGE.containing_type = _TEXTANNOTATION -_TEXTANNOTATION_DETECTEDBREAK.fields_by_name[ - "type" -].enum_type = _TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE -_TEXTANNOTATION_DETECTEDBREAK.containing_type = _TEXTANNOTATION -_TEXTANNOTATION_DETECTEDBREAK_BREAKTYPE.containing_type = _TEXTANNOTATION_DETECTEDBREAK -_TEXTANNOTATION_TEXTPROPERTY.fields_by_name[ - "detected_languages" -].message_type = _TEXTANNOTATION_DETECTEDLANGUAGE -_TEXTANNOTATION_TEXTPROPERTY.fields_by_name[ - "detected_break" -].message_type = _TEXTANNOTATION_DETECTEDBREAK -_TEXTANNOTATION_TEXTPROPERTY.containing_type = _TEXTANNOTATION -_TEXTANNOTATION.fields_by_name["pages"].message_type = _PAGE -_PAGE.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_PAGE.fields_by_name["blocks"].message_type = _BLOCK -_BLOCK.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_BLOCK.fields_by_name[ - "bounding_box" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_BLOCK.fields_by_name["paragraphs"].message_type = _PARAGRAPH -_BLOCK.fields_by_name["block_type"].enum_type = _BLOCK_BLOCKTYPE -_BLOCK_BLOCKTYPE.containing_type = _BLOCK -_PARAGRAPH.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_PARAGRAPH.fields_by_name[ - "bounding_box" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_PARAGRAPH.fields_by_name["words"].message_type = _WORD -_WORD.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_WORD.fields_by_name[ - "bounding_box" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -_WORD.fields_by_name["symbols"].message_type = _SYMBOL -_SYMBOL.fields_by_name["property"].message_type = _TEXTANNOTATION_TEXTPROPERTY -_SYMBOL.fields_by_name[ - "bounding_box" -].message_type = ( - google_dot_cloud_dot_vision__v1p4beta1_dot_proto_dot_geometry__pb2._BOUNDINGPOLY -) -DESCRIPTOR.message_types_by_name["TextAnnotation"] = _TEXTANNOTATION -DESCRIPTOR.message_types_by_name["Page"] = _PAGE -DESCRIPTOR.message_types_by_name["Block"] = _BLOCK -DESCRIPTOR.message_types_by_name["Paragraph"] = _PARAGRAPH -DESCRIPTOR.message_types_by_name["Word"] = _WORD -DESCRIPTOR.message_types_by_name["Symbol"] = _SYMBOL -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -TextAnnotation = _reflection.GeneratedProtocolMessageType( - "TextAnnotation", - (_message.Message,), - { - "DetectedLanguage": _reflection.GeneratedProtocolMessageType( - "DetectedLanguage", - (_message.Message,), - { - "DESCRIPTOR": _TEXTANNOTATION_DETECTEDLANGUAGE, - "__module__": "google.cloud.vision_v1p4beta1.proto.text_annotation_pb2", - "__doc__": """Detected language for a structural component. - - Attributes: - language_code: - The BCP-47 language code, such as “en-US” or “sr-Latn”. For - more information, see http://www.unicode.org/reports/tr35/#Uni - code_locale_identifier. - confidence: - Confidence of detected language. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.TextAnnotation.DetectedLanguage) - }, - ), - "DetectedBreak": _reflection.GeneratedProtocolMessageType( - "DetectedBreak", - (_message.Message,), - { - "DESCRIPTOR": _TEXTANNOTATION_DETECTEDBREAK, - "__module__": "google.cloud.vision_v1p4beta1.proto.text_annotation_pb2", - "__doc__": """Detected start or end of a structural component. - - Attributes: - type: - Detected break type. - is_prefix: - True if break prepends the element. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.TextAnnotation.DetectedBreak) - }, - ), - "TextProperty": _reflection.GeneratedProtocolMessageType( - "TextProperty", - (_message.Message,), - { - "DESCRIPTOR": _TEXTANNOTATION_TEXTPROPERTY, - "__module__": "google.cloud.vision_v1p4beta1.proto.text_annotation_pb2", - "__doc__": """Additional information detected on the structural component. - - Attributes: - detected_languages: - A list of detected languages together with confidence. - detected_break: - Detected start or end of a text segment. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty) - }, - ), - "DESCRIPTOR": _TEXTANNOTATION, - "__module__": "google.cloud.vision_v1p4beta1.proto.text_annotation_pb2", - "__doc__": """TextAnnotation contains a structured representation of OCR extracted - text. The hierarchy of an OCR extracted text structure is like this: - TextAnnotation -> Page -> Block -> Paragraph -> Word -> Symbol Each - structural component, starting from Page, may further have their own - properties. Properties describe detected languages, breaks etc.. - Please refer to the [TextAnnotation.TextProperty][google.cloud.vision. - v1p4beta1.TextAnnotation.TextProperty] message definition below for - more detail. - - Attributes: - pages: - List of pages detected by OCR. - text: - UTF-8 text detected on the pages. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.TextAnnotation) - }, -) -_sym_db.RegisterMessage(TextAnnotation) -_sym_db.RegisterMessage(TextAnnotation.DetectedLanguage) -_sym_db.RegisterMessage(TextAnnotation.DetectedBreak) -_sym_db.RegisterMessage(TextAnnotation.TextProperty) - -Page = _reflection.GeneratedProtocolMessageType( - "Page", - (_message.Message,), - { - "DESCRIPTOR": _PAGE, - "__module__": "google.cloud.vision_v1p4beta1.proto.text_annotation_pb2", - "__doc__": """Detected page from OCR. - - Attributes: - property: - Additional information detected on the page. - width: - Page width. For PDFs the unit is points. For images (including - TIFFs) the unit is pixels. - height: - Page height. For PDFs the unit is points. For images - (including TIFFs) the unit is pixels. - blocks: - List of blocks of text, images etc on this page. - confidence: - Confidence of the OCR results on the page. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.Page) - }, -) -_sym_db.RegisterMessage(Page) - -Block = _reflection.GeneratedProtocolMessageType( - "Block", - (_message.Message,), - { - "DESCRIPTOR": _BLOCK, - "__module__": "google.cloud.vision_v1p4beta1.proto.text_annotation_pb2", - "__doc__": """Logical element on the page. - - Attributes: - property: - Additional information detected for the block. - bounding_box: - The bounding box for the block. The vertices are in the order - of top-left, top-right, bottom-right, bottom-left. When a - rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: - - when the text is horizontal it might look like: :: - 0----1 | | 3----2 - when it’s rotated 180 - degrees around the top-left corner it becomes: :: - 2----3 | | 1----0 and the vertex order - will still be (0, 1, 2, 3). - paragraphs: - List of paragraphs in this block (if this blocks is of type - text). - block_type: - Detected block type (text, image etc) for this block. - confidence: - Confidence of the OCR results on the block. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.Block) - }, -) -_sym_db.RegisterMessage(Block) - -Paragraph = _reflection.GeneratedProtocolMessageType( - "Paragraph", - (_message.Message,), - { - "DESCRIPTOR": _PARAGRAPH, - "__module__": "google.cloud.vision_v1p4beta1.proto.text_annotation_pb2", - "__doc__": """Structural unit of text representing a number of words in certain - order. - - Attributes: - property: - Additional information detected for the paragraph. - bounding_box: - The bounding box for the paragraph. The vertices are in the - order of top-left, top-right, bottom-right, bottom-left. When - a rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: \* - when the text is horizontal it might look like: 0—-1 \| \| - 3—-2 \* when it’s rotated 180 degrees around the top-left - corner it becomes: 2—-3 \| \| 1—-0 and the vertex order will - still be (0, 1, 2, 3). - words: - List of all words in this paragraph. - confidence: - Confidence of the OCR results for the paragraph. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.Paragraph) - }, -) -_sym_db.RegisterMessage(Paragraph) - -Word = _reflection.GeneratedProtocolMessageType( - "Word", - (_message.Message,), - { - "DESCRIPTOR": _WORD, - "__module__": "google.cloud.vision_v1p4beta1.proto.text_annotation_pb2", - "__doc__": """A word representation. - - Attributes: - property: - Additional information detected for the word. - bounding_box: - The bounding box for the word. The vertices are in the order - of top-left, top-right, bottom-right, bottom-left. When a - rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: \* - when the text is horizontal it might look like: 0—-1 \| \| - 3—-2 \* when it’s rotated 180 degrees around the top-left - corner it becomes: 2—-3 \| \| 1—-0 and the vertex order will - still be (0, 1, 2, 3). - symbols: - List of symbols in the word. The order of the symbols follows - the natural reading order. - confidence: - Confidence of the OCR results for the word. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.Word) - }, -) -_sym_db.RegisterMessage(Word) - -Symbol = _reflection.GeneratedProtocolMessageType( - "Symbol", - (_message.Message,), - { - "DESCRIPTOR": _SYMBOL, - "__module__": "google.cloud.vision_v1p4beta1.proto.text_annotation_pb2", - "__doc__": """A single symbol representation. - - Attributes: - property: - Additional information detected for the symbol. - bounding_box: - The bounding box for the symbol. The vertices are in the order - of top-left, top-right, bottom-right, bottom-left. When a - rotation of the bounding box is detected the rotation is - represented as around the top-left corner as defined when the - text is read in the ‘natural’ orientation. For example: \* - when the text is horizontal it might look like: 0—-1 \| \| - 3—-2 \* when it’s rotated 180 degrees around the top-left - corner it becomes: 2—-3 \| \| 1—-0 and the vertex order will - still be (0, 1, 2, 3). - text: - The actual UTF-8 representation of the symbol. - confidence: - Confidence of the OCR results for the symbol. Range [0, 1]. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.Symbol) - }, -) -_sym_db.RegisterMessage(Symbol) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p4beta1/proto/text_annotation_pb2_grpc.py b/google/cloud/vision_v1p4beta1/proto/text_annotation_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/vision_v1p4beta1/proto/text_annotation_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/vision_v1p4beta1/proto/web_detection_pb2.py b/google/cloud/vision_v1p4beta1/proto/web_detection_pb2.py deleted file mode 100644 index 069cac3a..00000000 --- a/google/cloud/vision_v1p4beta1/proto/web_detection_pb2.py +++ /dev/null @@ -1,629 +0,0 @@ -# -*- coding: utf-8 -*- -# Generated by the protocol buffer compiler. DO NOT EDIT! -# source: google/cloud/vision_v1p4beta1/proto/web_detection.proto -"""Generated protocol buffer code.""" -from google.protobuf import descriptor as _descriptor -from google.protobuf import message as _message -from google.protobuf import reflection as _reflection -from google.protobuf import symbol_database as _symbol_database - -# @@protoc_insertion_point(imports) - -_sym_db = _symbol_database.Default() - - -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 - - -DESCRIPTOR = _descriptor.FileDescriptor( - name="google/cloud/vision_v1p4beta1/proto/web_detection.proto", - package="google.cloud.vision.v1p4beta1", - syntax="proto3", - serialized_options=b"\n!com.google.cloud.vision.v1p4beta1B\021WebDetectionProtoP\001ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision\370\001\001\242\002\004GCVN", - create_key=_descriptor._internal_create_key, - serialized_pb=b'\n7google/cloud/vision_v1p4beta1/proto/web_detection.proto\x12\x1dgoogle.cloud.vision.v1p4beta1\x1a\x1cgoogle/api/annotations.proto"\x8c\x07\n\x0cWebDetection\x12K\n\x0cweb_entities\x18\x01 \x03(\x0b\x32\x35.google.cloud.vision.v1p4beta1.WebDetection.WebEntity\x12R\n\x14\x66ull_matching_images\x18\x02 \x03(\x0b\x32\x34.google.cloud.vision.v1p4beta1.WebDetection.WebImage\x12U\n\x17partial_matching_images\x18\x03 \x03(\x0b\x32\x34.google.cloud.vision.v1p4beta1.WebDetection.WebImage\x12W\n\x1apages_with_matching_images\x18\x04 \x03(\x0b\x32\x33.google.cloud.vision.v1p4beta1.WebDetection.WebPage\x12U\n\x17visually_similar_images\x18\x06 \x03(\x0b\x32\x34.google.cloud.vision.v1p4beta1.WebDetection.WebImage\x12O\n\x11\x62\x65st_guess_labels\x18\x08 \x03(\x0b\x32\x34.google.cloud.vision.v1p4beta1.WebDetection.WebLabel\x1a\x42\n\tWebEntity\x12\x11\n\tentity_id\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\x1a&\n\x08WebImage\x12\x0b\n\x03url\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x1a\xe4\x01\n\x07WebPage\x12\x0b\n\x03url\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x12\n\npage_title\x18\x03 \x01(\t\x12R\n\x14\x66ull_matching_images\x18\x04 \x03(\x0b\x32\x34.google.cloud.vision.v1p4beta1.WebDetection.WebImage\x12U\n\x17partial_matching_images\x18\x05 \x03(\x0b\x32\x34.google.cloud.vision.v1p4beta1.WebDetection.WebImage\x1a\x30\n\x08WebLabel\x12\r\n\x05label\x18\x01 \x01(\t\x12\x15\n\rlanguage_code\x18\x02 \x01(\tB\x87\x01\n!com.google.cloud.vision.v1p4beta1B\x11WebDetectionProtoP\x01ZCgoogle.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision\xf8\x01\x01\xa2\x02\x04GCVNb\x06proto3', - dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,], -) - - -_WEBDETECTION_WEBENTITY = _descriptor.Descriptor( - name="WebEntity", - full_name="google.cloud.vision.v1p4beta1.WebDetection.WebEntity", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="entity_id", - full_name="google.cloud.vision.v1p4beta1.WebDetection.WebEntity.entity_id", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p4beta1.WebDetection.WebEntity.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="description", - full_name="google.cloud.vision.v1p4beta1.WebDetection.WebEntity.description", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=642, - serialized_end=708, -) - -_WEBDETECTION_WEBIMAGE = _descriptor.Descriptor( - name="WebImage", - full_name="google.cloud.vision.v1p4beta1.WebDetection.WebImage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="url", - full_name="google.cloud.vision.v1p4beta1.WebDetection.WebImage.url", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p4beta1.WebDetection.WebImage.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=710, - serialized_end=748, -) - -_WEBDETECTION_WEBPAGE = _descriptor.Descriptor( - name="WebPage", - full_name="google.cloud.vision.v1p4beta1.WebDetection.WebPage", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="url", - full_name="google.cloud.vision.v1p4beta1.WebDetection.WebPage.url", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="score", - full_name="google.cloud.vision.v1p4beta1.WebDetection.WebPage.score", - index=1, - number=2, - type=2, - cpp_type=6, - label=1, - has_default_value=False, - default_value=float(0), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="page_title", - full_name="google.cloud.vision.v1p4beta1.WebDetection.WebPage.page_title", - index=2, - number=3, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="full_matching_images", - full_name="google.cloud.vision.v1p4beta1.WebDetection.WebPage.full_matching_images", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="partial_matching_images", - full_name="google.cloud.vision.v1p4beta1.WebDetection.WebPage.partial_matching_images", - index=4, - number=5, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=751, - serialized_end=979, -) - -_WEBDETECTION_WEBLABEL = _descriptor.Descriptor( - name="WebLabel", - full_name="google.cloud.vision.v1p4beta1.WebDetection.WebLabel", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="label", - full_name="google.cloud.vision.v1p4beta1.WebDetection.WebLabel.label", - index=0, - number=1, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="language_code", - full_name="google.cloud.vision.v1p4beta1.WebDetection.WebLabel.language_code", - index=1, - number=2, - type=9, - cpp_type=9, - label=1, - has_default_value=False, - default_value=b"".decode("utf-8"), - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=981, - serialized_end=1029, -) - -_WEBDETECTION = _descriptor.Descriptor( - name="WebDetection", - full_name="google.cloud.vision.v1p4beta1.WebDetection", - filename=None, - file=DESCRIPTOR, - containing_type=None, - create_key=_descriptor._internal_create_key, - fields=[ - _descriptor.FieldDescriptor( - name="web_entities", - full_name="google.cloud.vision.v1p4beta1.WebDetection.web_entities", - index=0, - number=1, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="full_matching_images", - full_name="google.cloud.vision.v1p4beta1.WebDetection.full_matching_images", - index=1, - number=2, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="partial_matching_images", - full_name="google.cloud.vision.v1p4beta1.WebDetection.partial_matching_images", - index=2, - number=3, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="pages_with_matching_images", - full_name="google.cloud.vision.v1p4beta1.WebDetection.pages_with_matching_images", - index=3, - number=4, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="visually_similar_images", - full_name="google.cloud.vision.v1p4beta1.WebDetection.visually_similar_images", - index=4, - number=6, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - _descriptor.FieldDescriptor( - name="best_guess_labels", - full_name="google.cloud.vision.v1p4beta1.WebDetection.best_guess_labels", - index=5, - number=8, - type=11, - cpp_type=10, - label=3, - has_default_value=False, - default_value=[], - message_type=None, - enum_type=None, - containing_type=None, - is_extension=False, - extension_scope=None, - serialized_options=None, - file=DESCRIPTOR, - create_key=_descriptor._internal_create_key, - ), - ], - extensions=[], - nested_types=[ - _WEBDETECTION_WEBENTITY, - _WEBDETECTION_WEBIMAGE, - _WEBDETECTION_WEBPAGE, - _WEBDETECTION_WEBLABEL, - ], - enum_types=[], - serialized_options=None, - is_extendable=False, - syntax="proto3", - extension_ranges=[], - oneofs=[], - serialized_start=121, - serialized_end=1029, -) - -_WEBDETECTION_WEBENTITY.containing_type = _WEBDETECTION -_WEBDETECTION_WEBIMAGE.containing_type = _WEBDETECTION -_WEBDETECTION_WEBPAGE.fields_by_name[ - "full_matching_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION_WEBPAGE.fields_by_name[ - "partial_matching_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION_WEBPAGE.containing_type = _WEBDETECTION -_WEBDETECTION_WEBLABEL.containing_type = _WEBDETECTION -_WEBDETECTION.fields_by_name["web_entities"].message_type = _WEBDETECTION_WEBENTITY -_WEBDETECTION.fields_by_name[ - "full_matching_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION.fields_by_name[ - "partial_matching_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION.fields_by_name[ - "pages_with_matching_images" -].message_type = _WEBDETECTION_WEBPAGE -_WEBDETECTION.fields_by_name[ - "visually_similar_images" -].message_type = _WEBDETECTION_WEBIMAGE -_WEBDETECTION.fields_by_name["best_guess_labels"].message_type = _WEBDETECTION_WEBLABEL -DESCRIPTOR.message_types_by_name["WebDetection"] = _WEBDETECTION -_sym_db.RegisterFileDescriptor(DESCRIPTOR) - -WebDetection = _reflection.GeneratedProtocolMessageType( - "WebDetection", - (_message.Message,), - { - "WebEntity": _reflection.GeneratedProtocolMessageType( - "WebEntity", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTION_WEBENTITY, - "__module__": "google.cloud.vision_v1p4beta1.proto.web_detection_pb2", - "__doc__": """Entity deduced from similar images on the Internet. - - Attributes: - entity_id: - Opaque entity ID. - score: - Overall relevancy score for the entity. Not normalized and not - comparable across different image queries. - description: - Canonical description of the entity, in English. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.WebDetection.WebEntity) - }, - ), - "WebImage": _reflection.GeneratedProtocolMessageType( - "WebImage", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTION_WEBIMAGE, - "__module__": "google.cloud.vision_v1p4beta1.proto.web_detection_pb2", - "__doc__": """Metadata for online images. - - Attributes: - url: - The result image URL. - score: - (Deprecated) Overall relevancy score for the image. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.WebDetection.WebImage) - }, - ), - "WebPage": _reflection.GeneratedProtocolMessageType( - "WebPage", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTION_WEBPAGE, - "__module__": "google.cloud.vision_v1p4beta1.proto.web_detection_pb2", - "__doc__": """Metadata for web pages. - - Attributes: - url: - The result web page URL. - score: - (Deprecated) Overall relevancy score for the web page. - page_title: - Title for the web page, may contain HTML markups. - full_matching_images: - Fully matching images on the page. Can include resized copies - of the query image. - partial_matching_images: - Partial matching images on the page. Those images are similar - enough to share some key-point features. For example an - original image will likely have partial matching for its - crops. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.WebDetection.WebPage) - }, - ), - "WebLabel": _reflection.GeneratedProtocolMessageType( - "WebLabel", - (_message.Message,), - { - "DESCRIPTOR": _WEBDETECTION_WEBLABEL, - "__module__": "google.cloud.vision_v1p4beta1.proto.web_detection_pb2", - "__doc__": """Label to provide extra metadata for the web detection. - - Attributes: - label: - Label for extra metadata. - language_code: - The BCP-47 language code for ``label``, such as “en-US” or - “sr-Latn”. For more information, see http://www.unicode.org/re - ports/tr35/#Unicode_locale_identifier. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.WebDetection.WebLabel) - }, - ), - "DESCRIPTOR": _WEBDETECTION, - "__module__": "google.cloud.vision_v1p4beta1.proto.web_detection_pb2", - "__doc__": """Relevant information for the image from the Internet. - - Attributes: - web_entities: - Deduced entities from similar images on the Internet. - full_matching_images: - Fully matching images from the Internet. Can include resized - copies of the query image. - partial_matching_images: - Partial matching images from the Internet. Those images are - similar enough to share some key-point features. For example - an original image will likely have partial matching for its - crops. - pages_with_matching_images: - Web pages containing the matching images from the Internet. - visually_similar_images: - The visually similar image results. - best_guess_labels: - The service’s best guess as to the topic of the request image. - Inferred from similar images on the open web. - """, - # @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.WebDetection) - }, -) -_sym_db.RegisterMessage(WebDetection) -_sym_db.RegisterMessage(WebDetection.WebEntity) -_sym_db.RegisterMessage(WebDetection.WebImage) -_sym_db.RegisterMessage(WebDetection.WebPage) -_sym_db.RegisterMessage(WebDetection.WebLabel) - - -DESCRIPTOR._options = None -# @@protoc_insertion_point(module_scope) diff --git a/google/cloud/vision_v1p4beta1/proto/web_detection_pb2_grpc.py b/google/cloud/vision_v1p4beta1/proto/web_detection_pb2_grpc.py deleted file mode 100644 index 8a939394..00000000 --- a/google/cloud/vision_v1p4beta1/proto/web_detection_pb2_grpc.py +++ /dev/null @@ -1,3 +0,0 @@ -# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! -"""Client and server classes corresponding to protobuf-defined services.""" -import grpc diff --git a/google/cloud/vision_v1p4beta1/py.typed b/google/cloud/vision_v1p4beta1/py.typed new file mode 100644 index 00000000..8cb07491 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-vision package uses inline types. diff --git a/google/cloud/vision_v1p4beta1/services/__init__.py b/google/cloud/vision_v1p4beta1/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/vision_v1p4beta1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/__init__.py b/google/cloud/vision_v1p4beta1/services/image_annotator/__init__.py new file mode 100644 index 00000000..2b601881 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import ImageAnnotatorClient +from .async_client import ImageAnnotatorAsyncClient + +__all__ = ( + "ImageAnnotatorClient", + "ImageAnnotatorAsyncClient", +) diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/async_client.py b/google/cloud/vision_v1p4beta1/services/image_annotator/async_client.py new file mode 100644 index 00000000..182132c9 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/async_client.py @@ -0,0 +1,456 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1p4beta1.types import image_annotator + +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport +from .client import ImageAnnotatorClient + + +class ImageAnnotatorAsyncClient: + """Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + """ + + _client: ImageAnnotatorClient + + DEFAULT_ENDPOINT = ImageAnnotatorClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ImageAnnotatorClient.DEFAULT_MTLS_ENDPOINT + + from_service_account_file = ImageAnnotatorClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(ImageAnnotatorClient).get_transport_class, type(ImageAnnotatorClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, ImageAnnotatorTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the image annotator client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ImageAnnotatorTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = ImageAnnotatorClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def batch_annotate_images( + self, + request: image_annotator.BatchAnnotateImagesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateImageRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: + r"""Run image detection and annotation for a batch of + images. + + Args: + request (:class:`~.image_annotator.BatchAnnotateImagesRequest`): + The request object. Multiple image annotation requests + are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AnnotateImageRequest]`): + Required. Individual image annotation + requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.image_annotator.BatchAnnotateImagesResponse: + Response to a batch image annotation + request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([requests]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = image_annotator.BatchAnnotateImagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_annotate_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def batch_annotate_files( + self, + request: image_annotator.BatchAnnotateFilesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateFileRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> image_annotator.BatchAnnotateFilesResponse: + r"""Service that performs image detection and annotation + for a batch of files. Now only "application/pdf", + "image/tiff" and "image/gif" are supported. + This service will extract at most 5 (customers can + specify which 5 in AnnotateFileRequest.pages) frames + (gif) or pages (pdf or tiff) from each file provided and + perform detection and annotation for each image + extracted. + + Args: + request (:class:`~.image_annotator.BatchAnnotateFilesRequest`): + The request object. A list of requests to annotate files + using the BatchAnnotateFiles API. + requests (:class:`Sequence[~.image_annotator.AnnotateFileRequest]`): + Required. The list of file annotation + requests. Right now we support only one + AnnotateFileRequest in + BatchAnnotateFilesRequest. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.image_annotator.BatchAnnotateFilesResponse: + A list of file annotation responses. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([requests]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = image_annotator.BatchAnnotateFilesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.batch_annotate_files, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def async_batch_annotate_images( + self, + request: image_annotator.AsyncBatchAnnotateImagesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateImageRequest] = None, + output_config: image_annotator.OutputConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Run asynchronous image detection and annotation for a list of + images. + + Progress and results can be retrieved through the + ``google.longrunning.Operations`` interface. + ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateImagesResponse`` (results). + + This service will write image annotation outputs to json files + in customer GCS bucket, each json file containing + BatchAnnotateImagesResponse proto. + + Args: + request (:class:`~.image_annotator.AsyncBatchAnnotateImagesRequest`): + The request object. Request for async image annotation + for a list of images. + requests (:class:`Sequence[~.image_annotator.AnnotateImageRequest]`): + Required. Individual image annotation + requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + output_config (:class:`~.image_annotator.OutputConfig`): + Required. The desired output location + and metadata (e.g. format). + This corresponds to the ``output_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.image_annotator.AsyncBatchAnnotateImagesResponse``: + Response to an async batch image annotation request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([requests, output_config]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = image_annotator.AsyncBatchAnnotateImagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + if output_config is not None: + request.output_config = output_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.async_batch_annotate_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + image_annotator.AsyncBatchAnnotateImagesResponse, + metadata_type=image_annotator.OperationMetadata, + ) + + # Done; return the response. + return response + + async def async_batch_annotate_files( + self, + request: image_annotator.AsyncBatchAnnotateFilesRequest = None, + *, + requests: Sequence[image_annotator.AsyncAnnotateFileRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Run asynchronous image detection and annotation for a list of + generic files, such as PDF files, which may contain multiple + pages and multiple images per page. Progress and results can be + retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateFilesResponse`` (results). + + Args: + request (:class:`~.image_annotator.AsyncBatchAnnotateFilesRequest`): + The request object. Multiple async file annotation + requests are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AsyncAnnotateFileRequest]`): + Required. Individual async file + annotation requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.image_annotator.AsyncBatchAnnotateFilesResponse``: + Response to an async batch file annotation request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([requests]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = image_annotator.AsyncBatchAnnotateFilesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.async_batch_annotate_files, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + image_annotator.AsyncBatchAnnotateFilesResponse, + metadata_type=image_annotator.OperationMetadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ImageAnnotatorAsyncClient",) diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/client.py b/google/cloud/vision_v1p4beta1/services/image_annotator/client.py new file mode 100644 index 00000000..2abb95a9 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/client.py @@ -0,0 +1,604 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1p4beta1.types import image_annotator + +from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ImageAnnotatorGrpcTransport +from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport + + +class ImageAnnotatorClientMeta(type): + """Metaclass for the ImageAnnotator client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[ImageAnnotatorTransport]] + _transport_registry["grpc"] = ImageAnnotatorGrpcTransport + _transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[ImageAnnotatorTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ImageAnnotatorClient(metaclass=ImageAnnotatorClientMeta): + """Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "vision.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + def __init__( + self, + *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, ImageAnnotatorTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the image annotator client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ImageAnnotatorTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ImageAnnotatorTransport): + # transport is a ImageAnnotatorTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def batch_annotate_images( + self, + request: image_annotator.BatchAnnotateImagesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateImageRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> image_annotator.BatchAnnotateImagesResponse: + r"""Run image detection and annotation for a batch of + images. + + Args: + request (:class:`~.image_annotator.BatchAnnotateImagesRequest`): + The request object. Multiple image annotation requests + are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AnnotateImageRequest]`): + Required. Individual image annotation + requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.image_annotator.BatchAnnotateImagesResponse: + Response to a batch image annotation + request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([requests]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a image_annotator.BatchAnnotateImagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, image_annotator.BatchAnnotateImagesRequest): + request = image_annotator.BatchAnnotateImagesRequest(request) + if requests is not None: + for i in range(len(requests)): + requests[i] = image_annotator.AnnotateImageRequest(requests[i]) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_annotate_images] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def batch_annotate_files( + self, + request: image_annotator.BatchAnnotateFilesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateFileRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> image_annotator.BatchAnnotateFilesResponse: + r"""Service that performs image detection and annotation + for a batch of files. Now only "application/pdf", + "image/tiff" and "image/gif" are supported. + This service will extract at most 5 (customers can + specify which 5 in AnnotateFileRequest.pages) frames + (gif) or pages (pdf or tiff) from each file provided and + perform detection and annotation for each image + extracted. + + Args: + request (:class:`~.image_annotator.BatchAnnotateFilesRequest`): + The request object. A list of requests to annotate files + using the BatchAnnotateFiles API. + requests (:class:`Sequence[~.image_annotator.AnnotateFileRequest]`): + Required. The list of file annotation + requests. Right now we support only one + AnnotateFileRequest in + BatchAnnotateFilesRequest. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.image_annotator.BatchAnnotateFilesResponse: + A list of file annotation responses. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([requests]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a image_annotator.BatchAnnotateFilesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, image_annotator.BatchAnnotateFilesRequest): + request = image_annotator.BatchAnnotateFilesRequest(request) + if requests is not None: + for i in range(len(requests)): + requests[i] = image_annotator.AnnotateFileRequest(requests[i]) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_annotate_files] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def async_batch_annotate_images( + self, + request: image_annotator.AsyncBatchAnnotateImagesRequest = None, + *, + requests: Sequence[image_annotator.AnnotateImageRequest] = None, + output_config: image_annotator.OutputConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Run asynchronous image detection and annotation for a list of + images. + + Progress and results can be retrieved through the + ``google.longrunning.Operations`` interface. + ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateImagesResponse`` (results). + + This service will write image annotation outputs to json files + in customer GCS bucket, each json file containing + BatchAnnotateImagesResponse proto. + + Args: + request (:class:`~.image_annotator.AsyncBatchAnnotateImagesRequest`): + The request object. Request for async image annotation + for a list of images. + requests (:class:`Sequence[~.image_annotator.AnnotateImageRequest]`): + Required. Individual image annotation + requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + output_config (:class:`~.image_annotator.OutputConfig`): + Required. The desired output location + and metadata (e.g. format). + This corresponds to the ``output_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.image_annotator.AsyncBatchAnnotateImagesResponse``: + Response to an async batch image annotation request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([requests, output_config]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a image_annotator.AsyncBatchAnnotateImagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, image_annotator.AsyncBatchAnnotateImagesRequest): + request = image_annotator.AsyncBatchAnnotateImagesRequest(request) + if requests is not None: + for i in range(len(requests)): + requests[i] = image_annotator.AnnotateImageRequest(requests[i]) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + if output_config is not None: + request.output_config = output_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.async_batch_annotate_images + ] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + image_annotator.AsyncBatchAnnotateImagesResponse, + metadata_type=image_annotator.OperationMetadata, + ) + + # Done; return the response. + return response + + def async_batch_annotate_files( + self, + request: image_annotator.AsyncBatchAnnotateFilesRequest = None, + *, + requests: Sequence[image_annotator.AsyncAnnotateFileRequest] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Run asynchronous image detection and annotation for a list of + generic files, such as PDF files, which may contain multiple + pages and multiple images per page. Progress and results can be + retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateFilesResponse`` (results). + + Args: + request (:class:`~.image_annotator.AsyncBatchAnnotateFilesRequest`): + The request object. Multiple async file annotation + requests are batched into a single service call. + requests (:class:`Sequence[~.image_annotator.AsyncAnnotateFileRequest]`): + Required. Individual async file + annotation requests for this batch. + This corresponds to the ``requests`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.image_annotator.AsyncBatchAnnotateFilesResponse``: + Response to an async batch file annotation request. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([requests]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a image_annotator.AsyncBatchAnnotateFilesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, image_annotator.AsyncBatchAnnotateFilesRequest): + request = image_annotator.AsyncBatchAnnotateFilesRequest(request) + if requests is not None: + for i in range(len(requests)): + requests[i] = image_annotator.AsyncAnnotateFileRequest(requests[i]) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if requests is not None: + request.requests = requests + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.async_batch_annotate_files + ] + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + image_annotator.AsyncBatchAnnotateFilesResponse, + metadata_type=image_annotator.OperationMetadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ImageAnnotatorClient",) diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/__init__.py b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/__init__.py new file mode 100644 index 00000000..f2315e0d --- /dev/null +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import ImageAnnotatorTransport +from .grpc import ImageAnnotatorGrpcTransport +from .grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ImageAnnotatorTransport]] +_transport_registry["grpc"] = ImageAnnotatorGrpcTransport +_transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport + + +__all__ = ( + "ImageAnnotatorTransport", + "ImageAnnotatorGrpcTransport", + "ImageAnnotatorGrpcAsyncIOTransport", +) diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py new file mode 100644 index 00000000..7b72bb0c --- /dev/null +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py @@ -0,0 +1,206 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.vision_v1p4beta1.types import image_annotator +from google.longrunning import operations_pb2 as operations # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ImageAnnotatorTransport(abc.ABC): + """Abstract transport class for ImageAnnotator.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ) + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.batch_annotate_images: gapic_v1.method.wrap_method( + self.batch_annotate_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.batch_annotate_files: gapic_v1.method.wrap_method( + self.batch_annotate_files, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.async_batch_annotate_images: gapic_v1.method.wrap_method( + self.async_batch_annotate_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.async_batch_annotate_files: gapic_v1.method.wrap_method( + self.async_batch_annotate_files, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def batch_annotate_images( + self, + ) -> typing.Callable[ + [image_annotator.BatchAnnotateImagesRequest], + typing.Union[ + image_annotator.BatchAnnotateImagesResponse, + typing.Awaitable[image_annotator.BatchAnnotateImagesResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_annotate_files( + self, + ) -> typing.Callable[ + [image_annotator.BatchAnnotateFilesRequest], + typing.Union[ + image_annotator.BatchAnnotateFilesResponse, + typing.Awaitable[image_annotator.BatchAnnotateFilesResponse], + ], + ]: + raise NotImplementedError() + + @property + def async_batch_annotate_images( + self, + ) -> typing.Callable[ + [image_annotator.AsyncBatchAnnotateImagesRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def async_batch_annotate_files( + self, + ) -> typing.Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + +__all__ = ("ImageAnnotatorTransport",) diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py new file mode 100644 index 00000000..3e41f0d3 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py @@ -0,0 +1,393 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.vision_v1p4beta1.types import image_annotator +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO + + +class ImageAnnotatorGrpcTransport(ImageAnnotatorTransport): + """gRPC backend transport for ImageAnnotator. + + Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def batch_annotate_images( + self, + ) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + image_annotator.BatchAnnotateImagesResponse, + ]: + r"""Return a callable for the batch annotate images method over gRPC. + + Run image detection and annotation for a batch of + images. + + Returns: + Callable[[~.BatchAnnotateImagesRequest], + ~.BatchAnnotateImagesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_annotate_images" not in self._stubs: + self._stubs["batch_annotate_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateImages", + request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, + response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, + ) + return self._stubs["batch_annotate_images"] + + @property + def batch_annotate_files( + self, + ) -> Callable[ + [image_annotator.BatchAnnotateFilesRequest], + image_annotator.BatchAnnotateFilesResponse, + ]: + r"""Return a callable for the batch annotate files method over gRPC. + + Service that performs image detection and annotation + for a batch of files. Now only "application/pdf", + "image/tiff" and "image/gif" are supported. + This service will extract at most 5 (customers can + specify which 5 in AnnotateFileRequest.pages) frames + (gif) or pages (pdf or tiff) from each file provided and + perform detection and annotation for each image + extracted. + + Returns: + Callable[[~.BatchAnnotateFilesRequest], + ~.BatchAnnotateFilesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_annotate_files" not in self._stubs: + self._stubs["batch_annotate_files"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateFiles", + request_serializer=image_annotator.BatchAnnotateFilesRequest.serialize, + response_deserializer=image_annotator.BatchAnnotateFilesResponse.deserialize, + ) + return self._stubs["batch_annotate_files"] + + @property + def async_batch_annotate_images( + self, + ) -> Callable[ + [image_annotator.AsyncBatchAnnotateImagesRequest], operations.Operation + ]: + r"""Return a callable for the async batch annotate images method over gRPC. + + Run asynchronous image detection and annotation for a list of + images. + + Progress and results can be retrieved through the + ``google.longrunning.Operations`` interface. + ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateImagesResponse`` (results). + + This service will write image annotation outputs to json files + in customer GCS bucket, each json file containing + BatchAnnotateImagesResponse proto. + + Returns: + Callable[[~.AsyncBatchAnnotateImagesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "async_batch_annotate_images" not in self._stubs: + self._stubs["async_batch_annotate_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateImages", + request_serializer=image_annotator.AsyncBatchAnnotateImagesRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["async_batch_annotate_images"] + + @property + def async_batch_annotate_files( + self, + ) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], operations.Operation + ]: + r"""Return a callable for the async batch annotate files method over gRPC. + + Run asynchronous image detection and annotation for a list of + generic files, such as PDF files, which may contain multiple + pages and multiple images per page. Progress and results can be + retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateFilesResponse`` (results). + + Returns: + Callable[[~.AsyncBatchAnnotateFilesRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "async_batch_annotate_files" not in self._stubs: + self._stubs["async_batch_annotate_files"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateFiles", + request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["async_batch_annotate_files"] + + +__all__ = ("ImageAnnotatorGrpcTransport",) diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc_asyncio.py b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc_asyncio.py new file mode 100644 index 00000000..d1f5775c --- /dev/null +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc_asyncio.py @@ -0,0 +1,395 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.vision_v1p4beta1.types import image_annotator +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO +from .grpc import ImageAnnotatorGrpcTransport + + +class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): + """gRPC AsyncIO backend transport for ImageAnnotator. + + Service that performs Google Cloud Vision API detection tasks + over client images, such as face, landmark, logo, label, and + text detection. The ImageAnnotator service returns detected + entities from the images. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def batch_annotate_images( + self, + ) -> Callable[ + [image_annotator.BatchAnnotateImagesRequest], + Awaitable[image_annotator.BatchAnnotateImagesResponse], + ]: + r"""Return a callable for the batch annotate images method over gRPC. + + Run image detection and annotation for a batch of + images. + + Returns: + Callable[[~.BatchAnnotateImagesRequest], + Awaitable[~.BatchAnnotateImagesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_annotate_images" not in self._stubs: + self._stubs["batch_annotate_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateImages", + request_serializer=image_annotator.BatchAnnotateImagesRequest.serialize, + response_deserializer=image_annotator.BatchAnnotateImagesResponse.deserialize, + ) + return self._stubs["batch_annotate_images"] + + @property + def batch_annotate_files( + self, + ) -> Callable[ + [image_annotator.BatchAnnotateFilesRequest], + Awaitable[image_annotator.BatchAnnotateFilesResponse], + ]: + r"""Return a callable for the batch annotate files method over gRPC. + + Service that performs image detection and annotation + for a batch of files. Now only "application/pdf", + "image/tiff" and "image/gif" are supported. + This service will extract at most 5 (customers can + specify which 5 in AnnotateFileRequest.pages) frames + (gif) or pages (pdf or tiff) from each file provided and + perform detection and annotation for each image + extracted. + + Returns: + Callable[[~.BatchAnnotateFilesRequest], + Awaitable[~.BatchAnnotateFilesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_annotate_files" not in self._stubs: + self._stubs["batch_annotate_files"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ImageAnnotator/BatchAnnotateFiles", + request_serializer=image_annotator.BatchAnnotateFilesRequest.serialize, + response_deserializer=image_annotator.BatchAnnotateFilesResponse.deserialize, + ) + return self._stubs["batch_annotate_files"] + + @property + def async_batch_annotate_images( + self, + ) -> Callable[ + [image_annotator.AsyncBatchAnnotateImagesRequest], + Awaitable[operations.Operation], + ]: + r"""Return a callable for the async batch annotate images method over gRPC. + + Run asynchronous image detection and annotation for a list of + images. + + Progress and results can be retrieved through the + ``google.longrunning.Operations`` interface. + ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateImagesResponse`` (results). + + This service will write image annotation outputs to json files + in customer GCS bucket, each json file containing + BatchAnnotateImagesResponse proto. + + Returns: + Callable[[~.AsyncBatchAnnotateImagesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "async_batch_annotate_images" not in self._stubs: + self._stubs["async_batch_annotate_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateImages", + request_serializer=image_annotator.AsyncBatchAnnotateImagesRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["async_batch_annotate_images"] + + @property + def async_batch_annotate_files( + self, + ) -> Callable[ + [image_annotator.AsyncBatchAnnotateFilesRequest], + Awaitable[operations.Operation], + ]: + r"""Return a callable for the async batch annotate files method over gRPC. + + Run asynchronous image detection and annotation for a list of + generic files, such as PDF files, which may contain multiple + pages and multiple images per page. Progress and results can be + retrieved through the ``google.longrunning.Operations`` + interface. ``Operation.metadata`` contains ``OperationMetadata`` + (metadata). ``Operation.response`` contains + ``AsyncBatchAnnotateFilesResponse`` (results). + + Returns: + Callable[[~.AsyncBatchAnnotateFilesRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "async_batch_annotate_files" not in self._stubs: + self._stubs["async_batch_annotate_files"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ImageAnnotator/AsyncBatchAnnotateFiles", + request_serializer=image_annotator.AsyncBatchAnnotateFilesRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["async_batch_annotate_files"] + + +__all__ = ("ImageAnnotatorGrpcAsyncIOTransport",) diff --git a/google/cloud/vision_v1p4beta1/services/product_search/__init__.py b/google/cloud/vision_v1p4beta1/services/product_search/__init__.py new file mode 100644 index 00000000..e82b5909 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/services/product_search/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import ProductSearchClient +from .async_client import ProductSearchAsyncClient + +__all__ = ( + "ProductSearchClient", + "ProductSearchAsyncClient", +) diff --git a/google/cloud/vision_v1p4beta1/services/product_search/async_client.py b/google/cloud/vision_v1p4beta1/services/product_search/async_client.py new file mode 100644 index 00000000..f00e5814 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/services/product_search/async_client.py @@ -0,0 +1,1983 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1p4beta1.services.product_search import pagers +from google.cloud.vision_v1p4beta1.types import geometry +from google.cloud.vision_v1p4beta1.types import product_search_service +from google.protobuf import empty_pb2 as empty # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + +from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport +from .client import ProductSearchClient + + +class ProductSearchAsyncClient: + """Manages Products and ProductSets of reference images for use in + product search. It uses the following resource model: + + - The API has a collection of + [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. + + In parallel, + + - The API has a collection of + [Product][google.cloud.vision.v1p4beta1.Product] resources, named + ``projects/*/locations/*/products/*`` + + - Each [Product][google.cloud.vision.v1p4beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` + """ + + _client: ProductSearchClient + + DEFAULT_ENDPOINT = ProductSearchClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = ProductSearchClient.DEFAULT_MTLS_ENDPOINT + + product_path = staticmethod(ProductSearchClient.product_path) + parse_product_path = staticmethod(ProductSearchClient.parse_product_path) + product_set_path = staticmethod(ProductSearchClient.product_set_path) + parse_product_set_path = staticmethod(ProductSearchClient.parse_product_set_path) + reference_image_path = staticmethod(ProductSearchClient.reference_image_path) + parse_reference_image_path = staticmethod( + ProductSearchClient.parse_reference_image_path + ) + + from_service_account_file = ProductSearchClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(ProductSearchClient).get_transport_class, type(ProductSearchClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, ProductSearchTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the product search client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProductSearchTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = ProductSearchClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def create_product_set( + self, + request: product_search_service.CreateProductSetRequest = None, + *, + parent: str = None, + product_set: product_search_service.ProductSet = None, + product_set_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Creates and returns a new ProductSet resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. + + Args: + request (:class:`~.product_search_service.CreateProductSetRequest`): + The request object. Request message for the + `CreateProductSet` method. + parent (:class:`str`): + Required. The project in which the ProductSet should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_set (:class:`~.product_search_service.ProductSet`): + Required. The ProductSet to create. + This corresponds to the ``product_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_set_id (:class:`str`): + A user-supplied resource id for this ProductSet. If set, + the server will attempt to use this value as the + resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``product_set_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, product_set, product_set_id]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.CreateProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if product_set is not None: + request.product_set = product_set + if product_set_id is not None: + request.product_set_id = product_set_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_product_sets( + self, + request: product_search_service.ListProductSetsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductSetsAsyncPager: + r"""Lists ProductSets in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductSetsRequest`): + The request object. Request message for the + `ListProductSets` method. + parent (:class:`str`): + Required. The project from which ProductSets should be + listed. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductSetsAsyncPager: + Response message for the ``ListProductSets`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.ListProductSetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_product_sets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductSetsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_product_set( + self, + request: product_search_service.GetProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Gets information associated with a ProductSet. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + + Args: + request (:class:`~.product_search_service.GetProductSetRequest`): + The request object. Request message for the + `GetProductSet` method. + name (:class:`str`): + Required. Resource name of the ProductSet to get. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.GetProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_product_set( + self, + request: product_search_service.UpdateProductSetRequest = None, + *, + product_set: product_search_service.ProductSet = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Makes changes to a ProductSet resource. Only display_name can be + updated currently. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. + + Args: + request (:class:`~.product_search_service.UpdateProductSetRequest`): + The request object. Request message for the + `UpdateProductSet` method. + product_set (:class:`~.product_search_service.ProductSet`): + Required. The ProductSet resource + which replaces the one on the server. + This corresponds to the ``product_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The [FieldMask][google.protobuf.FieldMask] that + specifies which fields to update. If update_mask isn't + specified, all mutable fields are to be updated. Valid + mask path is ``display_name``. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([product_set, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.UpdateProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if product_set is not None: + request.product_set = product_set + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("product_set.name", request.product_set.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_product_set( + self, + request: product_search_service.DeleteProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a ProductSet. Products and + ReferenceImages in the ProductSet are not deleted. + The actual image files are not deleted from Google Cloud + Storage. + + Args: + request (:class:`~.product_search_service.DeleteProductSetRequest`): + The request object. Request message for the + `DeleteProductSet` method. + name (:class:`str`): + Required. Resource name of the ProductSet to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.DeleteProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def create_product( + self, + request: product_search_service.CreateProductRequest = None, + *, + parent: str = None, + product: product_search_service.Product = None, + product_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Creates and returns a new product resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. + + Args: + request (:class:`~.product_search_service.CreateProductRequest`): + The request object. Request message for the + `CreateProduct` method. + parent (:class:`str`): + Required. The project in which the Product should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`~.product_search_service.Product`): + Required. The product to create. + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (:class:`str`): + A user-supplied resource id for this Product. If set, + the server will attempt to use this value as the + resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``product_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, product, product_id]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.CreateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_products( + self, + request: product_search_service.ListProductsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsAsyncPager: + r"""Lists products in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductsRequest`): + The request object. Request message for the + `ListProducts` method. + parent (:class:`str`): + Required. The project OR ProductSet from which Products + should be listed. + + Format: ``projects/PROJECT_ID/locations/LOC_ID`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductsAsyncPager: + Response message for the ``ListProducts`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.ListProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_products, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_product( + self, + request: product_search_service.GetProductRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Gets information associated with a Product. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + + Args: + request (:class:`~.product_search_service.GetProductRequest`): + The request object. Request message for the `GetProduct` + method. + name (:class:`str`): + Required. Resource name of the Product to get. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.GetProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_product( + self, + request: product_search_service.UpdateProductRequest = None, + *, + product: product_search_service.Product = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Makes changes to a Product resource. Only the ``display_name``, + ``description``, and ``labels`` fields can be updated right now. + + If labels are updated, the change will not be reflected in + queries until the next index time. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. + + Args: + request (:class:`~.product_search_service.UpdateProductRequest`): + The request object. Request message for the + `UpdateProduct` method. + product (:class:`~.product_search_service.Product`): + Required. The Product resource which + replaces the one on the server. + product.name is immutable. + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The [FieldMask][google.protobuf.FieldMask] that + specifies which fields to update. If update_mask isn't + specified, all mutable fields are to be updated. Valid + mask paths include ``product_labels``, ``display_name``, + and ``description``. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([product, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.UpdateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if product is not None: + request.product = product + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("product.name", request.product.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_product( + self, + request: product_search_service.DeleteProductRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a product and its reference + images. + Metadata of the product and all its images will be + deleted right away, but search queries against + ProductSets containing the product may still work until + all related caches are refreshed. + + Args: + request (:class:`~.product_search_service.DeleteProductRequest`): + The request object. Request message for the + `DeleteProduct` method. + name (:class:`str`): + Required. Resource name of product to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.DeleteProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def create_reference_image( + self, + request: product_search_service.CreateReferenceImageRequest = None, + *, + parent: str = None, + reference_image: product_search_service.ReferenceImage = None, + reference_image_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ReferenceImage: + r"""Creates and returns a new ReferenceImage resource. + + The ``bounding_poly`` field is optional. If ``bounding_poly`` is + not specified, the system will try to detect regions of interest + in the image that are compatible with the product_category on + the parent product. If it is specified, detection is ALWAYS + skipped. The system converts polygons into non-rotated + rectangles. + + Note that the pipeline will resize the image if the image + resolution is too large to process (above 50MP). + + Possible errors: + + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. + + Args: + request (:class:`~.product_search_service.CreateReferenceImageRequest`): + The request object. Request message for the + `CreateReferenceImage` method. + parent (:class:`str`): + Required. Resource name of the product in which to + create the reference image. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reference_image (:class:`~.product_search_service.ReferenceImage`): + Required. The reference image to + create. If an image ID is specified, it + is ignored. + This corresponds to the ``reference_image`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reference_image_id (:class:`str`): + A user-supplied resource id for the ReferenceImage to be + added. If set, the server will attempt to use this value + as the resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``reference_image_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ReferenceImage: + A ``ReferenceImage`` represents a product image and its + associated metadata, such as bounding boxes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, reference_image, reference_image_id]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.CreateReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if reference_image is not None: + request.reference_image = reference_image + if reference_image_id is not None: + request.reference_image_id = reference_image_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_reference_image( + self, + request: product_search_service.DeleteReferenceImageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a reference image. + The image metadata will be deleted right away, but + search queries against ProductSets containing the image + may still work until all related caches are refreshed. + + The actual image files are not deleted from Google Cloud + Storage. + + Args: + request (:class:`~.product_search_service.DeleteReferenceImageRequest`): + The request object. Request message for the + `DeleteReferenceImage` method. + name (:class:`str`): + Required. The resource name of the reference image to + delete. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.DeleteReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def list_reference_images( + self, + request: product_search_service.ListReferenceImagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListReferenceImagesAsyncPager: + r"""Lists reference images. + + Possible errors: + + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. + + Args: + request (:class:`~.product_search_service.ListReferenceImagesRequest`): + The request object. Request message for the + `ListReferenceImages` method. + parent (:class:`str`): + Required. Resource name of the product containing the + reference images. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListReferenceImagesAsyncPager: + Response message for the ``ListReferenceImages`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.ListReferenceImagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_reference_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListReferenceImagesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_reference_image( + self, + request: product_search_service.GetReferenceImageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ReferenceImage: + r"""Gets information associated with a ReferenceImage. + + Possible errors: + + - Returns NOT_FOUND if the specified image does not exist. + + Args: + request (:class:`~.product_search_service.GetReferenceImageRequest`): + The request object. Request message for the + `GetReferenceImage` method. + name (:class:`str`): + Required. The resource name of the ReferenceImage to + get. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ReferenceImage: + A ``ReferenceImage`` represents a product image and its + associated metadata, such as bounding boxes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.GetReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def add_product_to_product_set( + self, + request: product_search_service.AddProductToProductSetRequest = None, + *, + name: str = None, + product: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Adds a Product to the specified ProductSet. If the Product is + already present, no change is made. + + One Product can be added to at most 100 ProductSets. + + Possible errors: + + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. + + Args: + request (:class:`~.product_search_service.AddProductToProductSetRequest`): + The request object. Request message for the + `AddProductToProductSet` method. + name (:class:`str`): + Required. The resource name for the ProductSet to + modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`str`): + Required. The resource name for the Product to be added + to this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name, product]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.AddProductToProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.add_product_to_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def remove_product_from_product_set( + self, + request: product_search_service.RemoveProductFromProductSetRequest = None, + *, + name: str = None, + product: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Removes a Product from the specified ProductSet. + + Args: + request (:class:`~.product_search_service.RemoveProductFromProductSetRequest`): + The request object. Request message for the + `RemoveProductFromProductSet` method. + name (:class:`str`): + Required. The resource name for the ProductSet to + modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`str`): + Required. The resource name for the Product to be + removed from this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name, product]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.RemoveProductFromProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.remove_product_from_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def list_products_in_product_set( + self, + request: product_search_service.ListProductsInProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsInProductSetAsyncPager: + r"""Lists the Products in a ProductSet, in an unspecified order. If + the ProductSet does not exist, the products field of the + response will be empty. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductsInProductSetRequest`): + The request object. Request message for the + `ListProductsInProductSet` method. + name (:class:`str`): + Required. The ProductSet resource for which to retrieve + Products. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductsInProductSetAsyncPager: + Response message for the ``ListProductsInProductSet`` + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.ListProductsInProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_products_in_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListProductsInProductSetAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_product_sets( + self, + request: product_search_service.ImportProductSetsRequest = None, + *, + parent: str = None, + input_config: product_search_service.ImportProductSetsInputConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Asynchronous API that imports a list of reference images to + specified product sets based on a list of image information. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) ``Operation.response`` + contains ``ImportProductSetsResponse``. (results) + + The input source of this method is a csv file on Google Cloud + Storage. For the format of the csv file please see + [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1p4beta1.ImportProductSetsGcsSource.csv_file_uri]. + + Args: + request (:class:`~.product_search_service.ImportProductSetsRequest`): + The request object. Request message for the + `ImportProductSets` method. + parent (:class:`str`): + Required. The project in which the ProductSets should be + imported. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + input_config (:class:`~.product_search_service.ImportProductSetsInputConfig`): + Required. The input content for the + list of requests. + This corresponds to the ``input_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.product_search_service.ImportProductSetsResponse``: + Response message for the ``ImportProductSets`` method. + + This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, input_config]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.ImportProductSetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if input_config is not None: + request.input_config = input_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.import_product_sets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + product_search_service.ImportProductSetsResponse, + metadata_type=product_search_service.BatchOperationMetadata, + ) + + # Done; return the response. + return response + + async def purge_products( + self, + request: product_search_service.PurgeProductsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Asynchronous API to delete all Products in a ProductSet or all + Products that are in no ProductSet. + + If a Product is a member of the specified ProductSet in addition + to other ProductSets, the Product will still be deleted. + + It is recommended to not delete the specified ProductSet until + after this operation has completed. It is also recommended to + not add any of the Products involved in the batch delete to a + new ProductSet while this operation is running because those + Products may still end up deleted. + + It's not possible to undo the PurgeProducts operation. + Therefore, it is recommended to keep the csv files used in + ImportProductSets (if that was how you originally built the + Product Set) before starting PurgeProducts, in case you need to + re-import the data after deletion. + + If the plan is to purge all of the Products from a ProductSet + and then re-use the empty ProductSet to re-import new Products + into the empty ProductSet, you must wait until the PurgeProducts + operation has finished for that ProductSet. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) + + Args: + request (:class:`~.product_search_service.PurgeProductsRequest`): + The request object. Request message for the + `PurgeProducts` method. + parent (:class:`str`): + Required. The project and location in which the Products + should be deleted. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.empty.Empty``: A generic empty message that + you can re-use to avoid defining duplicated empty + messages in your APIs. A typical example is to use it as + the request or the response type of an API method. For + instance: + + :: + + service Foo { + rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); + } + + The JSON representation for ``Empty`` is empty JSON + object ``{}``. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = product_search_service.PurgeProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.purge_products, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty.Empty, + metadata_type=product_search_service.BatchOperationMetadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ProductSearchAsyncClient",) diff --git a/google/cloud/vision_v1p4beta1/services/product_search/client.py b/google/cloud/vision_v1p4beta1/services/product_search/client.py new file mode 100644 index 00000000..42410736 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/services/product_search/client.py @@ -0,0 +1,2095 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.vision_v1p4beta1.services.product_search import pagers +from google.cloud.vision_v1p4beta1.types import geometry +from google.cloud.vision_v1p4beta1.types import product_search_service +from google.protobuf import empty_pb2 as empty # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + +from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import ProductSearchGrpcTransport +from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport + + +class ProductSearchClientMeta(type): + """Metaclass for the ProductSearch client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[ProductSearchTransport]] + _transport_registry["grpc"] = ProductSearchGrpcTransport + _transport_registry["grpc_asyncio"] = ProductSearchGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[ProductSearchTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class ProductSearchClient(metaclass=ProductSearchClientMeta): + """Manages Products and ProductSets of reference images for use in + product search. It uses the following resource model: + + - The API has a collection of + [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. + + In parallel, + + - The API has a collection of + [Product][google.cloud.vision.v1p4beta1.Product] resources, named + ``projects/*/locations/*/products/*`` + + - Each [Product][google.cloud.vision.v1p4beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "vision.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @staticmethod + def product_path(project: str, location: str, product: str,) -> str: + """Return a fully-qualified product string.""" + return "projects/{project}/locations/{location}/products/{product}".format( + project=project, location=location, product=product, + ) + + @staticmethod + def parse_product_path(path: str) -> Dict[str, str]: + """Parse a product path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def product_set_path(project: str, location: str, product_set: str,) -> str: + """Return a fully-qualified product_set string.""" + return "projects/{project}/locations/{location}/productSets/{product_set}".format( + project=project, location=location, product_set=product_set, + ) + + @staticmethod + def parse_product_set_path(path: str) -> Dict[str, str]: + """Parse a product_set path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def reference_image_path( + project: str, location: str, product: str, reference_image: str, + ) -> str: + """Return a fully-qualified reference_image string.""" + return "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( + project=project, + location=location, + product=product, + reference_image=reference_image, + ) + + @staticmethod + def parse_reference_image_path(path: str) -> Dict[str, str]: + """Parse a reference_image path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)/referenceImages/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, ProductSearchTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the product search client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.ProductSearchTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, ProductSearchTransport): + # transport is a ProductSearchTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def create_product_set( + self, + request: product_search_service.CreateProductSetRequest = None, + *, + parent: str = None, + product_set: product_search_service.ProductSet = None, + product_set_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Creates and returns a new ProductSet resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. + + Args: + request (:class:`~.product_search_service.CreateProductSetRequest`): + The request object. Request message for the + `CreateProductSet` method. + parent (:class:`str`): + Required. The project in which the ProductSet should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_set (:class:`~.product_search_service.ProductSet`): + Required. The ProductSet to create. + This corresponds to the ``product_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_set_id (:class:`str`): + A user-supplied resource id for this ProductSet. If set, + the server will attempt to use this value as the + resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``product_set_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product_set, product_set_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.CreateProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.CreateProductSetRequest): + request = product_search_service.CreateProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if product_set is not None: + request.product_set = product_set + if product_set_id is not None: + request.product_set_id = product_set_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_product_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_product_sets( + self, + request: product_search_service.ListProductSetsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductSetsPager: + r"""Lists ProductSets in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductSetsRequest`): + The request object. Request message for the + `ListProductSets` method. + parent (:class:`str`): + Required. The project from which ProductSets should be + listed. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductSetsPager: + Response message for the ``ListProductSets`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.ListProductSetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.ListProductSetsRequest): + request = product_search_service.ListProductSetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_product_sets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductSetsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_product_set( + self, + request: product_search_service.GetProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Gets information associated with a ProductSet. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + + Args: + request (:class:`~.product_search_service.GetProductSetRequest`): + The request object. Request message for the + `GetProductSet` method. + name (:class:`str`): + Required. Resource name of the ProductSet to get. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.GetProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.GetProductSetRequest): + request = product_search_service.GetProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_product_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_product_set( + self, + request: product_search_service.UpdateProductSetRequest = None, + *, + product_set: product_search_service.ProductSet = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ProductSet: + r"""Makes changes to a ProductSet resource. Only display_name can be + updated currently. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. + + Args: + request (:class:`~.product_search_service.UpdateProductSetRequest`): + The request object. Request message for the + `UpdateProductSet` method. + product_set (:class:`~.product_search_service.ProductSet`): + Required. The ProductSet resource + which replaces the one on the server. + This corresponds to the ``product_set`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The [FieldMask][google.protobuf.FieldMask] that + specifies which fields to update. If update_mask isn't + specified, all mutable fields are to be updated. Valid + mask path is ``display_name``. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ProductSet: + A ProductSet contains Products. A + ProductSet can contain a maximum of 1 + million reference images. If the limit + is exceeded, periodic indexing will + fail. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product_set, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.UpdateProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.UpdateProductSetRequest): + request = product_search_service.UpdateProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if product_set is not None: + request.product_set = product_set + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_product_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("product_set.name", request.product_set.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_product_set( + self, + request: product_search_service.DeleteProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a ProductSet. Products and + ReferenceImages in the ProductSet are not deleted. + The actual image files are not deleted from Google Cloud + Storage. + + Args: + request (:class:`~.product_search_service.DeleteProductSetRequest`): + The request object. Request message for the + `DeleteProductSet` method. + name (:class:`str`): + Required. Resource name of the ProductSet to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.DeleteProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.DeleteProductSetRequest): + request = product_search_service.DeleteProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_product_set] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def create_product( + self, + request: product_search_service.CreateProductRequest = None, + *, + parent: str = None, + product: product_search_service.Product = None, + product_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Creates and returns a new product resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. + + Args: + request (:class:`~.product_search_service.CreateProductRequest`): + The request object. Request message for the + `CreateProduct` method. + parent (:class:`str`): + Required. The project in which the Product should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`~.product_search_service.Product`): + Required. The product to create. + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product_id (:class:`str`): + A user-supplied resource id for this Product. If set, + the server will attempt to use this value as the + resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``product_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, product, product_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.CreateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.CreateProductRequest): + request = product_search_service.CreateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if product is not None: + request.product = product + if product_id is not None: + request.product_id = product_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_products( + self, + request: product_search_service.ListProductsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsPager: + r"""Lists products in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductsRequest`): + The request object. Request message for the + `ListProducts` method. + parent (:class:`str`): + Required. The project OR ProductSet from which Products + should be listed. + + Format: ``projects/PROJECT_ID/locations/LOC_ID`` + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductsPager: + Response message for the ``ListProducts`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.ListProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.ListProductsRequest): + request = product_search_service.ListProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_product( + self, + request: product_search_service.GetProductRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Gets information associated with a Product. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + + Args: + request (:class:`~.product_search_service.GetProductRequest`): + The request object. Request message for the `GetProduct` + method. + name (:class:`str`): + Required. Resource name of the Product to get. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.GetProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.GetProductRequest): + request = product_search_service.GetProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_product( + self, + request: product_search_service.UpdateProductRequest = None, + *, + product: product_search_service.Product = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.Product: + r"""Makes changes to a Product resource. Only the ``display_name``, + ``description``, and ``labels`` fields can be updated right now. + + If labels are updated, the change will not be reflected in + queries until the next index time. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. + + Args: + request (:class:`~.product_search_service.UpdateProductRequest`): + The request object. Request message for the + `UpdateProduct` method. + product (:class:`~.product_search_service.Product`): + Required. The Product resource which + replaces the one on the server. + product.name is immutable. + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The [FieldMask][google.protobuf.FieldMask] that + specifies which fields to update. If update_mask isn't + specified, all mutable fields are to be updated. Valid + mask paths include ``product_labels``, ``display_name``, + and ``description``. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.Product: + A Product contains ReferenceImages. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([product, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.UpdateProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.UpdateProductRequest): + request = product_search_service.UpdateProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if product is not None: + request.product = product + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("product.name", request.product.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_product( + self, + request: product_search_service.DeleteProductRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a product and its reference + images. + Metadata of the product and all its images will be + deleted right away, but search queries against + ProductSets containing the product may still work until + all related caches are refreshed. + + Args: + request (:class:`~.product_search_service.DeleteProductRequest`): + The request object. Request message for the + `DeleteProduct` method. + name (:class:`str`): + Required. Resource name of product to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.DeleteProductRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.DeleteProductRequest): + request = product_search_service.DeleteProductRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_product] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def create_reference_image( + self, + request: product_search_service.CreateReferenceImageRequest = None, + *, + parent: str = None, + reference_image: product_search_service.ReferenceImage = None, + reference_image_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ReferenceImage: + r"""Creates and returns a new ReferenceImage resource. + + The ``bounding_poly`` field is optional. If ``bounding_poly`` is + not specified, the system will try to detect regions of interest + in the image that are compatible with the product_category on + the parent product. If it is specified, detection is ALWAYS + skipped. The system converts polygons into non-rotated + rectangles. + + Note that the pipeline will resize the image if the image + resolution is too large to process (above 50MP). + + Possible errors: + + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. + + Args: + request (:class:`~.product_search_service.CreateReferenceImageRequest`): + The request object. Request message for the + `CreateReferenceImage` method. + parent (:class:`str`): + Required. Resource name of the product in which to + create the reference image. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reference_image (:class:`~.product_search_service.ReferenceImage`): + Required. The reference image to + create. If an image ID is specified, it + is ignored. + This corresponds to the ``reference_image`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reference_image_id (:class:`str`): + A user-supplied resource id for the ReferenceImage to be + added. If set, the server will attempt to use this value + as the resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + This corresponds to the ``reference_image_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ReferenceImage: + A ``ReferenceImage`` represents a product image and its + associated metadata, such as bounding boxes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, reference_image, reference_image_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.CreateReferenceImageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.CreateReferenceImageRequest): + request = product_search_service.CreateReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if reference_image is not None: + request.reference_image = reference_image + if reference_image_id is not None: + request.reference_image_id = reference_image_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_reference_image] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_reference_image( + self, + request: product_search_service.DeleteReferenceImageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Permanently deletes a reference image. + The image metadata will be deleted right away, but + search queries against ProductSets containing the image + may still work until all related caches are refreshed. + + The actual image files are not deleted from Google Cloud + Storage. + + Args: + request (:class:`~.product_search_service.DeleteReferenceImageRequest`): + The request object. Request message for the + `DeleteReferenceImage` method. + name (:class:`str`): + Required. The resource name of the reference image to + delete. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.DeleteReferenceImageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.DeleteReferenceImageRequest): + request = product_search_service.DeleteReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_reference_image] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def list_reference_images( + self, + request: product_search_service.ListReferenceImagesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListReferenceImagesPager: + r"""Lists reference images. + + Possible errors: + + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. + + Args: + request (:class:`~.product_search_service.ListReferenceImagesRequest`): + The request object. Request message for the + `ListReferenceImages` method. + parent (:class:`str`): + Required. Resource name of the product containing the + reference images. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListReferenceImagesPager: + Response message for the ``ListReferenceImages`` method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.ListReferenceImagesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.ListReferenceImagesRequest): + request = product_search_service.ListReferenceImagesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_reference_images] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListReferenceImagesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_reference_image( + self, + request: product_search_service.GetReferenceImageRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> product_search_service.ReferenceImage: + r"""Gets information associated with a ReferenceImage. + + Possible errors: + + - Returns NOT_FOUND if the specified image does not exist. + + Args: + request (:class:`~.product_search_service.GetReferenceImageRequest`): + The request object. Request message for the + `GetReferenceImage` method. + name (:class:`str`): + Required. The resource name of the ReferenceImage to + get. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.product_search_service.ReferenceImage: + A ``ReferenceImage`` represents a product image and its + associated metadata, such as bounding boxes. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.GetReferenceImageRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.GetReferenceImageRequest): + request = product_search_service.GetReferenceImageRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_reference_image] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def add_product_to_product_set( + self, + request: product_search_service.AddProductToProductSetRequest = None, + *, + name: str = None, + product: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Adds a Product to the specified ProductSet. If the Product is + already present, no change is made. + + One Product can be added to at most 100 ProductSets. + + Possible errors: + + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. + + Args: + request (:class:`~.product_search_service.AddProductToProductSetRequest`): + The request object. Request message for the + `AddProductToProductSet` method. + name (:class:`str`): + Required. The resource name for the ProductSet to + modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`str`): + Required. The resource name for the Product to be added + to this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, product]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.AddProductToProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, product_search_service.AddProductToProductSetRequest + ): + request = product_search_service.AddProductToProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.add_product_to_product_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def remove_product_from_product_set( + self, + request: product_search_service.RemoveProductFromProductSetRequest = None, + *, + name: str = None, + product: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Removes a Product from the specified ProductSet. + + Args: + request (:class:`~.product_search_service.RemoveProductFromProductSetRequest`): + The request object. Request message for the + `RemoveProductFromProductSet` method. + name (:class:`str`): + Required. The resource name for the ProductSet to + modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + product (:class:`str`): + Required. The resource name for the Product to be + removed from this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + This corresponds to the ``product`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name, product]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.RemoveProductFromProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, product_search_service.RemoveProductFromProductSetRequest + ): + request = product_search_service.RemoveProductFromProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if product is not None: + request.product = product + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.remove_product_from_product_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def list_products_in_product_set( + self, + request: product_search_service.ListProductsInProductSetRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListProductsInProductSetPager: + r"""Lists the Products in a ProductSet, in an unspecified order. If + the ProductSet does not exist, the products field of the + response will be empty. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Args: + request (:class:`~.product_search_service.ListProductsInProductSetRequest`): + The request object. Request message for the + `ListProductsInProductSet` method. + name (:class:`str`): + Required. The ProductSet resource for which to retrieve + Products. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListProductsInProductSetPager: + Response message for the ``ListProductsInProductSet`` + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.ListProductsInProductSetRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, product_search_service.ListProductsInProductSetRequest + ): + request = product_search_service.ListProductsInProductSetRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.list_products_in_product_set + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListProductsInProductSetPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def import_product_sets( + self, + request: product_search_service.ImportProductSetsRequest = None, + *, + parent: str = None, + input_config: product_search_service.ImportProductSetsInputConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Asynchronous API that imports a list of reference images to + specified product sets based on a list of image information. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) ``Operation.response`` + contains ``ImportProductSetsResponse``. (results) + + The input source of this method is a csv file on Google Cloud + Storage. For the format of the csv file please see + [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1p4beta1.ImportProductSetsGcsSource.csv_file_uri]. + + Args: + request (:class:`~.product_search_service.ImportProductSetsRequest`): + The request object. Request message for the + `ImportProductSets` method. + parent (:class:`str`): + Required. The project in which the ProductSets should be + imported. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + input_config (:class:`~.product_search_service.ImportProductSetsInputConfig`): + Required. The input content for the + list of requests. + This corresponds to the ``input_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.product_search_service.ImportProductSetsResponse``: + Response message for the ``ImportProductSets`` method. + + This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, input_config]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.ImportProductSetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.ImportProductSetsRequest): + request = product_search_service.ImportProductSetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if input_config is not None: + request.input_config = input_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_product_sets] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + product_search_service.ImportProductSetsResponse, + metadata_type=product_search_service.BatchOperationMetadata, + ) + + # Done; return the response. + return response + + def purge_products( + self, + request: product_search_service.PurgeProductsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Asynchronous API to delete all Products in a ProductSet or all + Products that are in no ProductSet. + + If a Product is a member of the specified ProductSet in addition + to other ProductSets, the Product will still be deleted. + + It is recommended to not delete the specified ProductSet until + after this operation has completed. It is also recommended to + not add any of the Products involved in the batch delete to a + new ProductSet while this operation is running because those + Products may still end up deleted. + + It's not possible to undo the PurgeProducts operation. + Therefore, it is recommended to keep the csv files used in + ImportProductSets (if that was how you originally built the + Product Set) before starting PurgeProducts, in case you need to + re-import the data after deletion. + + If the plan is to purge all of the Products from a ProductSet + and then re-use the empty ProductSet to re-import new Products + into the empty ProductSet, you must wait until the PurgeProducts + operation has finished for that ProductSet. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) + + Args: + request (:class:`~.product_search_service.PurgeProductsRequest`): + The request object. Request message for the + `PurgeProducts` method. + parent (:class:`str`): + Required. The project and location in which the Products + should be deleted. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.empty.Empty``: A generic empty message that + you can re-use to avoid defining duplicated empty + messages in your APIs. A typical example is to use it as + the request or the response type of an API method. For + instance: + + :: + + service Foo { + rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); + } + + The JSON representation for ``Empty`` is empty JSON + object ``{}``. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a product_search_service.PurgeProductsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, product_search_service.PurgeProductsRequest): + request = product_search_service.PurgeProductsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.purge_products] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty.Empty, + metadata_type=product_search_service.BatchOperationMetadata, + ) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("ProductSearchClient",) diff --git a/google/cloud/vision_v1p4beta1/services/product_search/pagers.py b/google/cloud/vision_v1p4beta1/services/product_search/pagers.py new file mode 100644 index 00000000..c3ac34cd --- /dev/null +++ b/google/cloud/vision_v1p4beta1/services/product_search/pagers.py @@ -0,0 +1,546 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.vision_v1p4beta1.types import product_search_service + + +class ListProductSetsPager: + """A pager for iterating through ``list_product_sets`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductSetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``product_sets`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProductSets`` requests and continue to iterate + through the ``product_sets`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductSetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., product_search_service.ListProductSetsResponse], + request: product_search_service.ListProductSetsRequest, + response: product_search_service.ListProductSetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductSetsRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductSetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductSetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[product_search_service.ListProductSetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[product_search_service.ProductSet]: + for page in self.pages: + yield from page.product_sets + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListProductSetsAsyncPager: + """A pager for iterating through ``list_product_sets`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductSetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``product_sets`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProductSets`` requests and continue to iterate + through the ``product_sets`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductSetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[product_search_service.ListProductSetsResponse] + ], + request: product_search_service.ListProductSetsRequest, + response: product_search_service.ListProductSetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductSetsRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductSetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductSetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[product_search_service.ListProductSetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[product_search_service.ProductSet]: + async def async_generator(): + async for page in self.pages: + for response in page.product_sets: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListProductsPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., product_search_service.ListProductsResponse], + request: product_search_service.ListProductsRequest, + response: product_search_service.ListProductsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductsRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[product_search_service.ListProductsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[product_search_service.Product]: + for page in self.pages: + yield from page.products + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListProductsAsyncPager: + """A pager for iterating through ``list_products`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProducts`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[product_search_service.ListProductsResponse]], + request: product_search_service.ListProductsRequest, + response: product_search_service.ListProductsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductsRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[product_search_service.ListProductsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[product_search_service.Product]: + async def async_generator(): + async for page in self.pages: + for response in page.products: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListReferenceImagesPager: + """A pager for iterating through ``list_reference_images`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListReferenceImagesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``reference_images`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListReferenceImages`` requests and continue to iterate + through the ``reference_images`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListReferenceImagesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., product_search_service.ListReferenceImagesResponse], + request: product_search_service.ListReferenceImagesRequest, + response: product_search_service.ListReferenceImagesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListReferenceImagesRequest`): + The initial request object. + response (:class:`~.product_search_service.ListReferenceImagesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListReferenceImagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[product_search_service.ListReferenceImagesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[product_search_service.ReferenceImage]: + for page in self.pages: + yield from page.reference_images + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListReferenceImagesAsyncPager: + """A pager for iterating through ``list_reference_images`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListReferenceImagesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``reference_images`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListReferenceImages`` requests and continue to iterate + through the ``reference_images`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListReferenceImagesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[product_search_service.ListReferenceImagesResponse] + ], + request: product_search_service.ListReferenceImagesRequest, + response: product_search_service.ListReferenceImagesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListReferenceImagesRequest`): + The initial request object. + response (:class:`~.product_search_service.ListReferenceImagesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListReferenceImagesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[product_search_service.ListReferenceImagesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[product_search_service.ReferenceImage]: + async def async_generator(): + async for page in self.pages: + for response in page.reference_images: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListProductsInProductSetPager: + """A pager for iterating through ``list_products_in_product_set`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductsInProductSetResponse` object, and + provides an ``__iter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListProductsInProductSet`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductsInProductSetResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., product_search_service.ListProductsInProductSetResponse], + request: product_search_service.ListProductsInProductSetRequest, + response: product_search_service.ListProductsInProductSetResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductsInProductSetRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductsInProductSetResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductsInProductSetRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages( + self, + ) -> Iterable[product_search_service.ListProductsInProductSetResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[product_search_service.Product]: + for page in self.pages: + yield from page.products + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListProductsInProductSetAsyncPager: + """A pager for iterating through ``list_products_in_product_set`` requests. + + This class thinly wraps an initial + :class:`~.product_search_service.ListProductsInProductSetResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``products`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListProductsInProductSet`` requests and continue to iterate + through the ``products`` field on the + corresponding responses. + + All the usual :class:`~.product_search_service.ListProductsInProductSetResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[product_search_service.ListProductsInProductSetResponse] + ], + request: product_search_service.ListProductsInProductSetRequest, + response: product_search_service.ListProductsInProductSetResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.product_search_service.ListProductsInProductSetRequest`): + The initial request object. + response (:class:`~.product_search_service.ListProductsInProductSetResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = product_search_service.ListProductsInProductSetRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[product_search_service.ListProductsInProductSetResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[product_search_service.Product]: + async def async_generator(): + async for page in self.pages: + for response in page.products: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/vision_v1p4beta1/services/product_search/transports/__init__.py b/google/cloud/vision_v1p4beta1/services/product_search/transports/__init__.py new file mode 100644 index 00000000..2d57de48 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/services/product_search/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import ProductSearchTransport +from .grpc import ProductSearchGrpcTransport +from .grpc_asyncio import ProductSearchGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProductSearchTransport]] +_transport_registry["grpc"] = ProductSearchGrpcTransport +_transport_registry["grpc_asyncio"] = ProductSearchGrpcAsyncIOTransport + + +__all__ = ( + "ProductSearchTransport", + "ProductSearchGrpcTransport", + "ProductSearchGrpcAsyncIOTransport", +) diff --git a/google/cloud/vision_v1p4beta1/services/product_search/transports/base.py b/google/cloud/vision_v1p4beta1/services/product_search/transports/base.py new file mode 100644 index 00000000..3d3d71bd --- /dev/null +++ b/google/cloud/vision_v1p4beta1/services/product_search/transports/base.py @@ -0,0 +1,549 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.vision_v1p4beta1.types import product_search_service +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution("google-cloud-vision",).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class ProductSearchTransport(abc.ABC): + """Abstract transport class for ProductSearch.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ) + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_product_set: gapic_v1.method.wrap_method( + self.create_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_product_sets: gapic_v1.method.wrap_method( + self.list_product_sets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_product_set: gapic_v1.method.wrap_method( + self.get_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update_product_set: gapic_v1.method.wrap_method( + self.update_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.delete_product_set: gapic_v1.method.wrap_method( + self.delete_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.create_product: gapic_v1.method.wrap_method( + self.create_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_products: gapic_v1.method.wrap_method( + self.list_products, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_product: gapic_v1.method.wrap_method( + self.get_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.update_product: gapic_v1.method.wrap_method( + self.update_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.delete_product: gapic_v1.method.wrap_method( + self.delete_product, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.create_reference_image: gapic_v1.method.wrap_method( + self.create_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.delete_reference_image: gapic_v1.method.wrap_method( + self.delete_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_reference_images: gapic_v1.method.wrap_method( + self.list_reference_images, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_reference_image: gapic_v1.method.wrap_method( + self.get_reference_image, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.add_product_to_product_set: gapic_v1.method.wrap_method( + self.add_product_to_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.remove_product_from_product_set: gapic_v1.method.wrap_method( + self.remove_product_from_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list_products_in_product_set: gapic_v1.method.wrap_method( + self.list_products_in_product_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.import_product_sets: gapic_v1.method.wrap_method( + self.import_product_sets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type(), + ), + default_timeout=600.0, + client_info=client_info, + ), + self.purge_products: gapic_v1.method.wrap_method( + self.purge_products, default_timeout=None, client_info=client_info, + ), + } + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_product_set( + self, + ) -> typing.Callable[ + [product_search_service.CreateProductSetRequest], + typing.Union[ + product_search_service.ProductSet, + typing.Awaitable[product_search_service.ProductSet], + ], + ]: + raise NotImplementedError() + + @property + def list_product_sets( + self, + ) -> typing.Callable[ + [product_search_service.ListProductSetsRequest], + typing.Union[ + product_search_service.ListProductSetsResponse, + typing.Awaitable[product_search_service.ListProductSetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_product_set( + self, + ) -> typing.Callable[ + [product_search_service.GetProductSetRequest], + typing.Union[ + product_search_service.ProductSet, + typing.Awaitable[product_search_service.ProductSet], + ], + ]: + raise NotImplementedError() + + @property + def update_product_set( + self, + ) -> typing.Callable[ + [product_search_service.UpdateProductSetRequest], + typing.Union[ + product_search_service.ProductSet, + typing.Awaitable[product_search_service.ProductSet], + ], + ]: + raise NotImplementedError() + + @property + def delete_product_set( + self, + ) -> typing.Callable[ + [product_search_service.DeleteProductSetRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def create_product( + self, + ) -> typing.Callable[ + [product_search_service.CreateProductRequest], + typing.Union[ + product_search_service.Product, + typing.Awaitable[product_search_service.Product], + ], + ]: + raise NotImplementedError() + + @property + def list_products( + self, + ) -> typing.Callable[ + [product_search_service.ListProductsRequest], + typing.Union[ + product_search_service.ListProductsResponse, + typing.Awaitable[product_search_service.ListProductsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_product( + self, + ) -> typing.Callable[ + [product_search_service.GetProductRequest], + typing.Union[ + product_search_service.Product, + typing.Awaitable[product_search_service.Product], + ], + ]: + raise NotImplementedError() + + @property + def update_product( + self, + ) -> typing.Callable[ + [product_search_service.UpdateProductRequest], + typing.Union[ + product_search_service.Product, + typing.Awaitable[product_search_service.Product], + ], + ]: + raise NotImplementedError() + + @property + def delete_product( + self, + ) -> typing.Callable[ + [product_search_service.DeleteProductRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def create_reference_image( + self, + ) -> typing.Callable[ + [product_search_service.CreateReferenceImageRequest], + typing.Union[ + product_search_service.ReferenceImage, + typing.Awaitable[product_search_service.ReferenceImage], + ], + ]: + raise NotImplementedError() + + @property + def delete_reference_image( + self, + ) -> typing.Callable[ + [product_search_service.DeleteReferenceImageRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def list_reference_images( + self, + ) -> typing.Callable[ + [product_search_service.ListReferenceImagesRequest], + typing.Union[ + product_search_service.ListReferenceImagesResponse, + typing.Awaitable[product_search_service.ListReferenceImagesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_reference_image( + self, + ) -> typing.Callable[ + [product_search_service.GetReferenceImageRequest], + typing.Union[ + product_search_service.ReferenceImage, + typing.Awaitable[product_search_service.ReferenceImage], + ], + ]: + raise NotImplementedError() + + @property + def add_product_to_product_set( + self, + ) -> typing.Callable[ + [product_search_service.AddProductToProductSetRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def remove_product_from_product_set( + self, + ) -> typing.Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def list_products_in_product_set( + self, + ) -> typing.Callable[ + [product_search_service.ListProductsInProductSetRequest], + typing.Union[ + product_search_service.ListProductsInProductSetResponse, + typing.Awaitable[product_search_service.ListProductsInProductSetResponse], + ], + ]: + raise NotImplementedError() + + @property + def import_product_sets( + self, + ) -> typing.Callable[ + [product_search_service.ImportProductSetsRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def purge_products( + self, + ) -> typing.Callable[ + [product_search_service.PurgeProductsRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + +__all__ = ("ProductSearchTransport",) diff --git a/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py b/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py new file mode 100644 index 00000000..5f060e60 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py @@ -0,0 +1,956 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.vision_v1p4beta1.types import product_search_service +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO + + +class ProductSearchGrpcTransport(ProductSearchTransport): + """gRPC backend transport for ProductSearch. + + Manages Products and ProductSets of reference images for use in + product search. It uses the following resource model: + + - The API has a collection of + [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. + + In parallel, + + - The API has a collection of + [Product][google.cloud.vision.v1p4beta1.Product] resources, named + ``projects/*/locations/*/products/*`` + + - Each [Product][google.cloud.vision.v1p4beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def create_product_set( + self, + ) -> Callable[ + [product_search_service.CreateProductSetRequest], + product_search_service.ProductSet, + ]: + r"""Return a callable for the create product set method over gRPC. + + Creates and returns a new ProductSet resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. + + Returns: + Callable[[~.CreateProductSetRequest], + ~.ProductSet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_product_set" not in self._stubs: + self._stubs["create_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/CreateProductSet", + request_serializer=product_search_service.CreateProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["create_product_set"] + + @property + def list_product_sets( + self, + ) -> Callable[ + [product_search_service.ListProductSetsRequest], + product_search_service.ListProductSetsResponse, + ]: + r"""Return a callable for the list product sets method over gRPC. + + Lists ProductSets in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. + + Returns: + Callable[[~.ListProductSetsRequest], + ~.ListProductSetsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_product_sets" not in self._stubs: + self._stubs["list_product_sets"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/ListProductSets", + request_serializer=product_search_service.ListProductSetsRequest.serialize, + response_deserializer=product_search_service.ListProductSetsResponse.deserialize, + ) + return self._stubs["list_product_sets"] + + @property + def get_product_set( + self, + ) -> Callable[ + [product_search_service.GetProductSetRequest], product_search_service.ProductSet + ]: + r"""Return a callable for the get product set method over gRPC. + + Gets information associated with a ProductSet. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + + Returns: + Callable[[~.GetProductSetRequest], + ~.ProductSet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_product_set" not in self._stubs: + self._stubs["get_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/GetProductSet", + request_serializer=product_search_service.GetProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["get_product_set"] + + @property + def update_product_set( + self, + ) -> Callable[ + [product_search_service.UpdateProductSetRequest], + product_search_service.ProductSet, + ]: + r"""Return a callable for the update product set method over gRPC. + + Makes changes to a ProductSet resource. Only display_name can be + updated currently. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. + + Returns: + Callable[[~.UpdateProductSetRequest], + ~.ProductSet]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_product_set" not in self._stubs: + self._stubs["update_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/UpdateProductSet", + request_serializer=product_search_service.UpdateProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["update_product_set"] + + @property + def delete_product_set( + self, + ) -> Callable[[product_search_service.DeleteProductSetRequest], empty.Empty]: + r"""Return a callable for the delete product set method over gRPC. + + Permanently deletes a ProductSet. Products and + ReferenceImages in the ProductSet are not deleted. + The actual image files are not deleted from Google Cloud + Storage. + + Returns: + Callable[[~.DeleteProductSetRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_product_set" not in self._stubs: + self._stubs["delete_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteProductSet", + request_serializer=product_search_service.DeleteProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_product_set"] + + @property + def create_product( + self, + ) -> Callable[ + [product_search_service.CreateProductRequest], product_search_service.Product + ]: + r"""Return a callable for the create product method over gRPC. + + Creates and returns a new product resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. + + Returns: + Callable[[~.CreateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_product" not in self._stubs: + self._stubs["create_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/CreateProduct", + request_serializer=product_search_service.CreateProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["create_product"] + + @property + def list_products( + self, + ) -> Callable[ + [product_search_service.ListProductsRequest], + product_search_service.ListProductsResponse, + ]: + r"""Return a callable for the list products method over gRPC. + + Lists products in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Returns: + Callable[[~.ListProductsRequest], + ~.ListProductsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_products" not in self._stubs: + self._stubs["list_products"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/ListProducts", + request_serializer=product_search_service.ListProductsRequest.serialize, + response_deserializer=product_search_service.ListProductsResponse.deserialize, + ) + return self._stubs["list_products"] + + @property + def get_product( + self, + ) -> Callable[ + [product_search_service.GetProductRequest], product_search_service.Product + ]: + r"""Return a callable for the get product method over gRPC. + + Gets information associated with a Product. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + + Returns: + Callable[[~.GetProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_product" not in self._stubs: + self._stubs["get_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/GetProduct", + request_serializer=product_search_service.GetProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["get_product"] + + @property + def update_product( + self, + ) -> Callable[ + [product_search_service.UpdateProductRequest], product_search_service.Product + ]: + r"""Return a callable for the update product method over gRPC. + + Makes changes to a Product resource. Only the ``display_name``, + ``description``, and ``labels`` fields can be updated right now. + + If labels are updated, the change will not be reflected in + queries until the next index time. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. + + Returns: + Callable[[~.UpdateProductRequest], + ~.Product]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_product" not in self._stubs: + self._stubs["update_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/UpdateProduct", + request_serializer=product_search_service.UpdateProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["update_product"] + + @property + def delete_product( + self, + ) -> Callable[[product_search_service.DeleteProductRequest], empty.Empty]: + r"""Return a callable for the delete product method over gRPC. + + Permanently deletes a product and its reference + images. + Metadata of the product and all its images will be + deleted right away, but search queries against + ProductSets containing the product may still work until + all related caches are refreshed. + + Returns: + Callable[[~.DeleteProductRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_product" not in self._stubs: + self._stubs["delete_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteProduct", + request_serializer=product_search_service.DeleteProductRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_product"] + + @property + def create_reference_image( + self, + ) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + product_search_service.ReferenceImage, + ]: + r"""Return a callable for the create reference image method over gRPC. + + Creates and returns a new ReferenceImage resource. + + The ``bounding_poly`` field is optional. If ``bounding_poly`` is + not specified, the system will try to detect regions of interest + in the image that are compatible with the product_category on + the parent product. If it is specified, detection is ALWAYS + skipped. The system converts polygons into non-rotated + rectangles. + + Note that the pipeline will resize the image if the image + resolution is too large to process (above 50MP). + + Possible errors: + + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. + + Returns: + Callable[[~.CreateReferenceImageRequest], + ~.ReferenceImage]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_reference_image" not in self._stubs: + self._stubs["create_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/CreateReferenceImage", + request_serializer=product_search_service.CreateReferenceImageRequest.serialize, + response_deserializer=product_search_service.ReferenceImage.deserialize, + ) + return self._stubs["create_reference_image"] + + @property + def delete_reference_image( + self, + ) -> Callable[[product_search_service.DeleteReferenceImageRequest], empty.Empty]: + r"""Return a callable for the delete reference image method over gRPC. + + Permanently deletes a reference image. + The image metadata will be deleted right away, but + search queries against ProductSets containing the image + may still work until all related caches are refreshed. + + The actual image files are not deleted from Google Cloud + Storage. + + Returns: + Callable[[~.DeleteReferenceImageRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_reference_image" not in self._stubs: + self._stubs["delete_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteReferenceImage", + request_serializer=product_search_service.DeleteReferenceImageRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_reference_image"] + + @property + def list_reference_images( + self, + ) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + product_search_service.ListReferenceImagesResponse, + ]: + r"""Return a callable for the list reference images method over gRPC. + + Lists reference images. + + Possible errors: + + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. + + Returns: + Callable[[~.ListReferenceImagesRequest], + ~.ListReferenceImagesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_reference_images" not in self._stubs: + self._stubs["list_reference_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/ListReferenceImages", + request_serializer=product_search_service.ListReferenceImagesRequest.serialize, + response_deserializer=product_search_service.ListReferenceImagesResponse.deserialize, + ) + return self._stubs["list_reference_images"] + + @property + def get_reference_image( + self, + ) -> Callable[ + [product_search_service.GetReferenceImageRequest], + product_search_service.ReferenceImage, + ]: + r"""Return a callable for the get reference image method over gRPC. + + Gets information associated with a ReferenceImage. + + Possible errors: + + - Returns NOT_FOUND if the specified image does not exist. + + Returns: + Callable[[~.GetReferenceImageRequest], + ~.ReferenceImage]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_reference_image" not in self._stubs: + self._stubs["get_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/GetReferenceImage", + request_serializer=product_search_service.GetReferenceImageRequest.serialize, + response_deserializer=product_search_service.ReferenceImage.deserialize, + ) + return self._stubs["get_reference_image"] + + @property + def add_product_to_product_set( + self, + ) -> Callable[[product_search_service.AddProductToProductSetRequest], empty.Empty]: + r"""Return a callable for the add product to product set method over gRPC. + + Adds a Product to the specified ProductSet. If the Product is + already present, no change is made. + + One Product can be added to at most 100 ProductSets. + + Possible errors: + + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. + + Returns: + Callable[[~.AddProductToProductSetRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "add_product_to_product_set" not in self._stubs: + self._stubs["add_product_to_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/AddProductToProductSet", + request_serializer=product_search_service.AddProductToProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["add_product_to_product_set"] + + @property + def remove_product_from_product_set( + self, + ) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], empty.Empty + ]: + r"""Return a callable for the remove product from product + set method over gRPC. + + Removes a Product from the specified ProductSet. + + Returns: + Callable[[~.RemoveProductFromProductSetRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "remove_product_from_product_set" not in self._stubs: + self._stubs[ + "remove_product_from_product_set" + ] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/RemoveProductFromProductSet", + request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["remove_product_from_product_set"] + + @property + def list_products_in_product_set( + self, + ) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + product_search_service.ListProductsInProductSetResponse, + ]: + r"""Return a callable for the list products in product set method over gRPC. + + Lists the Products in a ProductSet, in an unspecified order. If + the ProductSet does not exist, the products field of the + response will be empty. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Returns: + Callable[[~.ListProductsInProductSetRequest], + ~.ListProductsInProductSetResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_products_in_product_set" not in self._stubs: + self._stubs["list_products_in_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/ListProductsInProductSet", + request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, + response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, + ) + return self._stubs["list_products_in_product_set"] + + @property + def import_product_sets( + self, + ) -> Callable[ + [product_search_service.ImportProductSetsRequest], operations.Operation + ]: + r"""Return a callable for the import product sets method over gRPC. + + Asynchronous API that imports a list of reference images to + specified product sets based on a list of image information. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) ``Operation.response`` + contains ``ImportProductSetsResponse``. (results) + + The input source of this method is a csv file on Google Cloud + Storage. For the format of the csv file please see + [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1p4beta1.ImportProductSetsGcsSource.csv_file_uri]. + + Returns: + Callable[[~.ImportProductSetsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_product_sets" not in self._stubs: + self._stubs["import_product_sets"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/ImportProductSets", + request_serializer=product_search_service.ImportProductSetsRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["import_product_sets"] + + @property + def purge_products( + self, + ) -> Callable[[product_search_service.PurgeProductsRequest], operations.Operation]: + r"""Return a callable for the purge products method over gRPC. + + Asynchronous API to delete all Products in a ProductSet or all + Products that are in no ProductSet. + + If a Product is a member of the specified ProductSet in addition + to other ProductSets, the Product will still be deleted. + + It is recommended to not delete the specified ProductSet until + after this operation has completed. It is also recommended to + not add any of the Products involved in the batch delete to a + new ProductSet while this operation is running because those + Products may still end up deleted. + + It's not possible to undo the PurgeProducts operation. + Therefore, it is recommended to keep the csv files used in + ImportProductSets (if that was how you originally built the + Product Set) before starting PurgeProducts, in case you need to + re-import the data after deletion. + + If the plan is to purge all of the Products from a ProductSet + and then re-use the empty ProductSet to re-import new Products + into the empty ProductSet, you must wait until the PurgeProducts + operation has finished for that ProductSet. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) + + Returns: + Callable[[~.PurgeProductsRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "purge_products" not in self._stubs: + self._stubs["purge_products"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/PurgeProducts", + request_serializer=product_search_service.PurgeProductsRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["purge_products"] + + +__all__ = ("ProductSearchGrpcTransport",) diff --git a/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc_asyncio.py b/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc_asyncio.py new file mode 100644 index 00000000..d52e9a69 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc_asyncio.py @@ -0,0 +1,972 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.vision_v1p4beta1.types import product_search_service +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO +from .grpc import ProductSearchGrpcTransport + + +class ProductSearchGrpcAsyncIOTransport(ProductSearchTransport): + """gRPC AsyncIO backend transport for ProductSearch. + + Manages Products and ProductSets of reference images for use in + product search. It uses the following resource model: + + - The API has a collection of + [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] resources, + named ``projects/*/locations/*/productSets/*``, which acts as a + way to put different products into groups to limit + identification. + + In parallel, + + - The API has a collection of + [Product][google.cloud.vision.v1p4beta1.Product] resources, named + ``projects/*/locations/*/products/*`` + + - Each [Product][google.cloud.vision.v1p4beta1.Product] has a + collection of + [ReferenceImage][google.cloud.vision.v1p4beta1.ReferenceImage] + resources, named + ``projects/*/locations/*/products/*/referenceImages/*`` + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "vision.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def create_product_set( + self, + ) -> Callable[ + [product_search_service.CreateProductSetRequest], + Awaitable[product_search_service.ProductSet], + ]: + r"""Return a callable for the create product set method over gRPC. + + Creates and returns a new ProductSet resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing, or is + longer than 4096 characters. + + Returns: + Callable[[~.CreateProductSetRequest], + Awaitable[~.ProductSet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_product_set" not in self._stubs: + self._stubs["create_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/CreateProductSet", + request_serializer=product_search_service.CreateProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["create_product_set"] + + @property + def list_product_sets( + self, + ) -> Callable[ + [product_search_service.ListProductSetsRequest], + Awaitable[product_search_service.ListProductSetsResponse], + ]: + r"""Return a callable for the list product sets method over gRPC. + + Lists ProductSets in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100, or + less than 1. + + Returns: + Callable[[~.ListProductSetsRequest], + Awaitable[~.ListProductSetsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_product_sets" not in self._stubs: + self._stubs["list_product_sets"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/ListProductSets", + request_serializer=product_search_service.ListProductSetsRequest.serialize, + response_deserializer=product_search_service.ListProductSetsResponse.deserialize, + ) + return self._stubs["list_product_sets"] + + @property + def get_product_set( + self, + ) -> Callable[ + [product_search_service.GetProductSetRequest], + Awaitable[product_search_service.ProductSet], + ]: + r"""Return a callable for the get product set method over gRPC. + + Gets information associated with a ProductSet. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + + Returns: + Callable[[~.GetProductSetRequest], + Awaitable[~.ProductSet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_product_set" not in self._stubs: + self._stubs["get_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/GetProductSet", + request_serializer=product_search_service.GetProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["get_product_set"] + + @property + def update_product_set( + self, + ) -> Callable[ + [product_search_service.UpdateProductSetRequest], + Awaitable[product_search_service.ProductSet], + ]: + r"""Return a callable for the update product set method over gRPC. + + Makes changes to a ProductSet resource. Only display_name can be + updated currently. + + Possible errors: + + - Returns NOT_FOUND if the ProductSet does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but missing from the request or longer than 4096 + characters. + + Returns: + Callable[[~.UpdateProductSetRequest], + Awaitable[~.ProductSet]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_product_set" not in self._stubs: + self._stubs["update_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/UpdateProductSet", + request_serializer=product_search_service.UpdateProductSetRequest.serialize, + response_deserializer=product_search_service.ProductSet.deserialize, + ) + return self._stubs["update_product_set"] + + @property + def delete_product_set( + self, + ) -> Callable[ + [product_search_service.DeleteProductSetRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the delete product set method over gRPC. + + Permanently deletes a ProductSet. Products and + ReferenceImages in the ProductSet are not deleted. + The actual image files are not deleted from Google Cloud + Storage. + + Returns: + Callable[[~.DeleteProductSetRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_product_set" not in self._stubs: + self._stubs["delete_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteProductSet", + request_serializer=product_search_service.DeleteProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_product_set"] + + @property + def create_product( + self, + ) -> Callable[ + [product_search_service.CreateProductRequest], + Awaitable[product_search_service.Product], + ]: + r"""Return a callable for the create product method over gRPC. + + Creates and returns a new product resource. + + Possible errors: + + - Returns INVALID_ARGUMENT if display_name is missing or longer + than 4096 characters. + - Returns INVALID_ARGUMENT if description is longer than 4096 + characters. + - Returns INVALID_ARGUMENT if product_category is missing or + invalid. + + Returns: + Callable[[~.CreateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_product" not in self._stubs: + self._stubs["create_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/CreateProduct", + request_serializer=product_search_service.CreateProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["create_product"] + + @property + def list_products( + self, + ) -> Callable[ + [product_search_service.ListProductsRequest], + Awaitable[product_search_service.ListProductsResponse], + ]: + r"""Return a callable for the list products method over gRPC. + + Lists products in an unspecified order. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Returns: + Callable[[~.ListProductsRequest], + Awaitable[~.ListProductsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_products" not in self._stubs: + self._stubs["list_products"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/ListProducts", + request_serializer=product_search_service.ListProductsRequest.serialize, + response_deserializer=product_search_service.ListProductsResponse.deserialize, + ) + return self._stubs["list_products"] + + @property + def get_product( + self, + ) -> Callable[ + [product_search_service.GetProductRequest], + Awaitable[product_search_service.Product], + ]: + r"""Return a callable for the get product method over gRPC. + + Gets information associated with a Product. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + + Returns: + Callable[[~.GetProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_product" not in self._stubs: + self._stubs["get_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/GetProduct", + request_serializer=product_search_service.GetProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["get_product"] + + @property + def update_product( + self, + ) -> Callable[ + [product_search_service.UpdateProductRequest], + Awaitable[product_search_service.Product], + ]: + r"""Return a callable for the update product method over gRPC. + + Makes changes to a Product resource. Only the ``display_name``, + ``description``, and ``labels`` fields can be updated right now. + + If labels are updated, the change will not be reflected in + queries until the next index time. + + Possible errors: + + - Returns NOT_FOUND if the Product does not exist. + - Returns INVALID_ARGUMENT if display_name is present in + update_mask but is missing from the request or longer than + 4096 characters. + - Returns INVALID_ARGUMENT if description is present in + update_mask but is longer than 4096 characters. + - Returns INVALID_ARGUMENT if product_category is present in + update_mask. + + Returns: + Callable[[~.UpdateProductRequest], + Awaitable[~.Product]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_product" not in self._stubs: + self._stubs["update_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/UpdateProduct", + request_serializer=product_search_service.UpdateProductRequest.serialize, + response_deserializer=product_search_service.Product.deserialize, + ) + return self._stubs["update_product"] + + @property + def delete_product( + self, + ) -> Callable[ + [product_search_service.DeleteProductRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the delete product method over gRPC. + + Permanently deletes a product and its reference + images. + Metadata of the product and all its images will be + deleted right away, but search queries against + ProductSets containing the product may still work until + all related caches are refreshed. + + Returns: + Callable[[~.DeleteProductRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_product" not in self._stubs: + self._stubs["delete_product"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteProduct", + request_serializer=product_search_service.DeleteProductRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_product"] + + @property + def create_reference_image( + self, + ) -> Callable[ + [product_search_service.CreateReferenceImageRequest], + Awaitable[product_search_service.ReferenceImage], + ]: + r"""Return a callable for the create reference image method over gRPC. + + Creates and returns a new ReferenceImage resource. + + The ``bounding_poly`` field is optional. If ``bounding_poly`` is + not specified, the system will try to detect regions of interest + in the image that are compatible with the product_category on + the parent product. If it is specified, detection is ALWAYS + skipped. The system converts polygons into non-rotated + rectangles. + + Note that the pipeline will resize the image if the image + resolution is too large to process (above 50MP). + + Possible errors: + + - Returns INVALID_ARGUMENT if the image_uri is missing or + longer than 4096 characters. + - Returns INVALID_ARGUMENT if the product does not exist. + - Returns INVALID_ARGUMENT if bounding_poly is not provided, + and nothing compatible with the parent product's + product_category is detected. + - Returns INVALID_ARGUMENT if bounding_poly contains more than + 10 polygons. + + Returns: + Callable[[~.CreateReferenceImageRequest], + Awaitable[~.ReferenceImage]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_reference_image" not in self._stubs: + self._stubs["create_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/CreateReferenceImage", + request_serializer=product_search_service.CreateReferenceImageRequest.serialize, + response_deserializer=product_search_service.ReferenceImage.deserialize, + ) + return self._stubs["create_reference_image"] + + @property + def delete_reference_image( + self, + ) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the delete reference image method over gRPC. + + Permanently deletes a reference image. + The image metadata will be deleted right away, but + search queries against ProductSets containing the image + may still work until all related caches are refreshed. + + The actual image files are not deleted from Google Cloud + Storage. + + Returns: + Callable[[~.DeleteReferenceImageRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_reference_image" not in self._stubs: + self._stubs["delete_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/DeleteReferenceImage", + request_serializer=product_search_service.DeleteReferenceImageRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_reference_image"] + + @property + def list_reference_images( + self, + ) -> Callable[ + [product_search_service.ListReferenceImagesRequest], + Awaitable[product_search_service.ListReferenceImagesResponse], + ]: + r"""Return a callable for the list reference images method over gRPC. + + Lists reference images. + + Possible errors: + + - Returns NOT_FOUND if the parent product does not exist. + - Returns INVALID_ARGUMENT if the page_size is greater than + 100, or less than 1. + + Returns: + Callable[[~.ListReferenceImagesRequest], + Awaitable[~.ListReferenceImagesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_reference_images" not in self._stubs: + self._stubs["list_reference_images"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/ListReferenceImages", + request_serializer=product_search_service.ListReferenceImagesRequest.serialize, + response_deserializer=product_search_service.ListReferenceImagesResponse.deserialize, + ) + return self._stubs["list_reference_images"] + + @property + def get_reference_image( + self, + ) -> Callable[ + [product_search_service.GetReferenceImageRequest], + Awaitable[product_search_service.ReferenceImage], + ]: + r"""Return a callable for the get reference image method over gRPC. + + Gets information associated with a ReferenceImage. + + Possible errors: + + - Returns NOT_FOUND if the specified image does not exist. + + Returns: + Callable[[~.GetReferenceImageRequest], + Awaitable[~.ReferenceImage]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_reference_image" not in self._stubs: + self._stubs["get_reference_image"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/GetReferenceImage", + request_serializer=product_search_service.GetReferenceImageRequest.serialize, + response_deserializer=product_search_service.ReferenceImage.deserialize, + ) + return self._stubs["get_reference_image"] + + @property + def add_product_to_product_set( + self, + ) -> Callable[ + [product_search_service.AddProductToProductSetRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the add product to product set method over gRPC. + + Adds a Product to the specified ProductSet. If the Product is + already present, no change is made. + + One Product can be added to at most 100 ProductSets. + + Possible errors: + + - Returns NOT_FOUND if the Product or the ProductSet doesn't + exist. + + Returns: + Callable[[~.AddProductToProductSetRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "add_product_to_product_set" not in self._stubs: + self._stubs["add_product_to_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/AddProductToProductSet", + request_serializer=product_search_service.AddProductToProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["add_product_to_product_set"] + + @property + def remove_product_from_product_set( + self, + ) -> Callable[ + [product_search_service.RemoveProductFromProductSetRequest], + Awaitable[empty.Empty], + ]: + r"""Return a callable for the remove product from product + set method over gRPC. + + Removes a Product from the specified ProductSet. + + Returns: + Callable[[~.RemoveProductFromProductSetRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "remove_product_from_product_set" not in self._stubs: + self._stubs[ + "remove_product_from_product_set" + ] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/RemoveProductFromProductSet", + request_serializer=product_search_service.RemoveProductFromProductSetRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["remove_product_from_product_set"] + + @property + def list_products_in_product_set( + self, + ) -> Callable[ + [product_search_service.ListProductsInProductSetRequest], + Awaitable[product_search_service.ListProductsInProductSetResponse], + ]: + r"""Return a callable for the list products in product set method over gRPC. + + Lists the Products in a ProductSet, in an unspecified order. If + the ProductSet does not exist, the products field of the + response will be empty. + + Possible errors: + + - Returns INVALID_ARGUMENT if page_size is greater than 100 or + less than 1. + + Returns: + Callable[[~.ListProductsInProductSetRequest], + Awaitable[~.ListProductsInProductSetResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_products_in_product_set" not in self._stubs: + self._stubs["list_products_in_product_set"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/ListProductsInProductSet", + request_serializer=product_search_service.ListProductsInProductSetRequest.serialize, + response_deserializer=product_search_service.ListProductsInProductSetResponse.deserialize, + ) + return self._stubs["list_products_in_product_set"] + + @property + def import_product_sets( + self, + ) -> Callable[ + [product_search_service.ImportProductSetsRequest], + Awaitable[operations.Operation], + ]: + r"""Return a callable for the import product sets method over gRPC. + + Asynchronous API that imports a list of reference images to + specified product sets based on a list of image information. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) ``Operation.response`` + contains ``ImportProductSetsResponse``. (results) + + The input source of this method is a csv file on Google Cloud + Storage. For the format of the csv file please see + [ImportProductSetsGcsSource.csv_file_uri][google.cloud.vision.v1p4beta1.ImportProductSetsGcsSource.csv_file_uri]. + + Returns: + Callable[[~.ImportProductSetsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_product_sets" not in self._stubs: + self._stubs["import_product_sets"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/ImportProductSets", + request_serializer=product_search_service.ImportProductSetsRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["import_product_sets"] + + @property + def purge_products( + self, + ) -> Callable[ + [product_search_service.PurgeProductsRequest], Awaitable[operations.Operation] + ]: + r"""Return a callable for the purge products method over gRPC. + + Asynchronous API to delete all Products in a ProductSet or all + Products that are in no ProductSet. + + If a Product is a member of the specified ProductSet in addition + to other ProductSets, the Product will still be deleted. + + It is recommended to not delete the specified ProductSet until + after this operation has completed. It is also recommended to + not add any of the Products involved in the batch delete to a + new ProductSet while this operation is running because those + Products may still end up deleted. + + It's not possible to undo the PurgeProducts operation. + Therefore, it is recommended to keep the csv files used in + ImportProductSets (if that was how you originally built the + Product Set) before starting PurgeProducts, in case you need to + re-import the data after deletion. + + If the plan is to purge all of the Products from a ProductSet + and then re-use the empty ProductSet to re-import new Products + into the empty ProductSet, you must wait until the PurgeProducts + operation has finished for that ProductSet. + + The [google.longrunning.Operation][google.longrunning.Operation] + API can be used to keep track of the progress and results of the + request. ``Operation.metadata`` contains + ``BatchOperationMetadata``. (progress) + + Returns: + Callable[[~.PurgeProductsRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "purge_products" not in self._stubs: + self._stubs["purge_products"] = self.grpc_channel.unary_unary( + "/google.cloud.vision.v1p4beta1.ProductSearch/PurgeProducts", + request_serializer=product_search_service.PurgeProductsRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["purge_products"] + + +__all__ = ("ProductSearchGrpcAsyncIOTransport",) diff --git a/google/cloud/vision_v1p4beta1/types.py b/google/cloud/vision_v1p4beta1/types.py deleted file mode 100644 index 25a10a3d..00000000 --- a/google/cloud/vision_v1p4beta1/types.py +++ /dev/null @@ -1,76 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -from __future__ import absolute_import -import sys - -from google.api_core.protobuf_helpers import get_messages - -from google.cloud.vision_v1p4beta1.proto import face_pb2 -from google.cloud.vision_v1p4beta1.proto import geometry_pb2 -from google.cloud.vision_v1p4beta1.proto import image_annotator_pb2 -from google.cloud.vision_v1p4beta1.proto import product_search_pb2 -from google.cloud.vision_v1p4beta1.proto import product_search_service_pb2 -from google.cloud.vision_v1p4beta1.proto import text_annotation_pb2 -from google.cloud.vision_v1p4beta1.proto import web_detection_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import any_pb2 -from google.protobuf import empty_pb2 -from google.protobuf import field_mask_pb2 -from google.protobuf import timestamp_pb2 -from google.protobuf import wrappers_pb2 -from google.rpc import status_pb2 -from google.type import color_pb2 -from google.type import latlng_pb2 - - -_shared_modules = [ - operations_pb2, - any_pb2, - empty_pb2, - field_mask_pb2, - timestamp_pb2, - wrappers_pb2, - status_pb2, - color_pb2, - latlng_pb2, -] - -_local_modules = [ - face_pb2, - geometry_pb2, - image_annotator_pb2, - product_search_pb2, - product_search_service_pb2, - text_annotation_pb2, - web_detection_pb2, -] - -names = [] - -for module in _shared_modules: # pragma: NO COVER - for name, message in get_messages(module).items(): - setattr(sys.modules[__name__], name, message) - names.append(name) -for module in _local_modules: - for name, message in get_messages(module).items(): - message.__module__ = "google.cloud.vision_v1p4beta1.types" - setattr(sys.modules[__name__], name, message) - names.append(name) - - -__all__ = tuple(sorted(names)) diff --git a/google/cloud/vision_v1p4beta1/types/__init__.py b/google/cloud/vision_v1p4beta1/types/__init__.py new file mode 100644 index 00000000..8addc27c --- /dev/null +++ b/google/cloud/vision_v1p4beta1/types/__init__.py @@ -0,0 +1,203 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .geometry import ( + Vertex, + NormalizedVertex, + BoundingPoly, + Position, +) +from .face import ( + FaceRecognitionParams, + Celebrity, + FaceRecognitionResult, +) +from .product_search_service import ( + Product, + ProductSet, + ReferenceImage, + CreateProductRequest, + ListProductsRequest, + ListProductsResponse, + GetProductRequest, + UpdateProductRequest, + DeleteProductRequest, + CreateProductSetRequest, + ListProductSetsRequest, + ListProductSetsResponse, + GetProductSetRequest, + UpdateProductSetRequest, + DeleteProductSetRequest, + CreateReferenceImageRequest, + ListReferenceImagesRequest, + ListReferenceImagesResponse, + GetReferenceImageRequest, + DeleteReferenceImageRequest, + AddProductToProductSetRequest, + RemoveProductFromProductSetRequest, + ListProductsInProductSetRequest, + ListProductsInProductSetResponse, + ImportProductSetsGcsSource, + ImportProductSetsInputConfig, + ImportProductSetsRequest, + ImportProductSetsResponse, + BatchOperationMetadata, + ProductSetPurgeConfig, + PurgeProductsRequest, +) +from .product_search import ( + ProductSearchParams, + ProductSearchResults, +) +from .text_annotation import ( + TextAnnotation, + Page, + Block, + Paragraph, + Word, + Symbol, +) +from .web_detection import WebDetection +from .image_annotator import ( + Feature, + ImageSource, + Image, + FaceAnnotation, + LocationInfo, + Property, + EntityAnnotation, + LocalizedObjectAnnotation, + SafeSearchAnnotation, + LatLongRect, + ColorInfo, + DominantColorsAnnotation, + ImageProperties, + CropHint, + CropHintsAnnotation, + CropHintsParams, + WebDetectionParams, + ImageContext, + AnnotateImageRequest, + ImageAnnotationContext, + AnnotateImageResponse, + BatchAnnotateImagesRequest, + BatchAnnotateImagesResponse, + AnnotateFileRequest, + AnnotateFileResponse, + BatchAnnotateFilesRequest, + BatchAnnotateFilesResponse, + AsyncAnnotateFileRequest, + AsyncAnnotateFileResponse, + AsyncBatchAnnotateImagesRequest, + AsyncBatchAnnotateImagesResponse, + AsyncBatchAnnotateFilesRequest, + AsyncBatchAnnotateFilesResponse, + InputConfig, + OutputConfig, + GcsSource, + GcsDestination, + OperationMetadata, +) + + +__all__ = ( + "Vertex", + "NormalizedVertex", + "BoundingPoly", + "Position", + "FaceRecognitionParams", + "Celebrity", + "FaceRecognitionResult", + "Product", + "ProductSet", + "ReferenceImage", + "CreateProductRequest", + "ListProductsRequest", + "ListProductsResponse", + "GetProductRequest", + "UpdateProductRequest", + "DeleteProductRequest", + "CreateProductSetRequest", + "ListProductSetsRequest", + "ListProductSetsResponse", + "GetProductSetRequest", + "UpdateProductSetRequest", + "DeleteProductSetRequest", + "CreateReferenceImageRequest", + "ListReferenceImagesRequest", + "ListReferenceImagesResponse", + "GetReferenceImageRequest", + "DeleteReferenceImageRequest", + "AddProductToProductSetRequest", + "RemoveProductFromProductSetRequest", + "ListProductsInProductSetRequest", + "ListProductsInProductSetResponse", + "ImportProductSetsGcsSource", + "ImportProductSetsInputConfig", + "ImportProductSetsRequest", + "ImportProductSetsResponse", + "BatchOperationMetadata", + "ProductSetPurgeConfig", + "PurgeProductsRequest", + "ProductSearchParams", + "ProductSearchResults", + "TextAnnotation", + "Page", + "Block", + "Paragraph", + "Word", + "Symbol", + "WebDetection", + "Feature", + "ImageSource", + "Image", + "FaceAnnotation", + "LocationInfo", + "Property", + "EntityAnnotation", + "LocalizedObjectAnnotation", + "SafeSearchAnnotation", + "LatLongRect", + "ColorInfo", + "DominantColorsAnnotation", + "ImageProperties", + "CropHint", + "CropHintsAnnotation", + "CropHintsParams", + "WebDetectionParams", + "ImageContext", + "AnnotateImageRequest", + "ImageAnnotationContext", + "AnnotateImageResponse", + "BatchAnnotateImagesRequest", + "BatchAnnotateImagesResponse", + "AnnotateFileRequest", + "AnnotateFileResponse", + "BatchAnnotateFilesRequest", + "BatchAnnotateFilesResponse", + "AsyncAnnotateFileRequest", + "AsyncAnnotateFileResponse", + "AsyncBatchAnnotateImagesRequest", + "AsyncBatchAnnotateImagesResponse", + "AsyncBatchAnnotateFilesRequest", + "AsyncBatchAnnotateFilesResponse", + "InputConfig", + "OutputConfig", + "GcsSource", + "GcsDestination", + "OperationMetadata", +) diff --git a/google/cloud/vision_v1p4beta1/types/face.py b/google/cloud/vision_v1p4beta1/types/face.py new file mode 100644 index 00000000..68b34cc0 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/types/face.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p4beta1", + manifest={"FaceRecognitionParams", "Celebrity", "FaceRecognitionResult",}, +) + + +class FaceRecognitionParams(proto.Message): + r"""Parameters for a celebrity recognition request. + + Attributes: + celebrity_set (Sequence[str]): + The resource names for one or more + [CelebritySet][google.cloud.vision.v1p4beta1.CelebritySet]s. + A celebrity set is preloaded and can be specified as + "builtin/default". If this is specified, the algorithm will + try to match the faces detected in the input image to the + Celebrities in the CelebritySets. + """ + + celebrity_set = proto.RepeatedField(proto.STRING, number=1) + + +class Celebrity(proto.Message): + r"""A Celebrity is a group of Faces with an identity. + + Attributes: + name (str): + The resource name of the preloaded Celebrity. Has the format + ``builtin/{mid}``. + display_name (str): + The Celebrity's display name. + description (str): + The Celebrity's description. + """ + + name = proto.Field(proto.STRING, number=1) + + display_name = proto.Field(proto.STRING, number=2) + + description = proto.Field(proto.STRING, number=3) + + +class FaceRecognitionResult(proto.Message): + r"""Information about a face's identity. + + Attributes: + celebrity (~.face.Celebrity): + The [Celebrity][google.cloud.vision.v1p4beta1.Celebrity] + that this face was matched to. + confidence (float): + Recognition confidence. Range [0, 1]. + """ + + celebrity = proto.Field(proto.MESSAGE, number=1, message=Celebrity,) + + confidence = proto.Field(proto.FLOAT, number=2) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p4beta1/types/geometry.py b/google/cloud/vision_v1p4beta1/types/geometry.py new file mode 100644 index 00000000..03a2a726 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/types/geometry.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p4beta1", + manifest={"Vertex", "NormalizedVertex", "BoundingPoly", "Position",}, +) + + +class Vertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the vertex coordinates are in the same scale as the + original image. + + Attributes: + x (int): + X coordinate. + y (int): + Y coordinate. + """ + + x = proto.Field(proto.INT32, number=1) + + y = proto.Field(proto.INT32, number=2) + + +class NormalizedVertex(proto.Message): + r"""A vertex represents a 2D point in the image. + NOTE: the normalized vertex coordinates are relative to the + original image and range from 0 to 1. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate. + """ + + x = proto.Field(proto.FLOAT, number=1) + + y = proto.Field(proto.FLOAT, number=2) + + +class BoundingPoly(proto.Message): + r"""A bounding polygon for the detected image annotation. + + Attributes: + vertices (Sequence[~.geometry.Vertex]): + The bounding polygon vertices. + normalized_vertices (Sequence[~.geometry.NormalizedVertex]): + The bounding polygon normalized vertices. + """ + + vertices = proto.RepeatedField(proto.MESSAGE, number=1, message=Vertex,) + + normalized_vertices = proto.RepeatedField( + proto.MESSAGE, number=2, message=NormalizedVertex, + ) + + +class Position(proto.Message): + r"""A 3D position in the image, used primarily for Face detection + landmarks. A valid Position must have both x and y coordinates. + The position coordinates are in the same scale as the original + image. + + Attributes: + x (float): + X coordinate. + y (float): + Y coordinate. + z (float): + Z coordinate (or depth). + """ + + x = proto.Field(proto.FLOAT, number=1) + + y = proto.Field(proto.FLOAT, number=2) + + z = proto.Field(proto.FLOAT, number=3) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p4beta1/types/image_annotator.py b/google/cloud/vision_v1p4beta1/types/image_annotator.py new file mode 100644 index 00000000..6f6c1cf6 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/types/image_annotator.py @@ -0,0 +1,1196 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.vision_v1p4beta1.types import face +from google.cloud.vision_v1p4beta1.types import geometry +from google.cloud.vision_v1p4beta1.types import product_search +from google.cloud.vision_v1p4beta1.types import text_annotation +from google.cloud.vision_v1p4beta1.types import web_detection as gcv_web_detection +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore +from google.type import color_pb2 as gt_color # type: ignore +from google.type import latlng_pb2 as latlng # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p4beta1", + manifest={ + "Likelihood", + "Feature", + "ImageSource", + "Image", + "FaceAnnotation", + "LocationInfo", + "Property", + "EntityAnnotation", + "LocalizedObjectAnnotation", + "SafeSearchAnnotation", + "LatLongRect", + "ColorInfo", + "DominantColorsAnnotation", + "ImageProperties", + "CropHint", + "CropHintsAnnotation", + "CropHintsParams", + "WebDetectionParams", + "ImageContext", + "AnnotateImageRequest", + "ImageAnnotationContext", + "AnnotateImageResponse", + "BatchAnnotateImagesRequest", + "BatchAnnotateImagesResponse", + "AnnotateFileRequest", + "AnnotateFileResponse", + "BatchAnnotateFilesRequest", + "BatchAnnotateFilesResponse", + "AsyncAnnotateFileRequest", + "AsyncAnnotateFileResponse", + "AsyncBatchAnnotateImagesRequest", + "AsyncBatchAnnotateImagesResponse", + "AsyncBatchAnnotateFilesRequest", + "AsyncBatchAnnotateFilesResponse", + "InputConfig", + "OutputConfig", + "GcsSource", + "GcsDestination", + "OperationMetadata", + }, +) + + +class Likelihood(proto.Enum): + r"""A bucketized representation of likelihood, which is intended + to give clients highly stable results across model upgrades. + """ + UNKNOWN = 0 + VERY_UNLIKELY = 1 + UNLIKELY = 2 + POSSIBLE = 3 + LIKELY = 4 + VERY_LIKELY = 5 + + +class Feature(proto.Message): + r"""The type of Google Cloud Vision API detection to perform, and the + maximum number of results to return for that type. Multiple + ``Feature`` objects can be specified in the ``features`` list. + + Attributes: + type_ (~.image_annotator.Feature.Type): + The feature type. + max_results (int): + Maximum number of results of this type. Does not apply to + ``TEXT_DETECTION``, ``DOCUMENT_TEXT_DETECTION``, or + ``CROP_HINTS``. + model (str): + Model to use for the feature. + Supported values: "builtin/stable" (the default + if unset) and "builtin/latest". + """ + + class Type(proto.Enum): + r"""Type of Google Cloud Vision API feature to be extracted.""" + TYPE_UNSPECIFIED = 0 + FACE_DETECTION = 1 + LANDMARK_DETECTION = 2 + LOGO_DETECTION = 3 + LABEL_DETECTION = 4 + TEXT_DETECTION = 5 + DOCUMENT_TEXT_DETECTION = 11 + SAFE_SEARCH_DETECTION = 6 + IMAGE_PROPERTIES = 7 + CROP_HINTS = 9 + WEB_DETECTION = 10 + PRODUCT_SEARCH = 12 + OBJECT_LOCALIZATION = 19 + + type_ = proto.Field(proto.ENUM, number=1, enum=Type,) + + max_results = proto.Field(proto.INT32, number=2) + + model = proto.Field(proto.STRING, number=3) + + +class ImageSource(proto.Message): + r"""External image source (Google Cloud Storage or web URL image + location). + + Attributes: + gcs_image_uri (str): + **Use ``image_uri`` instead.** + + The Google Cloud Storage URI of the form + ``gs://bucket_name/object_name``. Object versioning is not + supported. See `Google Cloud Storage Request + URIs `__ + for more info. + image_uri (str): + The URI of the source image. Can be either: + + 1. A Google Cloud Storage URI of the form + ``gs://bucket_name/object_name``. Object versioning is + not supported. See `Google Cloud Storage Request + URIs `__ + for more info. + + 2. A publicly-accessible image HTTP/HTTPS URL. When fetching + images from HTTP/HTTPS URLs, Google cannot guarantee that + the request will be completed. Your request may fail if + the specified host denies the request (e.g. due to + request throttling or DOS prevention), or if Google + throttles requests to the site for abuse prevention. You + should not depend on externally-hosted images for + production applications. + + When both ``gcs_image_uri`` and ``image_uri`` are specified, + ``image_uri`` takes precedence. + """ + + gcs_image_uri = proto.Field(proto.STRING, number=1) + + image_uri = proto.Field(proto.STRING, number=2) + + +class Image(proto.Message): + r"""Client image to perform Google Cloud Vision API tasks over. + + Attributes: + content (bytes): + Image content, represented as a stream of bytes. Note: As + with all ``bytes`` fields, protobuffers use a pure binary + representation, whereas JSON representations use base64. + source (~.image_annotator.ImageSource): + Google Cloud Storage image location, or publicly-accessible + image URL. If both ``content`` and ``source`` are provided + for an image, ``content`` takes precedence and is used to + perform the image annotation request. + """ + + content = proto.Field(proto.BYTES, number=1) + + source = proto.Field(proto.MESSAGE, number=2, message=ImageSource,) + + +class FaceAnnotation(proto.Message): + r"""A face annotation object contains the results of face + detection. + + Attributes: + bounding_poly (~.geometry.BoundingPoly): + The bounding polygon around the face. The coordinates of the + bounding box are in the original image's scale. The bounding + box is computed to "frame" the face in accordance with human + expectations. It is based on the landmarker results. Note + that one or more x and/or y coordinates may not be generated + in the ``BoundingPoly`` (the polygon will be unbounded) if + only a partial face appears in the image to be annotated. + fd_bounding_poly (~.geometry.BoundingPoly): + The ``fd_bounding_poly`` bounding polygon is tighter than + the ``boundingPoly``, and encloses only the skin part of the + face. Typically, it is used to eliminate the face from any + image analysis that detects the "amount of skin" visible in + an image. It is not based on the landmarker results, only on + the initial face detection, hence the fd (face detection) + prefix. + landmarks (Sequence[~.image_annotator.FaceAnnotation.Landmark]): + Detected face landmarks. + roll_angle (float): + Roll angle, which indicates the amount of + clockwise/anti-clockwise rotation of the face relative to + the image vertical about the axis perpendicular to the face. + Range [-180,180]. + pan_angle (float): + Yaw angle, which indicates the leftward/rightward angle that + the face is pointing relative to the vertical plane + perpendicular to the image. Range [-180,180]. + tilt_angle (float): + Pitch angle, which indicates the upwards/downwards angle + that the face is pointing relative to the image's horizontal + plane. Range [-180,180]. + detection_confidence (float): + Detection confidence. Range [0, 1]. + landmarking_confidence (float): + Face landmarking confidence. Range [0, 1]. + joy_likelihood (~.image_annotator.Likelihood): + Joy likelihood. + sorrow_likelihood (~.image_annotator.Likelihood): + Sorrow likelihood. + anger_likelihood (~.image_annotator.Likelihood): + Anger likelihood. + surprise_likelihood (~.image_annotator.Likelihood): + Surprise likelihood. + under_exposed_likelihood (~.image_annotator.Likelihood): + Under-exposed likelihood. + blurred_likelihood (~.image_annotator.Likelihood): + Blurred likelihood. + headwear_likelihood (~.image_annotator.Likelihood): + Headwear likelihood. + recognition_result (Sequence[~.face.FaceRecognitionResult]): + Additional recognition information. Only computed if + image_context.face_recognition_params is provided, **and** a + match is found to a + [Celebrity][google.cloud.vision.v1p4beta1.Celebrity] in the + input + [CelebritySet][google.cloud.vision.v1p4beta1.CelebritySet]. + This field is sorted in order of decreasing confidence + values. + """ + + class Landmark(proto.Message): + r"""A face-specific landmark (for example, a face feature). + + Attributes: + type_ (~.image_annotator.FaceAnnotation.Landmark.Type): + Face landmark type. + position (~.geometry.Position): + Face landmark position. + """ + + class Type(proto.Enum): + r"""Face landmark (feature) type. Left and right are defined from the + vantage of the viewer of the image without considering mirror + projections typical of photos. So, ``LEFT_EYE``, typically, is the + person's right eye. + """ + UNKNOWN_LANDMARK = 0 + LEFT_EYE = 1 + RIGHT_EYE = 2 + LEFT_OF_LEFT_EYEBROW = 3 + RIGHT_OF_LEFT_EYEBROW = 4 + LEFT_OF_RIGHT_EYEBROW = 5 + RIGHT_OF_RIGHT_EYEBROW = 6 + MIDPOINT_BETWEEN_EYES = 7 + NOSE_TIP = 8 + UPPER_LIP = 9 + LOWER_LIP = 10 + MOUTH_LEFT = 11 + MOUTH_RIGHT = 12 + MOUTH_CENTER = 13 + NOSE_BOTTOM_RIGHT = 14 + NOSE_BOTTOM_LEFT = 15 + NOSE_BOTTOM_CENTER = 16 + LEFT_EYE_TOP_BOUNDARY = 17 + LEFT_EYE_RIGHT_CORNER = 18 + LEFT_EYE_BOTTOM_BOUNDARY = 19 + LEFT_EYE_LEFT_CORNER = 20 + RIGHT_EYE_TOP_BOUNDARY = 21 + RIGHT_EYE_RIGHT_CORNER = 22 + RIGHT_EYE_BOTTOM_BOUNDARY = 23 + RIGHT_EYE_LEFT_CORNER = 24 + LEFT_EYEBROW_UPPER_MIDPOINT = 25 + RIGHT_EYEBROW_UPPER_MIDPOINT = 26 + LEFT_EAR_TRAGION = 27 + RIGHT_EAR_TRAGION = 28 + LEFT_EYE_PUPIL = 29 + RIGHT_EYE_PUPIL = 30 + FOREHEAD_GLABELLA = 31 + CHIN_GNATHION = 32 + CHIN_LEFT_GONION = 33 + CHIN_RIGHT_GONION = 34 + + type_ = proto.Field(proto.ENUM, number=3, enum="FaceAnnotation.Landmark.Type",) + + position = proto.Field(proto.MESSAGE, number=4, message=geometry.Position,) + + bounding_poly = proto.Field(proto.MESSAGE, number=1, message=geometry.BoundingPoly,) + + fd_bounding_poly = proto.Field( + proto.MESSAGE, number=2, message=geometry.BoundingPoly, + ) + + landmarks = proto.RepeatedField(proto.MESSAGE, number=3, message=Landmark,) + + roll_angle = proto.Field(proto.FLOAT, number=4) + + pan_angle = proto.Field(proto.FLOAT, number=5) + + tilt_angle = proto.Field(proto.FLOAT, number=6) + + detection_confidence = proto.Field(proto.FLOAT, number=7) + + landmarking_confidence = proto.Field(proto.FLOAT, number=8) + + joy_likelihood = proto.Field(proto.ENUM, number=9, enum="Likelihood",) + + sorrow_likelihood = proto.Field(proto.ENUM, number=10, enum="Likelihood",) + + anger_likelihood = proto.Field(proto.ENUM, number=11, enum="Likelihood",) + + surprise_likelihood = proto.Field(proto.ENUM, number=12, enum="Likelihood",) + + under_exposed_likelihood = proto.Field(proto.ENUM, number=13, enum="Likelihood",) + + blurred_likelihood = proto.Field(proto.ENUM, number=14, enum="Likelihood",) + + headwear_likelihood = proto.Field(proto.ENUM, number=15, enum="Likelihood",) + + recognition_result = proto.RepeatedField( + proto.MESSAGE, number=16, message=face.FaceRecognitionResult, + ) + + +class LocationInfo(proto.Message): + r"""Detected entity location information. + + Attributes: + lat_lng (~.latlng.LatLng): + lat/long location coordinates. + """ + + lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng.LatLng,) + + +class Property(proto.Message): + r"""A ``Property`` consists of a user-supplied name/value pair. + + Attributes: + name (str): + Name of the property. + value (str): + Value of the property. + uint64_value (int): + Value of numeric properties. + """ + + name = proto.Field(proto.STRING, number=1) + + value = proto.Field(proto.STRING, number=2) + + uint64_value = proto.Field(proto.UINT64, number=3) + + +class EntityAnnotation(proto.Message): + r"""Set of detected entity features. + + Attributes: + mid (str): + Opaque entity ID. Some IDs may be available in `Google + Knowledge Graph Search + API `__. + locale (str): + The language code for the locale in which the entity textual + ``description`` is expressed. + description (str): + Entity textual description, expressed in its ``locale`` + language. + score (float): + Overall score of the result. Range [0, 1]. + confidence (float): + **Deprecated. Use ``score`` instead.** The accuracy of the + entity detection in an image. For example, for an image in + which the "Eiffel Tower" entity is detected, this field + represents the confidence that there is a tower in the query + image. Range [0, 1]. + topicality (float): + The relevancy of the ICA (Image Content Annotation) label to + the image. For example, the relevancy of "tower" is likely + higher to an image containing the detected "Eiffel Tower" + than to an image containing a detected distant towering + building, even though the confidence that there is a tower + in each image may be the same. Range [0, 1]. + bounding_poly (~.geometry.BoundingPoly): + Image region to which this entity belongs. Not produced for + ``LABEL_DETECTION`` features. + locations (Sequence[~.image_annotator.LocationInfo]): + The location information for the detected entity. Multiple + ``LocationInfo`` elements can be present because one + location may indicate the location of the scene in the + image, and another location may indicate the location of the + place where the image was taken. Location information is + usually present for landmarks. + properties (Sequence[~.image_annotator.Property]): + Some entities may have optional user-supplied ``Property`` + (name/value) fields, such a score or string that qualifies + the entity. + """ + + mid = proto.Field(proto.STRING, number=1) + + locale = proto.Field(proto.STRING, number=2) + + description = proto.Field(proto.STRING, number=3) + + score = proto.Field(proto.FLOAT, number=4) + + confidence = proto.Field(proto.FLOAT, number=5) + + topicality = proto.Field(proto.FLOAT, number=6) + + bounding_poly = proto.Field(proto.MESSAGE, number=7, message=geometry.BoundingPoly,) + + locations = proto.RepeatedField(proto.MESSAGE, number=8, message=LocationInfo,) + + properties = proto.RepeatedField(proto.MESSAGE, number=9, message=Property,) + + +class LocalizedObjectAnnotation(proto.Message): + r"""Set of detected objects with bounding boxes. + + Attributes: + mid (str): + Object ID that should align with + EntityAnnotation mid. + language_code (str): + The BCP-47 language code, such as "en-US" or "sr-Latn". For + more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + name (str): + Object name, expressed in its ``language_code`` language. + score (float): + Score of the result. Range [0, 1]. + bounding_poly (~.geometry.BoundingPoly): + Image region to which this object belongs. + This must be populated. + """ + + mid = proto.Field(proto.STRING, number=1) + + language_code = proto.Field(proto.STRING, number=2) + + name = proto.Field(proto.STRING, number=3) + + score = proto.Field(proto.FLOAT, number=4) + + bounding_poly = proto.Field(proto.MESSAGE, number=5, message=geometry.BoundingPoly,) + + +class SafeSearchAnnotation(proto.Message): + r"""Set of features pertaining to the image, computed by computer + vision methods over safe-search verticals (for example, adult, + spoof, medical, violence). + + Attributes: + adult (~.image_annotator.Likelihood): + Represents the adult content likelihood for + the image. Adult content may contain elements + such as nudity, pornographic images or cartoons, + or sexual activities. + spoof (~.image_annotator.Likelihood): + Spoof likelihood. The likelihood that an + modification was made to the image's canonical + version to make it appear funny or offensive. + medical (~.image_annotator.Likelihood): + Likelihood that this is a medical image. + violence (~.image_annotator.Likelihood): + Likelihood that this image contains violent + content. + racy (~.image_annotator.Likelihood): + Likelihood that the request image contains + racy content. Racy content may include (but is + not limited to) skimpy or sheer clothing, + strategically covered nudity, lewd or + provocative poses, or close-ups of sensitive + body areas. + """ + + adult = proto.Field(proto.ENUM, number=1, enum="Likelihood",) + + spoof = proto.Field(proto.ENUM, number=2, enum="Likelihood",) + + medical = proto.Field(proto.ENUM, number=3, enum="Likelihood",) + + violence = proto.Field(proto.ENUM, number=4, enum="Likelihood",) + + racy = proto.Field(proto.ENUM, number=9, enum="Likelihood",) + + +class LatLongRect(proto.Message): + r"""Rectangle determined by min and max ``LatLng`` pairs. + + Attributes: + min_lat_lng (~.latlng.LatLng): + Min lat/long pair. + max_lat_lng (~.latlng.LatLng): + Max lat/long pair. + """ + + min_lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng.LatLng,) + + max_lat_lng = proto.Field(proto.MESSAGE, number=2, message=latlng.LatLng,) + + +class ColorInfo(proto.Message): + r"""Color information consists of RGB channels, score, and the + fraction of the image that the color occupies in the image. + + Attributes: + color (~.gt_color.Color): + RGB components of the color. + score (float): + Image-specific score for this color. Value in range [0, 1]. + pixel_fraction (float): + The fraction of pixels the color occupies in the image. + Value in range [0, 1]. + """ + + color = proto.Field(proto.MESSAGE, number=1, message=gt_color.Color,) + + score = proto.Field(proto.FLOAT, number=2) + + pixel_fraction = proto.Field(proto.FLOAT, number=3) + + +class DominantColorsAnnotation(proto.Message): + r"""Set of dominant colors and their corresponding scores. + + Attributes: + colors (Sequence[~.image_annotator.ColorInfo]): + RGB color values with their score and pixel + fraction. + """ + + colors = proto.RepeatedField(proto.MESSAGE, number=1, message=ColorInfo,) + + +class ImageProperties(proto.Message): + r"""Stores image properties, such as dominant colors. + + Attributes: + dominant_colors (~.image_annotator.DominantColorsAnnotation): + If present, dominant colors completed + successfully. + """ + + dominant_colors = proto.Field( + proto.MESSAGE, number=1, message=DominantColorsAnnotation, + ) + + +class CropHint(proto.Message): + r"""Single crop hint that is used to generate a new crop when + serving an image. + + Attributes: + bounding_poly (~.geometry.BoundingPoly): + The bounding polygon for the crop region. The + coordinates of the bounding box are in the + original image's scale. + confidence (float): + Confidence of this being a salient region. Range [0, 1]. + importance_fraction (float): + Fraction of importance of this salient region + with respect to the original image. + """ + + bounding_poly = proto.Field(proto.MESSAGE, number=1, message=geometry.BoundingPoly,) + + confidence = proto.Field(proto.FLOAT, number=2) + + importance_fraction = proto.Field(proto.FLOAT, number=3) + + +class CropHintsAnnotation(proto.Message): + r"""Set of crop hints that are used to generate new crops when + serving images. + + Attributes: + crop_hints (Sequence[~.image_annotator.CropHint]): + Crop hint results. + """ + + crop_hints = proto.RepeatedField(proto.MESSAGE, number=1, message=CropHint,) + + +class CropHintsParams(proto.Message): + r"""Parameters for crop hints annotation request. + + Attributes: + aspect_ratios (Sequence[float]): + Aspect ratios in floats, representing the + ratio of the width to the height of the image. + For example, if the desired aspect ratio is 4/3, + the corresponding float value should be 1.33333. + If not specified, the best possible crop is + returned. The number of provided aspect ratios + is limited to a maximum of 16; any aspect ratios + provided after the 16th are ignored. + """ + + aspect_ratios = proto.RepeatedField(proto.FLOAT, number=1) + + +class WebDetectionParams(proto.Message): + r"""Parameters for web detection request. + + Attributes: + include_geo_results (bool): + Whether to include results derived from the + geo information in the image. + """ + + include_geo_results = proto.Field(proto.BOOL, number=2) + + +class ImageContext(proto.Message): + r"""Image context and/or feature-specific parameters. + + Attributes: + lat_long_rect (~.image_annotator.LatLongRect): + Not used. + language_hints (Sequence[str]): + List of languages to use for TEXT_DETECTION. In most cases, + an empty value yields the best results since it enables + automatic language detection. For languages based on the + Latin alphabet, setting ``language_hints`` is not needed. In + rare cases, when the language of the text in the image is + known, setting a hint will help get better results (although + it will be a significant hindrance if the hint is wrong). + Text detection returns an error if one or more of the + specified languages is not one of the `supported + languages `__. + crop_hints_params (~.image_annotator.CropHintsParams): + Parameters for crop hints annotation request. + face_recognition_params (~.face.FaceRecognitionParams): + Parameters for face recognition. + product_search_params (~.product_search.ProductSearchParams): + Parameters for product search. + web_detection_params (~.image_annotator.WebDetectionParams): + Parameters for web detection. + """ + + lat_long_rect = proto.Field(proto.MESSAGE, number=1, message=LatLongRect,) + + language_hints = proto.RepeatedField(proto.STRING, number=2) + + crop_hints_params = proto.Field(proto.MESSAGE, number=4, message=CropHintsParams,) + + face_recognition_params = proto.Field( + proto.MESSAGE, number=10, message=face.FaceRecognitionParams, + ) + + product_search_params = proto.Field( + proto.MESSAGE, number=5, message=product_search.ProductSearchParams, + ) + + web_detection_params = proto.Field( + proto.MESSAGE, number=6, message=WebDetectionParams, + ) + + +class AnnotateImageRequest(proto.Message): + r"""Request for performing Google Cloud Vision API tasks over a + user-provided image, with user-requested features, and with + context information. + + Attributes: + image (~.image_annotator.Image): + The image to be processed. + features (Sequence[~.image_annotator.Feature]): + Requested features. + image_context (~.image_annotator.ImageContext): + Additional context that may accompany the + image. + """ + + image = proto.Field(proto.MESSAGE, number=1, message=Image,) + + features = proto.RepeatedField(proto.MESSAGE, number=2, message=Feature,) + + image_context = proto.Field(proto.MESSAGE, number=3, message=ImageContext,) + + +class ImageAnnotationContext(proto.Message): + r"""If an image was produced from a file (e.g. a PDF), this + message gives information about the source of that image. + + Attributes: + uri (str): + The URI of the file used to produce the + image. + page_number (int): + If the file was a PDF or TIFF, this field + gives the page number within the file used to + produce the image. + """ + + uri = proto.Field(proto.STRING, number=1) + + page_number = proto.Field(proto.INT32, number=2) + + +class AnnotateImageResponse(proto.Message): + r"""Response to an image annotation request. + + Attributes: + face_annotations (Sequence[~.image_annotator.FaceAnnotation]): + If present, face detection has completed + successfully. + landmark_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, landmark detection has completed + successfully. + logo_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, logo detection has completed + successfully. + label_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, label detection has completed + successfully. + localized_object_annotations (Sequence[~.image_annotator.LocalizedObjectAnnotation]): + If present, localized object detection has + completed successfully. This will be sorted + descending by confidence score. + text_annotations (Sequence[~.image_annotator.EntityAnnotation]): + If present, text (OCR) detection has + completed successfully. + full_text_annotation (~.text_annotation.TextAnnotation): + If present, text (OCR) detection or document + (OCR) text detection has completed successfully. + This annotation provides the structural + hierarchy for the OCR detected text. + safe_search_annotation (~.image_annotator.SafeSearchAnnotation): + If present, safe-search annotation has + completed successfully. + image_properties_annotation (~.image_annotator.ImageProperties): + If present, image properties were extracted + successfully. + crop_hints_annotation (~.image_annotator.CropHintsAnnotation): + If present, crop hints have completed + successfully. + web_detection (~.gcv_web_detection.WebDetection): + If present, web detection has completed + successfully. + product_search_results (~.product_search.ProductSearchResults): + If present, product search has completed + successfully. + error (~.status.Status): + If set, represents the error message for the operation. Note + that filled-in image annotations are guaranteed to be + correct, even when ``error`` is set. + context (~.image_annotator.ImageAnnotationContext): + If present, contextual information is needed + to understand where this image comes from. + """ + + face_annotations = proto.RepeatedField( + proto.MESSAGE, number=1, message=FaceAnnotation, + ) + + landmark_annotations = proto.RepeatedField( + proto.MESSAGE, number=2, message=EntityAnnotation, + ) + + logo_annotations = proto.RepeatedField( + proto.MESSAGE, number=3, message=EntityAnnotation, + ) + + label_annotations = proto.RepeatedField( + proto.MESSAGE, number=4, message=EntityAnnotation, + ) + + localized_object_annotations = proto.RepeatedField( + proto.MESSAGE, number=22, message=LocalizedObjectAnnotation, + ) + + text_annotations = proto.RepeatedField( + proto.MESSAGE, number=5, message=EntityAnnotation, + ) + + full_text_annotation = proto.Field( + proto.MESSAGE, number=12, message=text_annotation.TextAnnotation, + ) + + safe_search_annotation = proto.Field( + proto.MESSAGE, number=6, message=SafeSearchAnnotation, + ) + + image_properties_annotation = proto.Field( + proto.MESSAGE, number=8, message=ImageProperties, + ) + + crop_hints_annotation = proto.Field( + proto.MESSAGE, number=11, message=CropHintsAnnotation, + ) + + web_detection = proto.Field( + proto.MESSAGE, number=13, message=gcv_web_detection.WebDetection, + ) + + product_search_results = proto.Field( + proto.MESSAGE, number=14, message=product_search.ProductSearchResults, + ) + + error = proto.Field(proto.MESSAGE, number=9, message=status.Status,) + + context = proto.Field(proto.MESSAGE, number=21, message=ImageAnnotationContext,) + + +class BatchAnnotateImagesRequest(proto.Message): + r"""Multiple image annotation requests are batched into a single + service call. + + Attributes: + requests (Sequence[~.image_annotator.AnnotateImageRequest]): + Required. Individual image annotation + requests for this batch. + """ + + requests = proto.RepeatedField( + proto.MESSAGE, number=1, message=AnnotateImageRequest, + ) + + +class BatchAnnotateImagesResponse(proto.Message): + r"""Response to a batch image annotation request. + + Attributes: + responses (Sequence[~.image_annotator.AnnotateImageResponse]): + Individual responses to image annotation + requests within the batch. + """ + + responses = proto.RepeatedField( + proto.MESSAGE, number=1, message=AnnotateImageResponse, + ) + + +class AnnotateFileRequest(proto.Message): + r"""A request to annotate one single file, e.g. a PDF, TIFF or + GIF file. + + Attributes: + input_config (~.image_annotator.InputConfig): + Required. Information about the input file. + features (Sequence[~.image_annotator.Feature]): + Required. Requested features. + image_context (~.image_annotator.ImageContext): + Additional context that may accompany the + image(s) in the file. + pages (Sequence[int]): + Pages of the file to perform image + annotation. + Pages starts from 1, we assume the first page of + the file is page 1. At most 5 pages are + supported per request. Pages can be negative. + Page 1 means the first page. + Page 2 means the second page. + Page -1 means the last page. + Page -2 means the second to the last page. + + If the file is GIF instead of PDF or TIFF, page + refers to GIF frames. + If this field is empty, by default the service + performs image annotation for the first 5 pages + of the file. + """ + + input_config = proto.Field(proto.MESSAGE, number=1, message="InputConfig",) + + features = proto.RepeatedField(proto.MESSAGE, number=2, message=Feature,) + + image_context = proto.Field(proto.MESSAGE, number=3, message=ImageContext,) + + pages = proto.RepeatedField(proto.INT32, number=4) + + +class AnnotateFileResponse(proto.Message): + r"""Response to a single file annotation request. A file may + contain one or more images, which individually have their own + responses. + + Attributes: + input_config (~.image_annotator.InputConfig): + Information about the file for which this + response is generated. + responses (Sequence[~.image_annotator.AnnotateImageResponse]): + Individual responses to images found within the file. This + field will be empty if the ``error`` field is set. + total_pages (int): + This field gives the total number of pages in + the file. + error (~.status.Status): + If set, represents the error message for the failed request. + The ``responses`` field will not be set in this case. + """ + + input_config = proto.Field(proto.MESSAGE, number=1, message="InputConfig",) + + responses = proto.RepeatedField( + proto.MESSAGE, number=2, message=AnnotateImageResponse, + ) + + total_pages = proto.Field(proto.INT32, number=3) + + error = proto.Field(proto.MESSAGE, number=4, message=status.Status,) + + +class BatchAnnotateFilesRequest(proto.Message): + r"""A list of requests to annotate files using the + BatchAnnotateFiles API. + + Attributes: + requests (Sequence[~.image_annotator.AnnotateFileRequest]): + Required. The list of file annotation + requests. Right now we support only one + AnnotateFileRequest in + BatchAnnotateFilesRequest. + """ + + requests = proto.RepeatedField( + proto.MESSAGE, number=1, message=AnnotateFileRequest, + ) + + +class BatchAnnotateFilesResponse(proto.Message): + r"""A list of file annotation responses. + + Attributes: + responses (Sequence[~.image_annotator.AnnotateFileResponse]): + The list of file annotation responses, each + response corresponding to each + AnnotateFileRequest in + BatchAnnotateFilesRequest. + """ + + responses = proto.RepeatedField( + proto.MESSAGE, number=1, message=AnnotateFileResponse, + ) + + +class AsyncAnnotateFileRequest(proto.Message): + r"""An offline file annotation request. + + Attributes: + input_config (~.image_annotator.InputConfig): + Required. Information about the input file. + features (Sequence[~.image_annotator.Feature]): + Required. Requested features. + image_context (~.image_annotator.ImageContext): + Additional context that may accompany the + image(s) in the file. + output_config (~.image_annotator.OutputConfig): + Required. The desired output location and + metadata (e.g. format). + """ + + input_config = proto.Field(proto.MESSAGE, number=1, message="InputConfig",) + + features = proto.RepeatedField(proto.MESSAGE, number=2, message=Feature,) + + image_context = proto.Field(proto.MESSAGE, number=3, message=ImageContext,) + + output_config = proto.Field(proto.MESSAGE, number=4, message="OutputConfig",) + + +class AsyncAnnotateFileResponse(proto.Message): + r"""The response for a single offline file annotation request. + + Attributes: + output_config (~.image_annotator.OutputConfig): + The output location and metadata from + AsyncAnnotateFileRequest. + """ + + output_config = proto.Field(proto.MESSAGE, number=1, message="OutputConfig",) + + +class AsyncBatchAnnotateImagesRequest(proto.Message): + r"""Request for async image annotation for a list of images. + + Attributes: + requests (Sequence[~.image_annotator.AnnotateImageRequest]): + Required. Individual image annotation + requests for this batch. + output_config (~.image_annotator.OutputConfig): + Required. The desired output location and + metadata (e.g. format). + """ + + requests = proto.RepeatedField( + proto.MESSAGE, number=1, message=AnnotateImageRequest, + ) + + output_config = proto.Field(proto.MESSAGE, number=2, message="OutputConfig",) + + +class AsyncBatchAnnotateImagesResponse(proto.Message): + r"""Response to an async batch image annotation request. + + Attributes: + output_config (~.image_annotator.OutputConfig): + The output location and metadata from + AsyncBatchAnnotateImagesRequest. + """ + + output_config = proto.Field(proto.MESSAGE, number=1, message="OutputConfig",) + + +class AsyncBatchAnnotateFilesRequest(proto.Message): + r"""Multiple async file annotation requests are batched into a + single service call. + + Attributes: + requests (Sequence[~.image_annotator.AsyncAnnotateFileRequest]): + Required. Individual async file annotation + requests for this batch. + """ + + requests = proto.RepeatedField( + proto.MESSAGE, number=1, message=AsyncAnnotateFileRequest, + ) + + +class AsyncBatchAnnotateFilesResponse(proto.Message): + r"""Response to an async batch file annotation request. + + Attributes: + responses (Sequence[~.image_annotator.AsyncAnnotateFileResponse]): + The list of file annotation responses, one + for each request in + AsyncBatchAnnotateFilesRequest. + """ + + responses = proto.RepeatedField( + proto.MESSAGE, number=1, message=AsyncAnnotateFileResponse, + ) + + +class InputConfig(proto.Message): + r"""The desired input location and metadata. + + Attributes: + gcs_source (~.image_annotator.GcsSource): + The Google Cloud Storage location to read the + input from. + content (bytes): + File content, represented as a stream of bytes. Note: As + with all ``bytes`` fields, protobuffers use a pure binary + representation, whereas JSON representations use base64. + + Currently, this field only works for BatchAnnotateFiles + requests. It does not work for AsyncBatchAnnotateFiles + requests. + mime_type (str): + The type of the file. Currently only + "application/pdf", "image/tiff" and "image/gif" + are supported. Wildcards are not supported. + """ + + gcs_source = proto.Field(proto.MESSAGE, number=1, message="GcsSource",) + + content = proto.Field(proto.BYTES, number=3) + + mime_type = proto.Field(proto.STRING, number=2) + + +class OutputConfig(proto.Message): + r"""The desired output location and metadata. + + Attributes: + gcs_destination (~.image_annotator.GcsDestination): + The Google Cloud Storage location to write + the output(s) to. + batch_size (int): + The max number of response protos to put into each output + JSON file on Google Cloud Storage. The valid range is [1, + 100]. If not specified, the default value is 20. + + For example, for one pdf file with 100 pages, 100 response + protos will be generated. If ``batch_size`` = 20, then 5 + json files each containing 20 response protos will be + written under the prefix ``gcs_destination``.\ ``uri``. + + Currently, batch_size only applies to GcsDestination, with + potential future support for other output configurations. + """ + + gcs_destination = proto.Field(proto.MESSAGE, number=1, message="GcsDestination",) + + batch_size = proto.Field(proto.INT32, number=2) + + +class GcsSource(proto.Message): + r"""The Google Cloud Storage location where the input will be + read from. + + Attributes: + uri (str): + Google Cloud Storage URI for the input file. + This must only be a Google Cloud Storage object. + Wildcards are not currently supported. + """ + + uri = proto.Field(proto.STRING, number=1) + + +class GcsDestination(proto.Message): + r"""The Google Cloud Storage location where the output will be + written to. + + Attributes: + uri (str): + Google Cloud Storage URI prefix where the results will be + stored. Results will be in JSON format and preceded by its + corresponding input URI prefix. This field can either + represent a gcs file prefix or gcs directory. In either + case, the uri should be unique because in order to get all + of the output files, you will need to do a wildcard gcs + search on the uri prefix you provide. + + Examples: + + - File Prefix: gs://bucket-name/here/filenameprefix The + output files will be created in gs://bucket-name/here/ + and the names of the output files will begin with + "filenameprefix". + + - Directory Prefix: gs://bucket-name/some/location/ The + output files will be created in + gs://bucket-name/some/location/ and the names of the + output files could be anything because there was no + filename prefix specified. + + If multiple outputs, each response is still + AnnotateFileResponse, each of which contains some subset of + the full list of AnnotateImageResponse. Multiple outputs can + happen if, for example, the output JSON is too large and + overflows into multiple sharded files. + """ + + uri = proto.Field(proto.STRING, number=1) + + +class OperationMetadata(proto.Message): + r"""Contains metadata for the BatchAnnotateImages operation. + + Attributes: + state (~.image_annotator.OperationMetadata.State): + Current state of the batch operation. + create_time (~.timestamp.Timestamp): + The time when the batch request was received. + update_time (~.timestamp.Timestamp): + The time when the operation result was last + updated. + """ + + class State(proto.Enum): + r"""Batch operation states.""" + STATE_UNSPECIFIED = 0 + CREATED = 1 + RUNNING = 2 + DONE = 3 + CANCELLED = 4 + + state = proto.Field(proto.ENUM, number=1, enum=State,) + + create_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + + update_time = proto.Field(proto.MESSAGE, number=6, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p4beta1/types/product_search.py b/google/cloud/vision_v1p4beta1/types/product_search.py new file mode 100644 index 00000000..e16037c9 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/types/product_search.py @@ -0,0 +1,185 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.vision_v1p4beta1.types import geometry +from google.cloud.vision_v1p4beta1.types import product_search_service +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p4beta1", + manifest={"ProductSearchParams", "ProductSearchResults",}, +) + + +class ProductSearchParams(proto.Message): + r"""Parameters for a product search request. + + Attributes: + bounding_poly (~.geometry.BoundingPoly): + The bounding polygon around the area of + interest in the image. If it is not specified, + system discretion will be applied. + product_set (str): + The resource name of a + [ProductSet][google.cloud.vision.v1p4beta1.ProductSet] to be + searched for similar images. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID``. + product_categories (Sequence[str]): + The list of product categories to search in. + Currently, we only consider the first category, + and either "homegoods-v2", "apparel-v2", + "toys-v2", "packagedgoods-v1", or "general-v1" + should be specified. The legacy categories + "homegoods", "apparel", and "toys" are still + supported but will be deprecated. For new + products, please use "homegoods-v2", + "apparel-v2", or "toys-v2" for better product + search accuracy. It is recommended to migrate + existing products to these categories as well. + filter (str): + The filtering expression. This can be used to + restrict search results based on Product labels. + We currently support an AND of OR of key-value + expressions, where each expression within an OR + must have the same key. An '=' should be used to + connect the key and value. + For example, "(color = red OR color = blue) AND + brand = Google" is acceptable, but "(color = red + OR brand = Google)" is not acceptable. "color: + red" is not acceptable because it uses a ':' + instead of an '='. + """ + + bounding_poly = proto.Field(proto.MESSAGE, number=9, message=geometry.BoundingPoly,) + + product_set = proto.Field(proto.STRING, number=6) + + product_categories = proto.RepeatedField(proto.STRING, number=7) + + filter = proto.Field(proto.STRING, number=8) + + +class ProductSearchResults(proto.Message): + r"""Results for a product search request. + + Attributes: + index_time (~.timestamp.Timestamp): + Timestamp of the index which provided these + results. Products added to the product set and + products removed from the product set after this + time are not reflected in the current results. + results (Sequence[~.product_search.ProductSearchResults.Result]): + List of results, one for each product match. + product_grouped_results (Sequence[~.product_search.ProductSearchResults.GroupedResult]): + List of results grouped by products detected + in the query image. Each entry corresponds to + one bounding polygon in the query image, and + contains the matching products specific to that + region. There may be duplicate product matches + in the union of all the per-product results. + """ + + class Result(proto.Message): + r"""Information about a product. + + Attributes: + product (~.product_search_service.Product): + The Product. + score (float): + A confidence level on the match, ranging from + 0 (no confidence) to 1 (full confidence). + image (str): + The resource name of the image from the + product that is the closest match to the query. + """ + + product = proto.Field( + proto.MESSAGE, number=1, message=product_search_service.Product, + ) + + score = proto.Field(proto.FLOAT, number=2) + + image = proto.Field(proto.STRING, number=3) + + class ObjectAnnotation(proto.Message): + r"""Prediction for what the object in the bounding box is. + + Attributes: + mid (str): + Object ID that should align with + EntityAnnotation mid. + language_code (str): + The BCP-47 language code, such as "en-US" or "sr-Latn". For + more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + name (str): + Object name, expressed in its ``language_code`` language. + score (float): + Score of the result. Range [0, 1]. + """ + + mid = proto.Field(proto.STRING, number=1) + + language_code = proto.Field(proto.STRING, number=2) + + name = proto.Field(proto.STRING, number=3) + + score = proto.Field(proto.FLOAT, number=4) + + class GroupedResult(proto.Message): + r"""Information about the products similar to a single product in + a query image. + + Attributes: + bounding_poly (~.geometry.BoundingPoly): + The bounding polygon around the product + detected in the query image. + results (Sequence[~.product_search.ProductSearchResults.Result]): + List of results, one for each product match. + object_annotations (Sequence[~.product_search.ProductSearchResults.ObjectAnnotation]): + List of generic predictions for the object in + the bounding box. + """ + + bounding_poly = proto.Field( + proto.MESSAGE, number=1, message=geometry.BoundingPoly, + ) + + results = proto.RepeatedField( + proto.MESSAGE, number=2, message="ProductSearchResults.Result", + ) + + object_annotations = proto.RepeatedField( + proto.MESSAGE, number=3, message="ProductSearchResults.ObjectAnnotation", + ) + + index_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + results = proto.RepeatedField(proto.MESSAGE, number=5, message=Result,) + + product_grouped_results = proto.RepeatedField( + proto.MESSAGE, number=6, message=GroupedResult, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p4beta1/types/product_search_service.py b/google/cloud/vision_v1p4beta1/types/product_search_service.py new file mode 100644 index 00000000..66a480f5 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/types/product_search_service.py @@ -0,0 +1,891 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.vision_v1p4beta1.types import geometry +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p4beta1", + manifest={ + "Product", + "ProductSet", + "ReferenceImage", + "CreateProductRequest", + "ListProductsRequest", + "ListProductsResponse", + "GetProductRequest", + "UpdateProductRequest", + "DeleteProductRequest", + "CreateProductSetRequest", + "ListProductSetsRequest", + "ListProductSetsResponse", + "GetProductSetRequest", + "UpdateProductSetRequest", + "DeleteProductSetRequest", + "CreateReferenceImageRequest", + "ListReferenceImagesRequest", + "ListReferenceImagesResponse", + "GetReferenceImageRequest", + "DeleteReferenceImageRequest", + "AddProductToProductSetRequest", + "RemoveProductFromProductSetRequest", + "ListProductsInProductSetRequest", + "ListProductsInProductSetResponse", + "ImportProductSetsGcsSource", + "ImportProductSetsInputConfig", + "ImportProductSetsRequest", + "ImportProductSetsResponse", + "BatchOperationMetadata", + "ProductSetPurgeConfig", + "PurgeProductsRequest", + }, +) + + +class Product(proto.Message): + r"""A Product contains ReferenceImages. + + Attributes: + name (str): + The resource name of the product. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + + This field is ignored when creating a product. + display_name (str): + The user-provided name for this Product. Must + not be empty. Must be at most 4096 characters + long. + description (str): + User-provided metadata to be stored with this + product. Must be at most 4096 characters long. + product_category (str): + Immutable. The category for the product + identified by the reference image. This should + be either "homegoods-v2", "apparel-v2", or + "toys-v2". The legacy categories "homegoods", + "apparel", and "toys" are still supported, but + these should not be used for new products. + product_labels (Sequence[~.product_search_service.Product.KeyValue]): + Key-value pairs that can be attached to a product. At query + time, constraints can be specified based on the + product_labels. + + Note that integer values can be provided as strings, e.g. + "1199". Only strings with integer values can match a + range-based restriction which is to be supported soon. + + Multiple values can be assigned to the same key. One product + may have up to 500 product_labels. + + Notice that the total number of distinct product_labels over + all products in one ProductSet cannot exceed 1M, otherwise + the product search pipeline will refuse to work for that + ProductSet. + """ + + class KeyValue(proto.Message): + r"""A product label represented as a key-value pair. + + Attributes: + key (str): + The key of the label attached to the product. + Cannot be empty and cannot exceed 128 bytes. + value (str): + The value of the label attached to the + product. Cannot be empty and cannot exceed 128 + bytes. + """ + + key = proto.Field(proto.STRING, number=1) + + value = proto.Field(proto.STRING, number=2) + + name = proto.Field(proto.STRING, number=1) + + display_name = proto.Field(proto.STRING, number=2) + + description = proto.Field(proto.STRING, number=3) + + product_category = proto.Field(proto.STRING, number=4) + + product_labels = proto.RepeatedField(proto.MESSAGE, number=5, message=KeyValue,) + + +class ProductSet(proto.Message): + r"""A ProductSet contains Products. A ProductSet can contain a + maximum of 1 million reference images. If the limit is exceeded, + periodic indexing will fail. + + Attributes: + name (str): + The resource name of the ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID``. + + This field is ignored when creating a ProductSet. + display_name (str): + The user-provided name for this ProductSet. + Must not be empty. Must be at most 4096 + characters long. + index_time (~.timestamp.Timestamp): + Output only. The time at which this + ProductSet was last indexed. Query results will + reflect all updates before this time. If this + ProductSet has never been indexed, this + timestamp is the default value + "1970-01-01T00:00:00Z". + + This field is ignored when creating a + ProductSet. + index_error (~.status.Status): + Output only. If there was an error with + indexing the product set, the field is + populated. + This field is ignored when creating a + ProductSet. + """ + + name = proto.Field(proto.STRING, number=1) + + display_name = proto.Field(proto.STRING, number=2) + + index_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + index_error = proto.Field(proto.MESSAGE, number=4, message=status.Status,) + + +class ReferenceImage(proto.Message): + r"""A ``ReferenceImage`` represents a product image and its associated + metadata, such as bounding boxes. + + Attributes: + name (str): + The resource name of the reference image. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. + + This field is ignored when creating a reference image. + uri (str): + Required. The Google Cloud Storage URI of the reference + image. + + The URI must start with ``gs://``. + bounding_polys (Sequence[~.geometry.BoundingPoly]): + Optional. Bounding polygons around the areas + of interest in the reference image. If this + field is empty, the system will try to detect + regions of interest. At most 10 bounding + polygons will be used. + The provided shape is converted into a non- + rotated rectangle. Once converted, the small + edge of the rectangle must be greater than or + equal to 300 pixels. The aspect ratio must be + 1:4 or less (i.e. 1:3 is ok; 1:5 is not). + """ + + name = proto.Field(proto.STRING, number=1) + + uri = proto.Field(proto.STRING, number=2) + + bounding_polys = proto.RepeatedField( + proto.MESSAGE, number=3, message=geometry.BoundingPoly, + ) + + +class CreateProductRequest(proto.Message): + r"""Request message for the ``CreateProduct`` method. + + Attributes: + parent (str): + Required. The project in which the Product should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + product (~.product_search_service.Product): + Required. The product to create. + product_id (str): + A user-supplied resource id for this Product. If set, the + server will attempt to use this value as the resource id. If + it is already in use, an error is returned with code + ALREADY_EXISTS. Must be at most 128 characters long. It + cannot contain the character ``/``. + """ + + parent = proto.Field(proto.STRING, number=1) + + product = proto.Field(proto.MESSAGE, number=2, message=Product,) + + product_id = proto.Field(proto.STRING, number=3) + + +class ListProductsRequest(proto.Message): + r"""Request message for the ``ListProducts`` method. + + Attributes: + parent (str): + Required. The project OR ProductSet from which Products + should be listed. + + Format: ``projects/PROJECT_ID/locations/LOC_ID`` + page_size (int): + The maximum number of items to return. + Default 10, maximum 100. + page_token (str): + The next_page_token returned from a previous List request, + if any. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListProductsResponse(proto.Message): + r"""Response message for the ``ListProducts`` method. + + Attributes: + products (Sequence[~.product_search_service.Product]): + List of products. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + products = proto.RepeatedField(proto.MESSAGE, number=1, message=Product,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetProductRequest(proto.Message): + r"""Request message for the ``GetProduct`` method. + + Attributes: + name (str): + Required. Resource name of the Product to get. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + +class UpdateProductRequest(proto.Message): + r"""Request message for the ``UpdateProduct`` method. + + Attributes: + product (~.product_search_service.Product): + Required. The Product resource which replaces + the one on the server. product.name is + immutable. + update_mask (~.field_mask.FieldMask): + The [FieldMask][google.protobuf.FieldMask] that specifies + which fields to update. If update_mask isn't specified, all + mutable fields are to be updated. Valid mask paths include + ``product_labels``, ``display_name``, and ``description``. + """ + + product = proto.Field(proto.MESSAGE, number=1, message=Product,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class DeleteProductRequest(proto.Message): + r"""Request message for the ``DeleteProduct`` method. + + Attributes: + name (str): + Required. Resource name of product to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + +class CreateProductSetRequest(proto.Message): + r"""Request message for the ``CreateProductSet`` method. + + Attributes: + parent (str): + Required. The project in which the ProductSet should be + created. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + product_set (~.product_search_service.ProductSet): + Required. The ProductSet to create. + product_set_id (str): + A user-supplied resource id for this ProductSet. If set, the + server will attempt to use this value as the resource id. If + it is already in use, an error is returned with code + ALREADY_EXISTS. Must be at most 128 characters long. It + cannot contain the character ``/``. + """ + + parent = proto.Field(proto.STRING, number=1) + + product_set = proto.Field(proto.MESSAGE, number=2, message=ProductSet,) + + product_set_id = proto.Field(proto.STRING, number=3) + + +class ListProductSetsRequest(proto.Message): + r"""Request message for the ``ListProductSets`` method. + + Attributes: + parent (str): + Required. The project from which ProductSets should be + listed. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + page_size (int): + The maximum number of items to return. + Default 10, maximum 100. + page_token (str): + The next_page_token returned from a previous List request, + if any. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListProductSetsResponse(proto.Message): + r"""Response message for the ``ListProductSets`` method. + + Attributes: + product_sets (Sequence[~.product_search_service.ProductSet]): + List of ProductSets. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + product_sets = proto.RepeatedField(proto.MESSAGE, number=1, message=ProductSet,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetProductSetRequest(proto.Message): + r"""Request message for the ``GetProductSet`` method. + + Attributes: + name (str): + Required. Resource name of the ProductSet to get. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + +class UpdateProductSetRequest(proto.Message): + r"""Request message for the ``UpdateProductSet`` method. + + Attributes: + product_set (~.product_search_service.ProductSet): + Required. The ProductSet resource which + replaces the one on the server. + update_mask (~.field_mask.FieldMask): + The [FieldMask][google.protobuf.FieldMask] that specifies + which fields to update. If update_mask isn't specified, all + mutable fields are to be updated. Valid mask path is + ``display_name``. + """ + + product_set = proto.Field(proto.MESSAGE, number=1, message=ProductSet,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class DeleteProductSetRequest(proto.Message): + r"""Request message for the ``DeleteProductSet`` method. + + Attributes: + name (str): + Required. Resource name of the ProductSet to delete. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + +class CreateReferenceImageRequest(proto.Message): + r"""Request message for the ``CreateReferenceImage`` method. + + Attributes: + parent (str): + Required. Resource name of the product in which to create + the reference image. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + reference_image (~.product_search_service.ReferenceImage): + Required. The reference image to create. + If an image ID is specified, it is ignored. + reference_image_id (str): + A user-supplied resource id for the ReferenceImage to be + added. If set, the server will attempt to use this value as + the resource id. If it is already in use, an error is + returned with code ALREADY_EXISTS. Must be at most 128 + characters long. It cannot contain the character ``/``. + """ + + parent = proto.Field(proto.STRING, number=1) + + reference_image = proto.Field(proto.MESSAGE, number=2, message=ReferenceImage,) + + reference_image_id = proto.Field(proto.STRING, number=3) + + +class ListReferenceImagesRequest(proto.Message): + r"""Request message for the ``ListReferenceImages`` method. + + Attributes: + parent (str): + Required. Resource name of the product containing the + reference images. + + Format is + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID``. + page_size (int): + The maximum number of items to return. + Default 10, maximum 100. + page_token (str): + A token identifying a page of results to be returned. This + is the value of ``nextPageToken`` returned in a previous + reference image list request. + + Defaults to the first page if not specified. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListReferenceImagesResponse(proto.Message): + r"""Response message for the ``ListReferenceImages`` method. + + Attributes: + reference_images (Sequence[~.product_search_service.ReferenceImage]): + The list of reference images. + page_size (int): + The maximum number of items to return. + Default 10, maximum 100. + next_page_token (str): + The next_page_token returned from a previous List request, + if any. + """ + + @property + def raw_page(self): + return self + + reference_images = proto.RepeatedField( + proto.MESSAGE, number=1, message=ReferenceImage, + ) + + page_size = proto.Field(proto.INT32, number=2) + + next_page_token = proto.Field(proto.STRING, number=3) + + +class GetReferenceImageRequest(proto.Message): + r"""Request message for the ``GetReferenceImage`` method. + + Attributes: + name (str): + Required. The resource name of the ReferenceImage to get. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. + """ + + name = proto.Field(proto.STRING, number=1) + + +class DeleteReferenceImageRequest(proto.Message): + r"""Request message for the ``DeleteReferenceImage`` method. + + Attributes: + name (str): + Required. The resource name of the reference image to + delete. + + Format is: + + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + +class AddProductToProductSetRequest(proto.Message): + r"""Request message for the ``AddProductToProductSet`` method. + + Attributes: + name (str): + Required. The resource name for the ProductSet to modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + product (str): + Required. The resource name for the Product to be added to + this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + product = proto.Field(proto.STRING, number=2) + + +class RemoveProductFromProductSetRequest(proto.Message): + r"""Request message for the ``RemoveProductFromProductSet`` method. + + Attributes: + name (str): + Required. The resource name for the ProductSet to modify. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + product (str): + Required. The resource name for the Product to be removed + from this ProductSet. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` + """ + + name = proto.Field(proto.STRING, number=1) + + product = proto.Field(proto.STRING, number=2) + + +class ListProductsInProductSetRequest(proto.Message): + r"""Request message for the ``ListProductsInProductSet`` method. + + Attributes: + name (str): + Required. The ProductSet resource for which to retrieve + Products. + + Format is: + ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` + page_size (int): + The maximum number of items to return. + Default 10, maximum 100. + page_token (str): + The next_page_token returned from a previous List request, + if any. + """ + + name = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + +class ListProductsInProductSetResponse(proto.Message): + r"""Response message for the ``ListProductsInProductSet`` method. + + Attributes: + products (Sequence[~.product_search_service.Product]): + The list of Products. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + products = proto.RepeatedField(proto.MESSAGE, number=1, message=Product,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class ImportProductSetsGcsSource(proto.Message): + r"""The Google Cloud Storage location for a csv file which + preserves a list of ImportProductSetRequests in each line. + + Attributes: + csv_file_uri (str): + The Google Cloud Storage URI of the input csv file. + + The URI must start with ``gs://``. + + The format of the input csv file should be one image per + line. In each line, there are 8 columns. + + 1. image-uri + 2. image-id + 3. product-set-id + 4. product-id + 5. product-category + 6. product-display-name + 7. labels + 8. bounding-poly + + The ``image-uri``, ``product-set-id``, ``product-id``, and + ``product-category`` columns are required. All other columns + are optional. + + If the ``ProductSet`` or ``Product`` specified by the + ``product-set-id`` and ``product-id`` values does not exist, + then the system will create a new ``ProductSet`` or + ``Product`` for the image. In this case, the + ``product-display-name`` column refers to + [display_name][google.cloud.vision.v1p4beta1.Product.display_name], + the ``product-category`` column refers to + [product_category][google.cloud.vision.v1p4beta1.Product.product_category], + and the ``labels`` column refers to + [product_labels][google.cloud.vision.v1p4beta1.Product.product_labels]. + + The ``image-id`` column is optional but must be unique if + provided. If it is empty, the system will automatically + assign a unique id to the image. + + The ``product-display-name`` column is optional. If it is + empty, the system sets the + [display_name][google.cloud.vision.v1p4beta1.Product.display_name] + field for the product to a space (" "). You can update the + ``display_name`` later by using the API. + + If a ``Product`` with the specified ``product-id`` already + exists, then the system ignores the + ``product-display-name``, ``product-category``, and + ``labels`` columns. + + The ``labels`` column (optional) is a line containing a list + of comma-separated key-value pairs, in the following format: + + :: + + "key_1=value_1,key_2=value_2,...,key_n=value_n" + + The ``bounding-poly`` column (optional) identifies one + region of interest from the image in the same manner as + ``CreateReferenceImage``. If you do not specify the + ``bounding-poly`` column, then the system will try to detect + regions of interest automatically. + + At most one ``bounding-poly`` column is allowed per line. If + the image contains multiple regions of interest, add a line + to the CSV file that includes the same product information, + and the ``bounding-poly`` values for each region of + interest. + + The ``bounding-poly`` column must contain an even number of + comma-separated numbers, in the format + "p1_x,p1_y,p2_x,p2_y,...,pn_x,pn_y". Use non-negative + integers for absolute bounding polygons, and float values in + [0, 1] for normalized bounding polygons. + + The system will resize the image if the image resolution is + too large to process (larger than 20MP). + """ + + csv_file_uri = proto.Field(proto.STRING, number=1) + + +class ImportProductSetsInputConfig(proto.Message): + r"""The input content for the ``ImportProductSets`` method. + + Attributes: + gcs_source (~.product_search_service.ImportProductSetsGcsSource): + The Google Cloud Storage location for a csv + file which preserves a list of + ImportProductSetRequests in each line. + """ + + gcs_source = proto.Field( + proto.MESSAGE, number=1, oneof="source", message=ImportProductSetsGcsSource, + ) + + +class ImportProductSetsRequest(proto.Message): + r"""Request message for the ``ImportProductSets`` method. + + Attributes: + parent (str): + Required. The project in which the ProductSets should be + imported. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + input_config (~.product_search_service.ImportProductSetsInputConfig): + Required. The input content for the list of + requests. + """ + + parent = proto.Field(proto.STRING, number=1) + + input_config = proto.Field( + proto.MESSAGE, number=2, message=ImportProductSetsInputConfig, + ) + + +class ImportProductSetsResponse(proto.Message): + r"""Response message for the ``ImportProductSets`` method. + + This message is returned by the + [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] + method in the returned + [google.longrunning.Operation.response][google.longrunning.Operation.response] + field. + + Attributes: + reference_images (Sequence[~.product_search_service.ReferenceImage]): + The list of reference_images that are imported successfully. + statuses (Sequence[~.status.Status]): + The rpc status for each ImportProductSet request, including + both successes and errors. + + The number of statuses here matches the number of lines in + the csv file, and statuses[i] stores the success or failure + status of processing the i-th line of the csv, starting from + line 0. + """ + + reference_images = proto.RepeatedField( + proto.MESSAGE, number=1, message=ReferenceImage, + ) + + statuses = proto.RepeatedField(proto.MESSAGE, number=2, message=status.Status,) + + +class BatchOperationMetadata(proto.Message): + r"""Metadata for the batch operations such as the current state. + + This is included in the ``metadata`` field of the ``Operation`` + returned by the ``GetOperation`` call of the + ``google::longrunning::Operations`` service. + + Attributes: + state (~.product_search_service.BatchOperationMetadata.State): + The current state of the batch operation. + submit_time (~.timestamp.Timestamp): + The time when the batch request was submitted + to the server. + end_time (~.timestamp.Timestamp): + The time when the batch request is finished and + [google.longrunning.Operation.done][google.longrunning.Operation.done] + is set to true. + """ + + class State(proto.Enum): + r"""Enumerates the possible states that the batch request can be + in. + """ + STATE_UNSPECIFIED = 0 + PROCESSING = 1 + SUCCESSFUL = 2 + FAILED = 3 + CANCELLED = 4 + + state = proto.Field(proto.ENUM, number=1, enum=State,) + + submit_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +class ProductSetPurgeConfig(proto.Message): + r"""Config to control which ProductSet contains the Products to + be deleted. + + Attributes: + product_set_id (str): + The ProductSet that contains the Products to delete. If a + Product is a member of product_set_id in addition to other + ProductSets, the Product will still be deleted. + """ + + product_set_id = proto.Field(proto.STRING, number=1) + + +class PurgeProductsRequest(proto.Message): + r"""Request message for the ``PurgeProducts`` method. + + Attributes: + product_set_purge_config (~.product_search_service.ProductSetPurgeConfig): + Specify which ProductSet contains the + Products to be deleted. + delete_orphan_products (bool): + If delete_orphan_products is true, all Products that are not + in any ProductSet will be deleted. + parent (str): + Required. The project and location in which the Products + should be deleted. + + Format is ``projects/PROJECT_ID/locations/LOC_ID``. + force (bool): + The default value is false. Override this + value to true to actually perform the purge. + """ + + product_set_purge_config = proto.Field( + proto.MESSAGE, number=2, oneof="target", message=ProductSetPurgeConfig, + ) + + delete_orphan_products = proto.Field(proto.BOOL, number=3, oneof="target") + + parent = proto.Field(proto.STRING, number=1) + + force = proto.Field(proto.BOOL, number=4) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p4beta1/types/text_annotation.py b/google/cloud/vision_v1p4beta1/types/text_annotation.py new file mode 100644 index 00000000..f20e9a1a --- /dev/null +++ b/google/cloud/vision_v1p4beta1/types/text_annotation.py @@ -0,0 +1,320 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.vision_v1p4beta1.types import geometry + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p4beta1", + manifest={"TextAnnotation", "Page", "Block", "Paragraph", "Word", "Symbol",}, +) + + +class TextAnnotation(proto.Message): + r"""TextAnnotation contains a structured representation of OCR extracted + text. The hierarchy of an OCR extracted text structure is like this: + TextAnnotation -> Page -> Block -> Paragraph -> Word -> Symbol Each + structural component, starting from Page, may further have their own + properties. Properties describe detected languages, breaks etc.. + Please refer to the + [TextAnnotation.TextProperty][google.cloud.vision.v1p4beta1.TextAnnotation.TextProperty] + message definition below for more detail. + + Attributes: + pages (Sequence[~.text_annotation.Page]): + List of pages detected by OCR. + text (str): + UTF-8 text detected on the pages. + """ + + class DetectedLanguage(proto.Message): + r"""Detected language for a structural component. + + Attributes: + language_code (str): + The BCP-47 language code, such as "en-US" or "sr-Latn". For + more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + confidence (float): + Confidence of detected language. Range [0, 1]. + """ + + language_code = proto.Field(proto.STRING, number=1) + + confidence = proto.Field(proto.FLOAT, number=2) + + class DetectedBreak(proto.Message): + r"""Detected start or end of a structural component. + + Attributes: + type_ (~.text_annotation.TextAnnotation.DetectedBreak.BreakType): + Detected break type. + is_prefix (bool): + True if break prepends the element. + """ + + class BreakType(proto.Enum): + r"""Enum to denote the type of break found. New line, space etc.""" + UNKNOWN = 0 + SPACE = 1 + SURE_SPACE = 2 + EOL_SURE_SPACE = 3 + HYPHEN = 4 + LINE_BREAK = 5 + + type_ = proto.Field( + proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", + ) + + is_prefix = proto.Field(proto.BOOL, number=2) + + class TextProperty(proto.Message): + r"""Additional information detected on the structural component. + + Attributes: + detected_languages (Sequence[~.text_annotation.TextAnnotation.DetectedLanguage]): + A list of detected languages together with + confidence. + detected_break (~.text_annotation.TextAnnotation.DetectedBreak): + Detected start or end of a text segment. + """ + + detected_languages = proto.RepeatedField( + proto.MESSAGE, number=1, message="TextAnnotation.DetectedLanguage", + ) + + detected_break = proto.Field( + proto.MESSAGE, number=2, message="TextAnnotation.DetectedBreak", + ) + + pages = proto.RepeatedField(proto.MESSAGE, number=1, message="Page",) + + text = proto.Field(proto.STRING, number=2) + + +class Page(proto.Message): + r"""Detected page from OCR. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected on the page. + width (int): + Page width. For PDFs the unit is points. For + images (including TIFFs) the unit is pixels. + height (int): + Page height. For PDFs the unit is points. For + images (including TIFFs) the unit is pixels. + blocks (Sequence[~.text_annotation.Block]): + List of blocks of text, images etc on this + page. + confidence (float): + Confidence of the OCR results on the page. Range [0, 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + width = proto.Field(proto.INT32, number=2) + + height = proto.Field(proto.INT32, number=3) + + blocks = proto.RepeatedField(proto.MESSAGE, number=4, message="Block",) + + confidence = proto.Field(proto.FLOAT, number=5) + + +class Block(proto.Message): + r"""Logical element on the page. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the + block. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the block. The vertices are in the + order of top-left, top-right, bottom-right, bottom-left. + When a rotation of the bounding box is detected the rotation + is represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: + + :: + + 0----1 + | | + 3----2 + + - when it's rotated 180 degrees around the top-left corner + it becomes: + + :: + + 2----3 + | | + 1----0 + + and the vertex order will still be (0, 1, 2, 3). + paragraphs (Sequence[~.text_annotation.Paragraph]): + List of paragraphs in this block (if this + blocks is of type text). + block_type (~.text_annotation.Block.BlockType): + Detected block type (text, image etc) for + this block. + confidence (float): + Confidence of the OCR results on the block. Range [0, 1]. + """ + + class BlockType(proto.Enum): + r"""Type of a block (text, image etc) as identified by OCR.""" + UNKNOWN = 0 + TEXT = 1 + TABLE = 2 + PICTURE = 3 + RULER = 4 + BARCODE = 5 + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + paragraphs = proto.RepeatedField(proto.MESSAGE, number=3, message="Paragraph",) + + block_type = proto.Field(proto.ENUM, number=4, enum=BlockType,) + + confidence = proto.Field(proto.FLOAT, number=5) + + +class Paragraph(proto.Message): + r"""Structural unit of text representing a number of words in + certain order. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the + paragraph. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the paragraph. The vertices are in the + order of top-left, top-right, bottom-right, bottom-left. + When a rotation of the bounding box is detected the rotation + is represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertex order will + still be (0, 1, 2, 3). + words (Sequence[~.text_annotation.Word]): + List of all words in this paragraph. + confidence (float): + Confidence of the OCR results for the paragraph. Range [0, + 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + words = proto.RepeatedField(proto.MESSAGE, number=3, message="Word",) + + confidence = proto.Field(proto.FLOAT, number=4) + + +class Word(proto.Message): + r"""A word representation. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the word. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the word. The vertices are in the order + of top-left, top-right, bottom-right, bottom-left. When a + rotation of the bounding box is detected the rotation is + represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertex order will + still be (0, 1, 2, 3). + symbols (Sequence[~.text_annotation.Symbol]): + List of symbols in the word. + The order of the symbols follows the natural + reading order. + confidence (float): + Confidence of the OCR results for the word. Range [0, 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + symbols = proto.RepeatedField(proto.MESSAGE, number=3, message="Symbol",) + + confidence = proto.Field(proto.FLOAT, number=4) + + +class Symbol(proto.Message): + r"""A single symbol representation. + + Attributes: + property (~.text_annotation.TextAnnotation.TextProperty): + Additional information detected for the + symbol. + bounding_box (~.geometry.BoundingPoly): + The bounding box for the symbol. The vertices are in the + order of top-left, top-right, bottom-right, bottom-left. + When a rotation of the bounding box is detected the rotation + is represented as around the top-left corner as defined when + the text is read in the 'natural' orientation. For example: + + - when the text is horizontal it might look like: 0----1 \| + \| 3----2 + - when it's rotated 180 degrees around the top-left corner + it becomes: 2----3 \| \| 1----0 and the vertex order will + still be (0, 1, 2, 3). + text (str): + The actual UTF-8 representation of the + symbol. + confidence (float): + Confidence of the OCR results for the symbol. Range [0, 1]. + """ + + property = proto.Field( + proto.MESSAGE, number=1, message=TextAnnotation.TextProperty, + ) + + bounding_box = proto.Field(proto.MESSAGE, number=2, message=geometry.BoundingPoly,) + + text = proto.Field(proto.STRING, number=3) + + confidence = proto.Field(proto.FLOAT, number=4) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/vision_v1p4beta1/types/web_detection.py b/google/cloud/vision_v1p4beta1/types/web_detection.py new file mode 100644 index 00000000..344fd0b0 --- /dev/null +++ b/google/cloud/vision_v1p4beta1/types/web_detection.py @@ -0,0 +1,163 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.vision.v1p4beta1", manifest={"WebDetection",}, +) + + +class WebDetection(proto.Message): + r"""Relevant information for the image from the Internet. + + Attributes: + web_entities (Sequence[~.web_detection.WebDetection.WebEntity]): + Deduced entities from similar images on the + Internet. + full_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Fully matching images from the Internet. + Can include resized copies of the query image. + partial_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Partial matching images from the Internet. + Those images are similar enough to share some + key-point features. For example an original + image will likely have partial matching for its + crops. + pages_with_matching_images (Sequence[~.web_detection.WebDetection.WebPage]): + Web pages containing the matching images from + the Internet. + visually_similar_images (Sequence[~.web_detection.WebDetection.WebImage]): + The visually similar image results. + best_guess_labels (Sequence[~.web_detection.WebDetection.WebLabel]): + The service's best guess as to the topic of + the request image. Inferred from similar images + on the open web. + """ + + class WebEntity(proto.Message): + r"""Entity deduced from similar images on the Internet. + + Attributes: + entity_id (str): + Opaque entity ID. + score (float): + Overall relevancy score for the entity. + Not normalized and not comparable across + different image queries. + description (str): + Canonical description of the entity, in + English. + """ + + entity_id = proto.Field(proto.STRING, number=1) + + score = proto.Field(proto.FLOAT, number=2) + + description = proto.Field(proto.STRING, number=3) + + class WebImage(proto.Message): + r"""Metadata for online images. + + Attributes: + url (str): + The result image URL. + score (float): + (Deprecated) Overall relevancy score for the + image. + """ + + url = proto.Field(proto.STRING, number=1) + + score = proto.Field(proto.FLOAT, number=2) + + class WebPage(proto.Message): + r"""Metadata for web pages. + + Attributes: + url (str): + The result web page URL. + score (float): + (Deprecated) Overall relevancy score for the + web page. + page_title (str): + Title for the web page, may contain HTML + markups. + full_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Fully matching images on the page. + Can include resized copies of the query image. + partial_matching_images (Sequence[~.web_detection.WebDetection.WebImage]): + Partial matching images on the page. + Those images are similar enough to share some + key-point features. For example an original + image will likely have partial matching for its + crops. + """ + + url = proto.Field(proto.STRING, number=1) + + score = proto.Field(proto.FLOAT, number=2) + + page_title = proto.Field(proto.STRING, number=3) + + full_matching_images = proto.RepeatedField( + proto.MESSAGE, number=4, message="WebDetection.WebImage", + ) + + partial_matching_images = proto.RepeatedField( + proto.MESSAGE, number=5, message="WebDetection.WebImage", + ) + + class WebLabel(proto.Message): + r"""Label to provide extra metadata for the web detection. + + Attributes: + label (str): + Label for extra metadata. + language_code (str): + The BCP-47 language code for ``label``, such as "en-US" or + "sr-Latn". For more information, see + http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. + """ + + label = proto.Field(proto.STRING, number=1) + + language_code = proto.Field(proto.STRING, number=2) + + web_entities = proto.RepeatedField(proto.MESSAGE, number=1, message=WebEntity,) + + full_matching_images = proto.RepeatedField( + proto.MESSAGE, number=2, message=WebImage, + ) + + partial_matching_images = proto.RepeatedField( + proto.MESSAGE, number=3, message=WebImage, + ) + + pages_with_matching_images = proto.RepeatedField( + proto.MESSAGE, number=4, message=WebPage, + ) + + visually_similar_images = proto.RepeatedField( + proto.MESSAGE, number=6, message=WebImage, + ) + + best_guess_labels = proto.RepeatedField(proto.MESSAGE, number=8, message=WebLabel,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/mypy.ini b/mypy.ini new file mode 100644 index 00000000..4505b485 --- /dev/null +++ b/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +namespace_packages = True diff --git a/noxfile.py b/noxfile.py index a6a01730..c23dbf75 100644 --- a/noxfile.py +++ b/noxfile.py @@ -27,8 +27,8 @@ BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] DEFAULT_PYTHON_VERSION = "3.8" -SYSTEM_TEST_PYTHON_VERSIONS = ["2.7", "3.8"] -UNIT_TEST_PYTHON_VERSIONS = ["2.7", "3.5", "3.6", "3.7", "3.8"] +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] +UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"] @nox.session(python=DEFAULT_PYTHON_VERSION) @@ -70,6 +70,8 @@ def lint_setup_py(session): def default(session): # Install all test dependencies, then install this package in-place. + session.install("asyncmock", "pytest-asyncio") + session.install("mock", "pytest", "pytest-cov") session.install("-e", ".") diff --git a/samples/snippets/crop_hints/crop_hints.py b/samples/snippets/crop_hints/crop_hints.py index 611eb564..766e4e00 100644 --- a/samples/snippets/crop_hints/crop_hints.py +++ b/samples/snippets/crop_hints/crop_hints.py @@ -26,7 +26,6 @@ import io from google.cloud import vision -from google.cloud.vision import types from PIL import Image, ImageDraw # [END vision_crop_hints_tutorial_imports] @@ -39,10 +38,10 @@ def get_crop_hint(path): with io.open(path, 'rb') as image_file: content = image_file.read() - image = types.Image(content=content) + image = vision.Image(content=content) - crop_hints_params = types.CropHintsParams(aspect_ratios=[1.77]) - image_context = types.ImageContext(crop_hints_params=crop_hints_params) + crop_hints_params = vision.CropHintsParams(aspect_ratios=[1.77]) + image_context = vision.ImageContext(crop_hints_params=crop_hints_params) response = client.crop_hints(image=image, image_context=image_context) hints = response.crop_hints_annotation.crop_hints diff --git a/samples/snippets/detect/beta_snippets.py b/samples/snippets/detect/beta_snippets.py index d5beb402..03dba60e 100644 --- a/samples/snippets/detect/beta_snippets.py +++ b/samples/snippets/detect/beta_snippets.py @@ -48,7 +48,7 @@ def localize_objects(path): with open(path, 'rb') as image_file: content = image_file.read() - image = vision.types.Image(content=content) + image = vision.Image(content=content) objects = client.object_localization( image=image).localized_object_annotations @@ -72,7 +72,7 @@ def localize_objects_uri(uri): from google.cloud import vision_v1p3beta1 as vision client = vision.ImageAnnotatorClient() - image = vision.types.Image() + image = vision.Image() image.source.image_uri = uri objects = client.object_localization( @@ -100,12 +100,12 @@ def detect_handwritten_ocr(path): with io.open(path, 'rb') as image_file: content = image_file.read() - image = vision.types.Image(content=content) + image = vision.Image(content=content) # Language hint codes for handwritten OCR: # en-t-i0-handwrit, mul-Latn-t-i0-handwrit # Note: Use only one language hint code per request for handwritten OCR. - image_context = vision.types.ImageContext( + image_context = vision.ImageContext( language_hints=['en-t-i0-handwrit']) response = client.document_text_detection(image=image, @@ -149,13 +149,13 @@ def detect_handwritten_ocr_uri(uri): """ from google.cloud import vision_v1p3beta1 as vision client = vision.ImageAnnotatorClient() - image = vision.types.Image() + image = vision.Image() image.source.image_uri = uri # Language hint codes for handwritten OCR: # en-t-i0-handwrit, mul-Latn-t-i0-handwrit # Note: Use only one language hint code per request for handwritten OCR. - image_context = vision.types.ImageContext( + image_context = vision.ImageContext( language_hints=['en-t-i0-handwrit']) response = client.document_text_detection(image=image, @@ -207,16 +207,16 @@ def detect_batch_annotate_files(path): # Other supported mime_types: image/tiff' or 'image/gif' mime_type = 'application/pdf' - input_config = vision.types.InputConfig( + input_config = vision.InputConfig( content=content, mime_type=mime_type) - feature = vision.types.Feature( - type=vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION) + feature = vision.Feature( + type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION) # Annotate the first two pages and the last one (max 5 pages) # First page starts at 1, and not 0. Last page is -1. pages = [1, 2, -1] - request = vision.types.AnnotateFileRequest( + request = vision.AnnotateFileRequest( input_config=input_config, features=[feature], pages=pages) @@ -255,16 +255,16 @@ def detect_batch_annotate_files_uri(gcs_uri): # Other supported mime_types: image/tiff' or 'image/gif' mime_type = 'application/pdf' - input_config = vision.types.InputConfig( - gcs_source=vision.types.GcsSource(uri=gcs_uri), mime_type=mime_type) + input_config = vision.InputConfig( + gcs_source=vision.GcsSource(uri=gcs_uri), mime_type=mime_type) - feature = vision.types.Feature( - type=vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION) + feature = vision.Feature( + type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION) # Annotate the first two pages and the last one (max 5 pages) # First page starts at 1, and not 0. Last page is -1. pages = [1, 2, -1] - request = vision.types.AnnotateFileRequest( + request = vision.AnnotateFileRequest( input_config=input_config, features=[feature], pages=pages) @@ -299,24 +299,24 @@ def async_batch_annotate_images_uri(input_image_uri, output_uri): import re from google.cloud import storage - from google.protobuf import json_format + from google.cloud import vision_v1p4beta1 as vision client = vision.ImageAnnotatorClient() # Construct the request for the image(s) to be annotated: - image_source = vision.types.ImageSource(image_uri=input_image_uri) - image = vision.types.Image(source=image_source) + image_source = vision.ImageSource(image_uri=input_image_uri) + image = vision.Image(source=image_source) features = [ - vision.types.Feature(type=vision.enums.Feature.Type.LABEL_DETECTION), - vision.types.Feature(type=vision.enums.Feature.Type.TEXT_DETECTION), - vision.types.Feature(type=vision.enums.Feature.Type.IMAGE_PROPERTIES), + vision.Feature(type_=vision.Feature.Type.LABEL_DETECTION), + vision.Feature(type_=vision.Feature.Type.TEXT_DETECTION), + vision.Feature(type_=vision.Feature.Type.IMAGE_PROPERTIES), ] requests = [ - vision.types.AnnotateImageRequest(image=image, features=features), + vision.AnnotateImageRequest(image=image, features=features), ] - gcs_destination = vision.types.GcsDestination(uri=output_uri) - output_config = vision.types.OutputConfig( + gcs_destination = vision.GcsDestination(uri=output_uri) + output_config = vision.OutputConfig( gcs_destination=gcs_destination, batch_size=2) operation = client.async_batch_annotate_images( @@ -347,8 +347,7 @@ def async_batch_annotate_images_uri(input_image_uri, output_uri): output = blob_list[0] json_string = output.download_as_string() - response = json_format.Parse(json_string, - vision.types.BatchAnnotateImagesResponse()) + response = vision.BatchAnnotateImagesResponse.from_json(json_string) # Prints the actual response for the first annotate image request. print(u'The annotation response for the first request: {}'.format( diff --git a/samples/snippets/detect/detect.py b/samples/snippets/detect/detect.py index c2731bba..898c0546 100644 --- a/samples/snippets/detect/detect.py +++ b/samples/snippets/detect/detect.py @@ -48,7 +48,7 @@ def detect_faces(path): with io.open(path, 'rb') as image_file: content = image_file.read() - image = vision.types.Image(content=content) + image = vision.Image(content=content) # [END vision_python_migration_image_file] response = client.face_detection(image=image) @@ -84,7 +84,7 @@ def detect_faces_uri(uri): from google.cloud import vision client = vision.ImageAnnotatorClient() # [START vision_python_migration_image_uri] - image = vision.types.Image() + image = vision.Image() image.source.image_uri = uri # [END vision_python_migration_image_uri] @@ -125,7 +125,7 @@ def detect_labels(path): with io.open(path, 'rb') as image_file: content = image_file.read() - image = vision.types.Image(content=content) + image = vision.Image(content=content) response = client.label_detection(image=image) labels = response.label_annotations @@ -149,7 +149,7 @@ def detect_labels_uri(uri): Web.""" from google.cloud import vision client = vision.ImageAnnotatorClient() - image = vision.types.Image() + image = vision.Image() image.source.image_uri = uri response = client.label_detection(image=image) @@ -178,7 +178,7 @@ def detect_landmarks(path): with io.open(path, 'rb') as image_file: content = image_file.read() - image = vision.types.Image(content=content) + image = vision.Image(content=content) response = client.landmark_detection(image=image) landmarks = response.landmark_annotations @@ -206,7 +206,7 @@ def detect_landmarks_uri(uri): Web.""" from google.cloud import vision client = vision.ImageAnnotatorClient() - image = vision.types.Image() + image = vision.Image() image.source.image_uri = uri response = client.landmark_detection(image=image) @@ -235,7 +235,7 @@ def detect_logos(path): with io.open(path, 'rb') as image_file: content = image_file.read() - image = vision.types.Image(content=content) + image = vision.Image(content=content) response = client.logo_detection(image=image) logos = response.logo_annotations @@ -259,7 +259,7 @@ def detect_logos_uri(uri): """ from google.cloud import vision client = vision.ImageAnnotatorClient() - image = vision.types.Image() + image = vision.Image() image.source.image_uri = uri response = client.logo_detection(image=image) @@ -288,7 +288,7 @@ def detect_safe_search(path): with io.open(path, 'rb') as image_file: content = image_file.read() - image = vision.types.Image(content=content) + image = vision.Image(content=content) response = client.safe_search_detection(image=image) safe = response.safe_search_annotation @@ -319,7 +319,7 @@ def detect_safe_search_uri(uri): on the Web.""" from google.cloud import vision client = vision.ImageAnnotatorClient() - image = vision.types.Image() + image = vision.Image() image.source.image_uri = uri response = client.safe_search_detection(image=image) @@ -355,7 +355,7 @@ def detect_text(path): with io.open(path, 'rb') as image_file: content = image_file.read() - image = vision.types.Image(content=content) + image = vision.Image(content=content) response = client.text_detection(image=image) texts = response.text_annotations @@ -384,7 +384,7 @@ def detect_text_uri(uri): """ from google.cloud import vision client = vision.ImageAnnotatorClient() - image = vision.types.Image() + image = vision.Image() image.source.image_uri = uri response = client.text_detection(image=image) @@ -418,7 +418,7 @@ def detect_properties(path): with io.open(path, 'rb') as image_file: content = image_file.read() - image = vision.types.Image(content=content) + image = vision.Image(content=content) response = client.image_properties(image=image) props = response.image_properties_annotation @@ -446,7 +446,7 @@ def detect_properties_uri(uri): on the Web.""" from google.cloud import vision client = vision.ImageAnnotatorClient() - image = vision.types.Image() + image = vision.Image() image.source.image_uri = uri response = client.image_properties(image=image) @@ -479,7 +479,7 @@ def detect_web(path): with io.open(path, 'rb') as image_file: content = image_file.read() - image = vision.types.Image(content=content) + image = vision.Image(content=content) response = client.web_detection(image=image) annotations = response.web_detection @@ -538,7 +538,7 @@ def detect_web_uri(uri): """Detects web annotations in the file located in Google Cloud Storage.""" from google.cloud import vision client = vision.ImageAnnotatorClient() - image = vision.types.Image() + image = vision.Image() image.source.image_uri = uri response = client.web_detection(image=image) @@ -603,11 +603,11 @@ def web_entities_include_geo_results(path): with io.open(path, 'rb') as image_file: content = image_file.read() - image = vision.types.Image(content=content) + image = vision.Image(content=content) - web_detection_params = vision.types.WebDetectionParams( + web_detection_params = vision.WebDetectionParams( include_geo_results=True) - image_context = vision.types.ImageContext( + image_context = vision.ImageContext( web_detection_params=web_detection_params) response = client.web_detection(image=image, image_context=image_context) @@ -632,12 +632,12 @@ def web_entities_include_geo_results_uri(uri): from google.cloud import vision client = vision.ImageAnnotatorClient() - image = vision.types.Image() + image = vision.Image() image.source.image_uri = uri - web_detection_params = vision.types.WebDetectionParams( + web_detection_params = vision.WebDetectionParams( include_geo_results=True) - image_context = vision.types.ImageContext( + image_context = vision.ImageContext( web_detection_params=web_detection_params) response = client.web_detection(image=image, image_context=image_context) @@ -664,10 +664,10 @@ def detect_crop_hints(path): # [START vision_python_migration_crop_hints] with io.open(path, 'rb') as image_file: content = image_file.read() - image = vision.types.Image(content=content) + image = vision.Image(content=content) - crop_hints_params = vision.types.CropHintsParams(aspect_ratios=[1.77]) - image_context = vision.types.ImageContext( + crop_hints_params = vision.CropHintsParams(aspect_ratios=[1.77]) + image_context = vision.ImageContext( crop_hints_params=crop_hints_params) response = client.crop_hints(image=image, image_context=image_context) @@ -695,11 +695,11 @@ def detect_crop_hints_uri(uri): """Detects crop hints in the file located in Google Cloud Storage.""" from google.cloud import vision client = vision.ImageAnnotatorClient() - image = vision.types.Image() + image = vision.Image() image.source.image_uri = uri - crop_hints_params = vision.types.CropHintsParams(aspect_ratios=[1.77]) - image_context = vision.types.ImageContext( + crop_hints_params = vision.CropHintsParams(aspect_ratios=[1.77]) + image_context = vision.ImageContext( crop_hints_params=crop_hints_params) response = client.crop_hints(image=image, image_context=image_context) @@ -732,7 +732,7 @@ def detect_document(path): with io.open(path, 'rb') as image_file: content = image_file.read() - image = vision.types.Image(content=content) + image = vision.Image(content=content) response = client.document_text_detection(image=image) @@ -770,7 +770,7 @@ def detect_document_uri(uri): Storage.""" from google.cloud import vision client = vision.ImageAnnotatorClient() - image = vision.types.Image() + image = vision.Image() image.source.image_uri = uri response = client.document_text_detection(image=image) @@ -805,10 +805,11 @@ def detect_document_uri(uri): # [START vision_text_detection_pdf_gcs] def async_detect_document(gcs_source_uri, gcs_destination_uri): """OCR with PDF/TIFF as source files on GCS""" + import json import re from google.cloud import vision from google.cloud import storage - from google.protobuf import json_format + # Supported mime_types are: 'application/pdf' and 'image/tiff' mime_type = 'application/pdf' @@ -817,18 +818,18 @@ def async_detect_document(gcs_source_uri, gcs_destination_uri): client = vision.ImageAnnotatorClient() - feature = vision.types.Feature( - type=vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION) + feature = vision.Feature( + type_=vision.Feature.Type.DOCUMENT_TEXT_DETECTION) - gcs_source = vision.types.GcsSource(uri=gcs_source_uri) - input_config = vision.types.InputConfig( + gcs_source = vision.GcsSource(uri=gcs_source_uri) + input_config = vision.InputConfig( gcs_source=gcs_source, mime_type=mime_type) - gcs_destination = vision.types.GcsDestination(uri=gcs_destination_uri) - output_config = vision.types.OutputConfig( + gcs_destination = vision.GcsDestination(uri=gcs_destination_uri) + output_config = vision.OutputConfig( gcs_destination=gcs_destination, batch_size=batch_size) - async_request = vision.types.AsyncAnnotateFileRequest( + async_request = vision.AsyncAnnotateFileRequest( features=[feature], input_config=input_config, output_config=output_config) @@ -860,19 +861,18 @@ def async_detect_document(gcs_source_uri, gcs_destination_uri): output = blob_list[0] json_string = output.download_as_string() - response = json_format.Parse( - json_string, vision.types.AnnotateFileResponse()) + response = json.loads(json_string) # The actual response for the first page of the input file. - first_page_response = response.responses[0] - annotation = first_page_response.full_text_annotation + first_page_response = response['responses'][0] + annotation = first_page_response['fullTextAnnotation'] # Here we print the full text from the first page. # The response contains more information: # annotation/pages/blocks/paragraphs/words/symbols # including confidence scores and bounding boxes - print(u'Full text:\n{}'.format( - annotation.text)) + print('Full text:\n') + print(annotation['text']) # [END vision_text_detection_pdf_gcs] @@ -888,7 +888,7 @@ def localize_objects(path): with open(path, 'rb') as image_file: content = image_file.read() - image = vision.types.Image(content=content) + image = vision.Image(content=content) objects = client.object_localization( image=image).localized_object_annotations @@ -912,7 +912,7 @@ def localize_objects_uri(uri): from google.cloud import vision client = vision.ImageAnnotatorClient() - image = vision.types.Image() + image = vision.Image() image.source.image_uri = uri objects = client.object_localization( diff --git a/samples/snippets/detect/set_endpoint.py b/samples/snippets/detect/set_endpoint.py index 44361436..1261b024 100644 --- a/samples/snippets/detect/set_endpoint.py +++ b/samples/snippets/detect/set_endpoint.py @@ -22,9 +22,9 @@ def set_endpoint(): client = vision.ImageAnnotatorClient(client_options=client_options) # [END vision_set_endpoint] - image_source = vision.types.ImageSource( + image_source = vision.ImageSource( image_uri='gs://cloud-samples-data/vision/text/screen.jpg') - image = vision.types.Image(source=image_source) + image = vision.Image(source=image_source) response = client.text_detection(image=image) diff --git a/samples/snippets/detect/vision_async_batch_annotate_images.py b/samples/snippets/detect/vision_async_batch_annotate_images.py index 5a9bd8fd..68d4a298 100644 --- a/samples/snippets/detect/vision_async_batch_annotate_images.py +++ b/samples/snippets/detect/vision_async_batch_annotate_images.py @@ -15,7 +15,6 @@ # [START vision_async_batch_annotate_images] from google.cloud import vision_v1 -from google.cloud.vision_v1 import enums def sample_async_batch_annotate_images( @@ -28,8 +27,8 @@ def sample_async_batch_annotate_images( source = {"image_uri": input_image_uri} image = {"source": source} features = [ - {"type": enums.Feature.Type.LABEL_DETECTION}, - {"type": enums.Feature.Type.IMAGE_PROPERTIES}, + {"type_": vision_v1.Feature.Type.LABEL_DETECTION}, + {"type_": vision_v1.Feature.Type.IMAGE_PROPERTIES}, ] # Each requests element corresponds to a single image. To annotate more @@ -43,7 +42,7 @@ def sample_async_batch_annotate_images( output_config = {"gcs_destination": gcs_destination, "batch_size": batch_size} - operation = client.async_batch_annotate_images(requests, output_config) + operation = client.async_batch_annotate_images(requests=requests, output_config=output_config) print("Waiting for operation to complete...") response = operation.result(90) diff --git a/samples/snippets/detect/vision_batch_annotate_files.py b/samples/snippets/detect/vision_batch_annotate_files.py index 1658d4fd..98345840 100644 --- a/samples/snippets/detect/vision_batch_annotate_files.py +++ b/samples/snippets/detect/vision_batch_annotate_files.py @@ -17,7 +17,6 @@ import io from google.cloud import vision_v1 -from google.cloud.vision_v1 import enums def sample_batch_annotate_files(file_path="path/to/your/document.pdf"): @@ -29,14 +28,14 @@ def sample_batch_annotate_files(file_path="path/to/your/document.pdf"): with io.open(file_path, "rb") as f: content = f.read() input_config = {"mime_type": mime_type, "content": content} - features = [{"type": enums.Feature.Type.DOCUMENT_TEXT_DETECTION}] + features = [{"type_": vision_v1.Feature.Type.DOCUMENT_TEXT_DETECTION}] # The service can process up to 5 pages per document file. Here we specify # the first, second, and last page of the document to be processed. pages = [1, 2, -1] requests = [{"input_config": input_config, "features": features, "pages": pages}] - response = client.batch_annotate_files(requests) + response = client.batch_annotate_files(requests=requests) for image_response in response.responses[0].responses: print(u"Full text: {}".format(image_response.full_text_annotation.text)) for page in image_response.full_text_annotation.pages: diff --git a/samples/snippets/detect/vision_batch_annotate_files_gcs.py b/samples/snippets/detect/vision_batch_annotate_files_gcs.py index 76c80a38..0cd0c204 100644 --- a/samples/snippets/detect/vision_batch_annotate_files_gcs.py +++ b/samples/snippets/detect/vision_batch_annotate_files_gcs.py @@ -15,7 +15,6 @@ # [START vision_batch_annotate_files_gcs] from google.cloud import vision_v1 -from google.cloud.vision_v1 import enums def sample_batch_annotate_files( @@ -28,7 +27,7 @@ def sample_batch_annotate_files( gcs_source = {"uri": storage_uri} input_config = {"gcs_source": gcs_source, "mime_type": mime_type} - features = [{"type": enums.Feature.Type.DOCUMENT_TEXT_DETECTION}] + features = [{"type_": vision_v1.Feature.Type.DOCUMENT_TEXT_DETECTION}] # The service can process up to 5 pages per document file. # Here we specify the first, second, and last page of the document to be @@ -36,7 +35,7 @@ def sample_batch_annotate_files( pages = [1, 2, -1] requests = [{"input_config": input_config, "features": features, "pages": pages}] - response = client.batch_annotate_files(requests) + response = client.batch_annotate_files(requests=requests) for image_response in response.responses[0].responses: print(u"Full text: {}".format(image_response.full_text_annotation.text)) for page in image_response.full_text_annotation.pages: diff --git a/samples/snippets/document_text/doctext.py b/samples/snippets/document_text/doctext.py index 29d82d6b..1f7a5a84 100644 --- a/samples/snippets/document_text/doctext.py +++ b/samples/snippets/document_text/doctext.py @@ -26,7 +26,6 @@ import io from google.cloud import vision -from google.cloud.vision import types from PIL import Image, ImageDraw # [END vision_document_text_tutorial_imports] @@ -62,7 +61,7 @@ def get_document_bounds(image_file, feature): with io.open(image_file, 'rb') as image_file: content = image_file.read() - image = types.Image(content=content) + image = vision.Image(content=content) response = client.document_text_detection(image=image) document = response.full_text_annotation diff --git a/samples/snippets/face_detection/faces.py b/samples/snippets/face_detection/faces.py index 7b95fa1e..b325e0ce 100755 --- a/samples/snippets/face_detection/faces.py +++ b/samples/snippets/face_detection/faces.py @@ -20,7 +20,6 @@ # [START vision_face_detection_tutorial_imports] from google.cloud import vision -from google.cloud.vision import types from PIL import Image, ImageDraw # [END vision_face_detection_tutorial_imports] @@ -40,7 +39,7 @@ def detect_face(face_file, max_results=4): # [END vision_face_detection_tutorial_client] content = face_file.read() - image = types.Image(content=content) + image = vision.Image(content=content) return client.face_detection( image=image, max_results=max_results).face_annotations diff --git a/samples/snippets/product_search/import_product_sets.py b/samples/snippets/product_search/import_product_sets.py index e2d03714..e2937509 100755 --- a/samples/snippets/product_search/import_product_sets.py +++ b/samples/snippets/product_search/import_product_sets.py @@ -40,13 +40,12 @@ def import_product_sets(project_id, location, gcs_uri): client = vision.ProductSearchClient() # A resource that represents Google Cloud Platform location. - location_path = client.location_path( - project=project_id, location=location) + location_path = f"projects/{project_id}/locations/{location}" # Set the input configuration along with Google Cloud Storage URI - gcs_source = vision.types.ImportProductSetsGcsSource( + gcs_source = vision.ImportProductSetsGcsSource( csv_file_uri=gcs_uri) - input_config = vision.types.ImportProductSetsInputConfig( + input_config = vision.ImportProductSetsInputConfig( gcs_source=gcs_source) # Import the product sets from the input URI. diff --git a/samples/snippets/product_search/product_in_product_set_management.py b/samples/snippets/product_search/product_in_product_set_management.py index ad16ab7e..282bc8d8 100755 --- a/samples/snippets/product_search/product_in_product_set_management.py +++ b/samples/snippets/product_search/product_in_product_set_management.py @@ -131,21 +131,21 @@ def purge_products_in_product_set( """ client = vision.ProductSearchClient() - parent = client.location_path( - project=project_id, location=location) + parent = f"projects/{project_id}/locations/{location}" - product_set_purge_config = vision.types.ProductSetPurgeConfig( + product_set_purge_config = vision.ProductSetPurgeConfig( product_set_id=product_set_id) # The purge operation is async. - operation = client.purge_products( - parent=parent, - product_set_purge_config=product_set_purge_config, + operation = client.purge_products(request={ + "parent": parent, + "product_set_purge_config": product_set_purge_config, # The operation is irreversible and removes multiple products. # The user is required to pass in force=True to actually perform the # purge. # If force is not set to True, the service raises an exception. - force=force) + "force": force + }) operation.result(timeout=300) diff --git a/samples/snippets/product_search/product_management.py b/samples/snippets/product_search/product_management.py index 46ed4f7b..96eb5872 100755 --- a/samples/snippets/product_search/product_management.py +++ b/samples/snippets/product_search/product_management.py @@ -30,6 +30,7 @@ # [START vision_product_search_update_product_labels] # [START vision_product_search_purge_orphan_products] from google.cloud import vision +from google.protobuf import field_mask_pb2 as field_mask # [END vision_product_search_create_product] # [END vision_product_search_delete_product] @@ -54,11 +55,11 @@ def create_product( client = vision.ProductSearchClient() # A resource that represents Google Cloud Platform location. - location_path = client.location_path(project=project_id, location=location) + location_path = f"projects/{project_id}/locations/{location}" # Create a product with the product specification in the region. # Set product display name and product category. - product = vision.types.Product( + product = vision.Product( display_name=product_display_name, product_category=product_category) @@ -83,7 +84,7 @@ def list_products(project_id, location): client = vision.ProductSearchClient() # A resource that represents Google Cloud Platform location. - location_path = client.location_path(project=project_id, location=location) + location_path = f"projects/{project_id}/locations/{location}" # List all the products available in the region. products = client.list_products(parent=location_path) @@ -145,13 +146,13 @@ def update_product_labels( # Set product name, product label and product display name. # Multiple labels are also supported. - key_value = vision.types.Product.KeyValue(key=key, value=value) - product = vision.types.Product( + key_value = vision.Product.KeyValue(key=key, value=value) + product = vision.Product( name=product_path, product_labels=[key_value]) # Updating only the product_labels field here. - update_mask = vision.types.FieldMask(paths=['product_labels']) + update_mask = field_mask.FieldMask(paths=['product_labels']) # This overwrites the product_labels. updated_product = client.update_product( @@ -192,18 +193,18 @@ def purge_orphan_products(project_id, location, force): """ client = vision.ProductSearchClient() - parent = client.location_path( - project=project_id, location=location) + parent = f"projects/{project_id}/locations/{location}" # The purge operation is async. - operation = client.purge_products( - parent=parent, - delete_orphan_products=True, + operation = client.purge_products(request={ + "parent": parent, + "delete_orphan_products": True, # The operation is irreversible and removes multiple products. # The user is required to pass in force=True to actually perform the # purge. # If force is not set to True, the service raises an exception. - force=force) + "force": force + }) operation.result(timeout=300) diff --git a/samples/snippets/product_search/product_search.py b/samples/snippets/product_search/product_search.py index 89c8f168..abfd5342 100755 --- a/samples/snippets/product_search/product_search.py +++ b/samples/snippets/product_search/product_search.py @@ -58,17 +58,17 @@ def get_similar_products_file( content = image_file.read() # Create annotate image request along with product search feature. - image = vision.types.Image(content=content) + image = vision.Image(content=content) # product search specific parameters product_set_path = product_search_client.product_set_path( project=project_id, location=location, product_set=product_set_id) - product_search_params = vision.types.ProductSearchParams( + product_search_params = vision.ProductSearchParams( product_set=product_set_path, product_categories=[product_category], filter=filter) - image_context = vision.types.ImageContext( + image_context = vision.ImageContext( product_search_params=product_search_params) # Search products similar to the image. @@ -76,9 +76,8 @@ def get_similar_products_file( image, image_context=image_context) index_time = response.product_search_results.index_time - print('Product set index time:') - print(' seconds: {}'.format(index_time.seconds)) - print(' nanos: {}\n'.format(index_time.nanos)) + print('Product set index time: ') + print(index_time) results = response.product_search_results.results @@ -119,18 +118,18 @@ def get_similar_products_uri( image_annotator_client = vision.ImageAnnotatorClient() # Create annotate image request along with product search feature. - image_source = vision.types.ImageSource(image_uri=image_uri) - image = vision.types.Image(source=image_source) + image_source = vision.ImageSource(image_uri=image_uri) + image = vision.Image(source=image_source) # product search specific parameters product_set_path = product_search_client.product_set_path( project=project_id, location=location, product_set=product_set_id) - product_search_params = vision.types.ProductSearchParams( + product_search_params = vision.ProductSearchParams( product_set=product_set_path, product_categories=[product_category], filter=filter) - image_context = vision.types.ImageContext( + image_context = vision.ImageContext( product_search_params=product_search_params) # Search products similar to the image. @@ -138,9 +137,8 @@ def get_similar_products_uri( image, image_context=image_context) index_time = response.product_search_results.index_time - print('Product set index time:') - print(' seconds: {}'.format(index_time.seconds)) - print(' nanos: {}\n'.format(index_time.nanos)) + print('Product set index time: ') + print(index_time) results = response.product_search_results.results diff --git a/samples/snippets/product_search/product_set_management.py b/samples/snippets/product_search/product_set_management.py index 7964bc27..995fc472 100755 --- a/samples/snippets/product_search/product_set_management.py +++ b/samples/snippets/product_search/product_set_management.py @@ -48,11 +48,10 @@ def create_product_set( client = vision.ProductSearchClient() # A resource that represents Google Cloud Platform location. - location_path = client.location_path( - project=project_id, location=location) + location_path = f"projects/{project_id}/locations/{location}" # Create a product set with the product set specification in the region. - product_set = vision.types.ProductSet( + product_set = vision.ProductSet( display_name=product_set_display_name) # The response is the product set with `name` populated. @@ -76,8 +75,7 @@ def list_product_sets(project_id, location): client = vision.ProductSearchClient() # A resource that represents Google Cloud Platform location. - location_path = client.location_path( - project=project_id, location=location) + location_path = f"projects/{project_id}/locations/{location}" # List all the product sets available in the region. product_sets = client.list_product_sets(parent=location_path) @@ -87,9 +85,8 @@ def list_product_sets(project_id, location): print('Product set name: {}'.format(product_set.name)) print('Product set id: {}'.format(product_set.name.split('/')[-1])) print('Product set display name: {}'.format(product_set.display_name)) - print('Product set index time:') - print(' seconds: {}'.format(product_set.index_time.seconds)) - print(' nanos: {}\n'.format(product_set.index_time.nanos)) + print('Product set index time: ') + print(product_set.index_time) # [END vision_product_search_list_product_sets] @@ -115,9 +112,8 @@ def get_product_set(project_id, location, product_set_id): print('Product set name: {}'.format(product_set.name)) print('Product set id: {}'.format(product_set.name.split('/')[-1])) print('Product set display name: {}'.format(product_set.display_name)) - print('Product set index time:') - print(' seconds: {}'.format(product_set.index_time.seconds)) - print(' nanos: {}'.format(product_set.index_time.nanos)) + print('Product set index time: ') + print(product_set.index_time) # [END vision_product_search_get_product_set] diff --git a/samples/snippets/product_search/reference_image_management.py b/samples/snippets/product_search/reference_image_management.py index 7e546b7e..4eebc3bf 100755 --- a/samples/snippets/product_search/reference_image_management.py +++ b/samples/snippets/product_search/reference_image_management.py @@ -53,7 +53,7 @@ def create_reference_image( project=project_id, location=location, product=product_id) # Create a reference image. - reference_image = vision.types.ReferenceImage(uri=gcs_uri) + reference_image = vision.ReferenceImage(uri=gcs_uri) # The response is the reference image with `name` populated. image = client.create_reference_image( diff --git a/samples/snippets/quickstart/quickstart.py b/samples/snippets/quickstart/quickstart.py index a8c7a5f2..521a1c18 100644 --- a/samples/snippets/quickstart/quickstart.py +++ b/samples/snippets/quickstart/quickstart.py @@ -23,7 +23,6 @@ def run_quickstart(): # Imports the Google Cloud client library # [START vision_python_migration_import] from google.cloud import vision - from google.cloud.vision import types # [END vision_python_migration_import] # Instantiates a client @@ -38,7 +37,7 @@ def run_quickstart(): with io.open(file_name, 'rb') as image_file: content = image_file.read() - image = types.Image(content=content) + image = vision.Image(content=content) # Performs label detection on the image file response = client.label_detection(image=image) diff --git a/samples/snippets/web/web_detect.py b/samples/snippets/web/web_detect.py index 6cdfa256..52b921e9 100644 --- a/samples/snippets/web/web_detect.py +++ b/samples/snippets/web/web_detect.py @@ -27,7 +27,6 @@ import io from google.cloud import vision -from google.cloud.vision import types # [END vision_web_detection_tutorial_imports] @@ -37,14 +36,14 @@ def annotate(path): client = vision.ImageAnnotatorClient() if path.startswith('http') or path.startswith('gs:'): - image = types.Image() + image = vision.Image() image.source.image_uri = path else: with io.open(path, 'rb') as image_file: content = image_file.read() - image = types.Image(content=content) + image = vision.Image(content=content) web_detection = client.web_detection(image=image).web_detection # [END vision_web_detection_tutorial_annotate] diff --git a/scripts/fixup_vision_v1_keywords.py b/scripts/fixup_vision_v1_keywords.py new file mode 100644 index 00000000..6071ce4b --- /dev/null +++ b/scripts/fixup_vision_v1_keywords.py @@ -0,0 +1,200 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class visionCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'add_product_to_product_set': ('name', 'product', ), + 'async_batch_annotate_files': ('requests', 'parent', ), + 'async_batch_annotate_images': ('requests', 'output_config', 'parent', ), + 'batch_annotate_files': ('requests', 'parent', ), + 'batch_annotate_images': ('requests', 'parent', ), + 'create_product': ('parent', 'product', 'product_id', ), + 'create_product_set': ('parent', 'product_set', 'product_set_id', ), + 'create_reference_image': ('parent', 'reference_image', 'reference_image_id', ), + 'delete_product': ('name', ), + 'delete_product_set': ('name', ), + 'delete_reference_image': ('name', ), + 'get_product': ('name', ), + 'get_product_set': ('name', ), + 'get_reference_image': ('name', ), + 'import_product_sets': ('parent', 'input_config', ), + 'list_products': ('parent', 'page_size', 'page_token', ), + 'list_product_sets': ('parent', 'page_size', 'page_token', ), + 'list_products_in_product_set': ('name', 'page_size', 'page_token', ), + 'list_reference_images': ('parent', 'page_size', 'page_token', ), + 'purge_products': ('parent', 'product_set_purge_config', 'delete_orphan_products', 'force', ), + 'remove_product_from_product_set': ('name', 'product', ), + 'update_product': ('product', 'update_mask', ), + 'update_product_set': ('product_set', 'update_mask', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=visionCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the vision client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/scripts/fixup_vision_v1p1beta1_keywords.py b/scripts/fixup_vision_v1p1beta1_keywords.py new file mode 100644 index 00000000..363a3f75 --- /dev/null +++ b/scripts/fixup_vision_v1p1beta1_keywords.py @@ -0,0 +1,178 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class visionCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_annotate_images': ('requests', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=visionCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the vision client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/scripts/fixup_vision_v1p2beta1_keywords.py b/scripts/fixup_vision_v1p2beta1_keywords.py new file mode 100644 index 00000000..a345a1f7 --- /dev/null +++ b/scripts/fixup_vision_v1p2beta1_keywords.py @@ -0,0 +1,179 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class visionCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'async_batch_annotate_files': ('requests', ), + 'batch_annotate_images': ('requests', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=visionCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the vision client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/scripts/fixup_vision_v1p3beta1_keywords.py b/scripts/fixup_vision_v1p3beta1_keywords.py new file mode 100644 index 00000000..9fcddd5b --- /dev/null +++ b/scripts/fixup_vision_v1p3beta1_keywords.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class visionCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'add_product_to_product_set': ('name', 'product', ), + 'async_batch_annotate_files': ('requests', ), + 'batch_annotate_images': ('requests', ), + 'create_product': ('parent', 'product', 'product_id', ), + 'create_product_set': ('parent', 'product_set', 'product_set_id', ), + 'create_reference_image': ('parent', 'reference_image', 'reference_image_id', ), + 'delete_product': ('name', ), + 'delete_product_set': ('name', ), + 'delete_reference_image': ('name', ), + 'get_product': ('name', ), + 'get_product_set': ('name', ), + 'get_reference_image': ('name', ), + 'import_product_sets': ('parent', 'input_config', ), + 'list_products': ('parent', 'page_size', 'page_token', ), + 'list_product_sets': ('parent', 'page_size', 'page_token', ), + 'list_products_in_product_set': ('name', 'page_size', 'page_token', ), + 'list_reference_images': ('parent', 'page_size', 'page_token', ), + 'remove_product_from_product_set': ('name', 'product', ), + 'update_product': ('product', 'update_mask', ), + 'update_product_set': ('product_set', 'update_mask', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=visionCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the vision client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/scripts/fixup_vision_v1p4beta1_keywords.py b/scripts/fixup_vision_v1p4beta1_keywords.py new file mode 100644 index 00000000..7877329b --- /dev/null +++ b/scripts/fixup_vision_v1p4beta1_keywords.py @@ -0,0 +1,200 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class visionCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'add_product_to_product_set': ('name', 'product', ), + 'async_batch_annotate_files': ('requests', ), + 'async_batch_annotate_images': ('requests', 'output_config', ), + 'batch_annotate_files': ('requests', ), + 'batch_annotate_images': ('requests', ), + 'create_product': ('parent', 'product', 'product_id', ), + 'create_product_set': ('parent', 'product_set', 'product_set_id', ), + 'create_reference_image': ('parent', 'reference_image', 'reference_image_id', ), + 'delete_product': ('name', ), + 'delete_product_set': ('name', ), + 'delete_reference_image': ('name', ), + 'get_product': ('name', ), + 'get_product_set': ('name', ), + 'get_reference_image': ('name', ), + 'import_product_sets': ('parent', 'input_config', ), + 'list_products': ('parent', 'page_size', 'page_token', ), + 'list_product_sets': ('parent', 'page_size', 'page_token', ), + 'list_products_in_product_set': ('name', 'page_size', 'page_token', ), + 'list_reference_images': ('parent', 'page_size', 'page_token', ), + 'purge_products': ('parent', 'product_set_purge_config', 'delete_orphan_products', 'force', ), + 'remove_product_from_product_set': ('name', 'product', ), + 'update_product': ('product', 'update_mask', ), + 'update_product_set': ('product_set', 'update_mask', ), + + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: not a.keyword.value in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), + cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=visionCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the vision client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/setup.py b/setup.py index b868d5d2..2d171f34 100644 --- a/setup.py +++ b/setup.py @@ -22,8 +22,9 @@ version = "1.0.0" release_status = "Development Status :: 5 - Production/Stable" dependencies = [ - "google-api-core[grpc] >= 1.14.0, < 2.0.0dev", - 'enum34; python_version < "3.4"', + "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", + "proto-plus >= 1.4.0", + "libcst >= 0.2.5", ] package_root = os.path.abspath(os.path.dirname(__file__)) @@ -33,7 +34,9 @@ readme = readme_file.read() packages = [ - package for package in setuptools.find_packages() if package.startswith("google") + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") ] namespaces = ["google"] @@ -54,12 +57,10 @@ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", "Operating System :: OS Independent", "Topic :: Internet", ], @@ -67,7 +68,14 @@ packages=packages, namespace_packages=namespaces, install_requires=dependencies, - python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*", + python_requires=">=3.6", + scripts=[ + "scripts/fixup_vision_v1_keywords.py", + "scripts/fixup_vision_v1p1beta1_keywords.py", + "scripts/fixup_vision_v1p2beta1_keywords.py", + "scripts/fixup_vision_v1p3beta1_keywords.py", + "scripts/fixup_vision_v1p4beta1_keywords.py", + ], include_package_data=True, zip_safe=False, ) diff --git a/synth.metadata b/synth.metadata index 3b9964ef..65ac2388 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,29 +4,21 @@ "git": { "name": ".", "remote": "https://github.com/googleapis/python-vision.git", - "sha": "3a6f4cda687219a198b53b6cd7d688d008103cd4" - } - }, - { - "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "b821f320473c8ec05a1c7fb9a496c958b1ab9834", - "internalRef": "331104099" + "sha": "a712e4055590022d6fdd748f07d9de773587eefe" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "b15c0c042cdea746fc19856527d8baf947c3c220" + "sha": "916c10e8581804df2b48a0f0457d848f3faa582e" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "b15c0c042cdea746fc19856527d8baf947c3c220" + "sha": "916c10e8581804df2b48a0f0457d848f3faa582e" } } ], @@ -76,230 +68,5 @@ "generator": "bazel" } } - ], - "generatedFiles": [ - ".coveragerc", - ".flake8", - ".github/CONTRIBUTING.md", - ".github/ISSUE_TEMPLATE/bug_report.md", - ".github/ISSUE_TEMPLATE/feature_request.md", - ".github/ISSUE_TEMPLATE/support_request.md", - ".github/PULL_REQUEST_TEMPLATE.md", - ".github/release-please.yml", - ".github/snippet-bot.yml", - ".gitignore", - ".kokoro/build.sh", - ".kokoro/continuous/common.cfg", - ".kokoro/continuous/continuous.cfg", - ".kokoro/docker/docs/Dockerfile", - ".kokoro/docker/docs/fetch_gpg_keys.sh", - ".kokoro/docs/common.cfg", - ".kokoro/docs/docs-presubmit.cfg", - ".kokoro/docs/docs.cfg", - ".kokoro/presubmit/common.cfg", - ".kokoro/presubmit/presubmit.cfg", - ".kokoro/publish-docs.sh", - ".kokoro/release.sh", - ".kokoro/release/common.cfg", - ".kokoro/release/release.cfg", - ".kokoro/samples/lint/common.cfg", - ".kokoro/samples/lint/continuous.cfg", - ".kokoro/samples/lint/periodic.cfg", - ".kokoro/samples/lint/presubmit.cfg", - ".kokoro/samples/python3.6/common.cfg", - ".kokoro/samples/python3.6/continuous.cfg", - ".kokoro/samples/python3.6/periodic.cfg", - ".kokoro/samples/python3.6/presubmit.cfg", - ".kokoro/samples/python3.7/common.cfg", - ".kokoro/samples/python3.7/continuous.cfg", - ".kokoro/samples/python3.7/periodic.cfg", - ".kokoro/samples/python3.7/presubmit.cfg", - ".kokoro/samples/python3.8/common.cfg", - ".kokoro/samples/python3.8/continuous.cfg", - ".kokoro/samples/python3.8/periodic.cfg", - ".kokoro/samples/python3.8/presubmit.cfg", - ".kokoro/test-samples.sh", - ".kokoro/trampoline.sh", - ".kokoro/trampoline_v2.sh", - ".trampolinerc", - "CODE_OF_CONDUCT.md", - "CONTRIBUTING.rst", - "LICENSE", - "MANIFEST.in", - "docs/_static/custom.css", - "docs/_templates/layout.html", - "docs/conf.py", - "docs/gapic/v1/api.rst", - "docs/gapic/v1/types.rst", - "docs/gapic/v1p2beta1/api.rst", - "docs/gapic/v1p2beta1/types.rst", - "docs/gapic/v1p3beta1/api.rst", - "docs/gapic/v1p3beta1/types.rst", - "docs/gapic/v1p4beta1/api.rst", - "docs/gapic/v1p4beta1/types.rst", - "docs/multiprocessing.rst", - "google/cloud/vision_v1/__init__.py", - "google/cloud/vision_v1/gapic/__init__.py", - "google/cloud/vision_v1/gapic/enums.py", - "google/cloud/vision_v1/gapic/image_annotator_client.py", - "google/cloud/vision_v1/gapic/image_annotator_client_config.py", - "google/cloud/vision_v1/gapic/product_search_client.py", - "google/cloud/vision_v1/gapic/product_search_client_config.py", - "google/cloud/vision_v1/gapic/transports/__init__.py", - "google/cloud/vision_v1/gapic/transports/image_annotator_grpc_transport.py", - "google/cloud/vision_v1/gapic/transports/product_search_grpc_transport.py", - "google/cloud/vision_v1/proto/__init__.py", - "google/cloud/vision_v1/proto/geometry.proto", - "google/cloud/vision_v1/proto/geometry_pb2.py", - "google/cloud/vision_v1/proto/geometry_pb2_grpc.py", - "google/cloud/vision_v1/proto/image_annotator.proto", - "google/cloud/vision_v1/proto/image_annotator_pb2.py", - "google/cloud/vision_v1/proto/image_annotator_pb2_grpc.py", - "google/cloud/vision_v1/proto/product_search.proto", - "google/cloud/vision_v1/proto/product_search_pb2.py", - "google/cloud/vision_v1/proto/product_search_pb2_grpc.py", - "google/cloud/vision_v1/proto/product_search_service.proto", - "google/cloud/vision_v1/proto/product_search_service_pb2.py", - "google/cloud/vision_v1/proto/product_search_service_pb2_grpc.py", - "google/cloud/vision_v1/proto/text_annotation.proto", - "google/cloud/vision_v1/proto/text_annotation_pb2.py", - "google/cloud/vision_v1/proto/text_annotation_pb2_grpc.py", - "google/cloud/vision_v1/proto/web_detection.proto", - "google/cloud/vision_v1/proto/web_detection_pb2.py", - "google/cloud/vision_v1/proto/web_detection_pb2_grpc.py", - "google/cloud/vision_v1/types.py", - "google/cloud/vision_v1p1beta1/__init__.py", - "google/cloud/vision_v1p1beta1/gapic/__init__.py", - "google/cloud/vision_v1p1beta1/gapic/enums.py", - "google/cloud/vision_v1p1beta1/gapic/image_annotator_client.py", - "google/cloud/vision_v1p1beta1/gapic/image_annotator_client_config.py", - "google/cloud/vision_v1p1beta1/gapic/transports/__init__.py", - "google/cloud/vision_v1p1beta1/gapic/transports/image_annotator_grpc_transport.py", - "google/cloud/vision_v1p1beta1/proto/__init__.py", - "google/cloud/vision_v1p1beta1/proto/geometry.proto", - "google/cloud/vision_v1p1beta1/proto/geometry_pb2.py", - "google/cloud/vision_v1p1beta1/proto/geometry_pb2_grpc.py", - "google/cloud/vision_v1p1beta1/proto/image_annotator.proto", - "google/cloud/vision_v1p1beta1/proto/image_annotator_pb2.py", - "google/cloud/vision_v1p1beta1/proto/image_annotator_pb2_grpc.py", - "google/cloud/vision_v1p1beta1/proto/text_annotation.proto", - "google/cloud/vision_v1p1beta1/proto/text_annotation_pb2.py", - "google/cloud/vision_v1p1beta1/proto/text_annotation_pb2_grpc.py", - "google/cloud/vision_v1p1beta1/proto/web_detection.proto", - "google/cloud/vision_v1p1beta1/proto/web_detection_pb2.py", - "google/cloud/vision_v1p1beta1/proto/web_detection_pb2_grpc.py", - "google/cloud/vision_v1p1beta1/types.py", - "google/cloud/vision_v1p2beta1/__init__.py", - "google/cloud/vision_v1p2beta1/gapic/__init__.py", - "google/cloud/vision_v1p2beta1/gapic/enums.py", - "google/cloud/vision_v1p2beta1/gapic/image_annotator_client.py", - "google/cloud/vision_v1p2beta1/gapic/image_annotator_client_config.py", - "google/cloud/vision_v1p2beta1/gapic/transports/__init__.py", - "google/cloud/vision_v1p2beta1/gapic/transports/image_annotator_grpc_transport.py", - "google/cloud/vision_v1p2beta1/proto/__init__.py", - "google/cloud/vision_v1p2beta1/proto/geometry.proto", - "google/cloud/vision_v1p2beta1/proto/geometry_pb2.py", - "google/cloud/vision_v1p2beta1/proto/geometry_pb2_grpc.py", - "google/cloud/vision_v1p2beta1/proto/image_annotator.proto", - "google/cloud/vision_v1p2beta1/proto/image_annotator_pb2.py", - "google/cloud/vision_v1p2beta1/proto/image_annotator_pb2_grpc.py", - "google/cloud/vision_v1p2beta1/proto/text_annotation.proto", - "google/cloud/vision_v1p2beta1/proto/text_annotation_pb2.py", - "google/cloud/vision_v1p2beta1/proto/text_annotation_pb2_grpc.py", - "google/cloud/vision_v1p2beta1/proto/web_detection.proto", - "google/cloud/vision_v1p2beta1/proto/web_detection_pb2.py", - "google/cloud/vision_v1p2beta1/proto/web_detection_pb2_grpc.py", - "google/cloud/vision_v1p2beta1/types.py", - "google/cloud/vision_v1p3beta1/__init__.py", - "google/cloud/vision_v1p3beta1/gapic/__init__.py", - "google/cloud/vision_v1p3beta1/gapic/enums.py", - "google/cloud/vision_v1p3beta1/gapic/image_annotator_client.py", - "google/cloud/vision_v1p3beta1/gapic/image_annotator_client_config.py", - "google/cloud/vision_v1p3beta1/gapic/product_search_client.py", - "google/cloud/vision_v1p3beta1/gapic/product_search_client_config.py", - "google/cloud/vision_v1p3beta1/gapic/transports/__init__.py", - "google/cloud/vision_v1p3beta1/gapic/transports/image_annotator_grpc_transport.py", - "google/cloud/vision_v1p3beta1/gapic/transports/product_search_grpc_transport.py", - "google/cloud/vision_v1p3beta1/proto/__init__.py", - "google/cloud/vision_v1p3beta1/proto/geometry.proto", - "google/cloud/vision_v1p3beta1/proto/geometry_pb2.py", - "google/cloud/vision_v1p3beta1/proto/geometry_pb2_grpc.py", - "google/cloud/vision_v1p3beta1/proto/image_annotator.proto", - "google/cloud/vision_v1p3beta1/proto/image_annotator_pb2.py", - "google/cloud/vision_v1p3beta1/proto/image_annotator_pb2_grpc.py", - "google/cloud/vision_v1p3beta1/proto/product_search.proto", - "google/cloud/vision_v1p3beta1/proto/product_search_pb2.py", - "google/cloud/vision_v1p3beta1/proto/product_search_pb2_grpc.py", - "google/cloud/vision_v1p3beta1/proto/product_search_service.proto", - "google/cloud/vision_v1p3beta1/proto/product_search_service_pb2.py", - "google/cloud/vision_v1p3beta1/proto/product_search_service_pb2_grpc.py", - "google/cloud/vision_v1p3beta1/proto/text_annotation.proto", - "google/cloud/vision_v1p3beta1/proto/text_annotation_pb2.py", - "google/cloud/vision_v1p3beta1/proto/text_annotation_pb2_grpc.py", - "google/cloud/vision_v1p3beta1/proto/web_detection.proto", - "google/cloud/vision_v1p3beta1/proto/web_detection_pb2.py", - "google/cloud/vision_v1p3beta1/proto/web_detection_pb2_grpc.py", - "google/cloud/vision_v1p3beta1/types.py", - "google/cloud/vision_v1p4beta1/__init__.py", - "google/cloud/vision_v1p4beta1/gapic/__init__.py", - "google/cloud/vision_v1p4beta1/gapic/enums.py", - "google/cloud/vision_v1p4beta1/gapic/image_annotator_client.py", - "google/cloud/vision_v1p4beta1/gapic/image_annotator_client_config.py", - "google/cloud/vision_v1p4beta1/gapic/product_search_client.py", - "google/cloud/vision_v1p4beta1/gapic/product_search_client_config.py", - "google/cloud/vision_v1p4beta1/gapic/transports/__init__.py", - "google/cloud/vision_v1p4beta1/gapic/transports/image_annotator_grpc_transport.py", - "google/cloud/vision_v1p4beta1/gapic/transports/product_search_grpc_transport.py", - "google/cloud/vision_v1p4beta1/proto/__init__.py", - "google/cloud/vision_v1p4beta1/proto/face.proto", - "google/cloud/vision_v1p4beta1/proto/face_pb2.py", - "google/cloud/vision_v1p4beta1/proto/face_pb2_grpc.py", - "google/cloud/vision_v1p4beta1/proto/geometry.proto", - "google/cloud/vision_v1p4beta1/proto/geometry_pb2.py", - "google/cloud/vision_v1p4beta1/proto/geometry_pb2_grpc.py", - "google/cloud/vision_v1p4beta1/proto/image_annotator.proto", - "google/cloud/vision_v1p4beta1/proto/image_annotator_pb2.py", - "google/cloud/vision_v1p4beta1/proto/image_annotator_pb2_grpc.py", - "google/cloud/vision_v1p4beta1/proto/product_search.proto", - "google/cloud/vision_v1p4beta1/proto/product_search_pb2.py", - "google/cloud/vision_v1p4beta1/proto/product_search_pb2_grpc.py", - "google/cloud/vision_v1p4beta1/proto/product_search_service.proto", - "google/cloud/vision_v1p4beta1/proto/product_search_service_pb2.py", - "google/cloud/vision_v1p4beta1/proto/product_search_service_pb2_grpc.py", - "google/cloud/vision_v1p4beta1/proto/text_annotation.proto", - "google/cloud/vision_v1p4beta1/proto/text_annotation_pb2.py", - "google/cloud/vision_v1p4beta1/proto/text_annotation_pb2_grpc.py", - "google/cloud/vision_v1p4beta1/proto/web_detection.proto", - "google/cloud/vision_v1p4beta1/proto/web_detection_pb2.py", - "google/cloud/vision_v1p4beta1/proto/web_detection_pb2_grpc.py", - "google/cloud/vision_v1p4beta1/types.py", - "noxfile.py", - "renovate.json", - "samples/AUTHORING_GUIDE.md", - "samples/CONTRIBUTING.md", - "samples/snippets/crop_hints/noxfile.py", - "samples/snippets/detect/noxfile.py", - "samples/snippets/document_text/noxfile.py", - "samples/snippets/face_detection/noxfile.py", - "samples/snippets/product_search/noxfile.py", - "samples/snippets/quickstart/noxfile.py", - "samples/snippets/web/noxfile.py", - "scripts/decrypt-secrets.sh", - "scripts/readme-gen/readme_gen.py", - "scripts/readme-gen/templates/README.tmpl.rst", - "scripts/readme-gen/templates/auth.tmpl.rst", - "scripts/readme-gen/templates/auth_api_key.tmpl.rst", - "scripts/readme-gen/templates/install_deps.tmpl.rst", - "scripts/readme-gen/templates/install_portaudio.tmpl.rst", - "setup.cfg", - "testing/.gitignore", - "tests/unit/gapic/v1/test_image_annotator_client_v1.py", - "tests/unit/gapic/v1/test_product_search_client_v1.py", - "tests/unit/gapic/v1p1beta1/test_image_annotator_client_v1p1beta1.py", - "tests/unit/gapic/v1p2beta1/test_image_annotator_client_v1p2beta1.py", - "tests/unit/gapic/v1p3beta1/test_image_annotator_client_v1p3beta1.py", - "tests/unit/gapic/v1p3beta1/test_product_search_client_v1p3beta1.py", - "tests/unit/gapic/v1p4beta1/test_image_annotator_client_v1p4beta1.py", - "tests/unit/gapic/v1p4beta1/test_product_search_client_v1p4beta1.py" ] } \ No newline at end of file diff --git a/synth.py b/synth.py index 2440c5c9..7ced8afa 100644 --- a/synth.py +++ b/synth.py @@ -33,62 +33,94 @@ bazel_target=f"//google/cloud/vision/{version}:vision-{version}-py", include_protos=True ) - - s.move(library / f"google/cloud/vision_{version}/gapic") - s.move(library / f"google/cloud/vision_{version}/__init__.py") - s.move(library / f"google/cloud/vision_{version}/types.py") + s.move(library / f"google/cloud/vision_{version}/proto") - s.move(library / f"tests/unit/gapic/{version}") + s.move(library / f"google/cloud/vision_{version}/services") + s.move(library / f"google/cloud/vision_{version}/types") + s.move(library / f"google/cloud/vision_{version}/__init__.py") + s.move(library / f"google/cloud/vision_{version}/py.typed") + s.move(library / f"tests/unit/gapic/vision_{version}") + + if version == "v1": + s.move(library / "google/cloud/vision") + # don't publish docs for these versions if version not in ["v1p1beta1"]: - s.move(library / f"docs/gapic/{version}") + s.move(library / f"docs/vision_{version}") # Add vision helpers to each version s.replace( f"google/cloud/vision_{version}/__init__.py", - f"from __future__ import absolute_import", - f"\g<0>\n\n" - f"from google.cloud.vision_helpers.decorators import " - f"add_single_feature_methods\n" - f"from google.cloud.vision_helpers import VisionHelpers", + "from .services.image_annotator import ImageAnnotatorClient", + "from google.cloud.vision_helpers.decorators import " + "add_single_feature_methods\n" + "from google.cloud.vision_helpers import VisionHelpers\n\n" + "from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient", ) s.replace( - f"google/cloud/vision_{version}/__init__.py", f"image_annotator_client", f"iac" + f"google/cloud/vision_{version}/__init__.py", + "__all__ = \(", + "@add_single_feature_methods\n" + "class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient):\n" + "\t__doc__ = IacImageAnnotatorClient.__doc__\n" + "\tFeature = Feature\n\n" + "__all__ = (", ) + # Temporary workaround due to bug https://github.com/googleapis/proto-plus-python/issues/135 s.replace( - f"google/cloud/vision_{version}/__init__.py", - f"from google.cloud.vision_{version}.gapic import iac", - f"from google.cloud.vision_{version}.gapic import " - f"image_annotator_client as iac", + f"google/cloud/vision_{version}/services/image_annotator/client.py", + "request = image_annotator.BatchAnnotateImagesRequest\(request\)", + "request = image_annotator.BatchAnnotateImagesRequest(request)\n" + " if requests is not None:\n" + " for i in range(len(requests)):\n" + " requests[i] = image_annotator.AnnotateImageRequest(requests[i])" ) - s.replace( - f"google/cloud/vision_{version}/__init__.py", - f"class ImageAnnotatorClient\(iac.ImageAnnotatorClient\):", - f"@add_single_feature_methods\n" - f"class ImageAnnotatorClient(VisionHelpers, iac.ImageAnnotatorClient):", + f"google/cloud/vision_{version}/services/image_annotator/client.py", + "request = image_annotator.BatchAnnotateFilesRequest\(request\)", + "request = image_annotator.BatchAnnotateFilesRequest(request)\n" + " if requests is not None:\n" + " for i in range(len(requests)):\n" + " requests[i] = image_annotator.AnnotateFileRequest(requests[i])" + ) + s.replace( + f"google/cloud/vision_{version}/services/image_annotator/client.py", + "request = image_annotator.AsyncBatchAnnotateImagesRequest\(request\)", + "request = image_annotator.AsyncBatchAnnotateImagesRequest(request)\n" + " if requests is not None:\n" + " for i in range(len(requests)):\n" + " requests[i] = image_annotator.AnnotateImageRequest(requests[i])" + ) + s.replace( + f"google/cloud/vision_{version}/services/image_annotator/client.py", + "request = image_annotator.AsyncBatchAnnotateFilesRequest\(request\)", + "request = image_annotator.AsyncBatchAnnotateFilesRequest(request)\n" + " if requests is not None:\n" + " for i in range(len(requests)):\n" + " requests[i] = image_annotator.AsyncAnnotateFileRequest(requests[i])" ) -# Move docs configuration -s.move(library / f"docs/conf.py") - -# Fix import of operations -targets = ["google/cloud/vision_*/**/*.py", "tests/system/gapic/*/**/*.py"] s.replace( - targets, - "import google.api_core.operations_v1", - "from google.api_core import operations_v1", + "google/cloud/vision/__init__.py", + "from google.cloud.vision_v1.services.image_annotator.client import ImageAnnotatorClient", + "from google.cloud.vision_v1 import ImageAnnotatorClient" ) +# Move docs configuration +s.move(library / f"docs/conf.py") + # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- templated_files = common.py_library( - samples=True, cov_level=99, system_test_external_dependencies=["google-cloud-storage"] + samples=True, + microgenerator=True, + cov_level=99, + system_test_external_dependencies=["google-cloud-storage"] ) -s.move(templated_files) +s.move(templated_files, excludes=[".coveragerc"]) # microgenerator has a good .coveragerc file # ---------------------------------------------------------------------------- # Samples templates diff --git a/tests/system.py b/tests/system.py index 839c269a..646a1420 100644 --- a/tests/system.py +++ b/tests/system.py @@ -26,6 +26,7 @@ from google.api_core import exceptions from google.cloud import storage from google.cloud import vision +from google.protobuf import field_mask_pb2 as field_mask from test_utils.retry import RetryErrors from test_utils.system import unique_resource_id @@ -141,14 +142,16 @@ def test_detect_logos_async(self): ) } }, - "features": [{"type": vision.enums.Feature.Type.LOGO_DETECTION}], + "features": [{"type_": vision.Feature.Type.LOGO_DETECTION}], } method_name = "test_detect_logos_async" output_gcs_uri_prefix = "gs://{bucket}/{method_name}".format( bucket=self.test_bucket.name, method_name=method_name ) output_config = {"gcs_destination": {"uri": output_gcs_uri_prefix}} - response = self.client.async_batch_annotate_images([request], output_config) + response = self.client.async_batch_annotate_images( + requests=[request], output_config=output_config + ) # Wait for the operation to complete. lro_waiting_seconds = 90 @@ -204,10 +207,10 @@ def test_async_batch_annotate_files(self): }, "mime_type": "application/pdf", }, - "features": [{"type": vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION}], + "features": [{"type_": vision.Feature.Type.DOCUMENT_TEXT_DETECTION}], "output_config": {"gcs_destination": {"uri": output_gcs_uri_prefix}}, } - response = self.client.async_batch_annotate_files([request]) + response = self.client.async_batch_annotate_files(requests=[request]) # Wait for the operation to complete. lro_waiting_seconds = 90 @@ -253,9 +256,7 @@ def setUp(self): self.products_to_delete = [] self.product_sets_to_delete = [] self.location = "us-west1" - self.location_path = self.ps_client.location_path( - project=PROJECT_ID, location=self.location - ) + self.location_path = f"projects/{PROJECT_ID}/locations/{self.location}" def tearDown(self): VisionSystemTestBase.tearDown(self) @@ -277,7 +278,7 @@ def _upload_image(self, image_name): def test_create_product_set(self): # Create a ProductSet. - product_set = vision.types.ProductSet(display_name="display name") + product_set = vision.ProductSet(display_name="display name") product_set_id = "set" + unique_resource_id() product_set_path = self.ps_client.product_set_path( project=PROJECT_ID, location=self.location, product_set=product_set_id @@ -293,7 +294,7 @@ def test_create_product_set(self): def test_get_product_set(self): # Create a ProductSet. - product_set = vision.types.ProductSet(display_name="display name") + product_set = vision.ProductSet(display_name="display name") product_set_id = "set" + unique_resource_id() product_set_path = self.ps_client.product_set_path( project=PROJECT_ID, location=self.location, product_set=product_set_id @@ -311,7 +312,7 @@ def test_get_product_set(self): def test_list_product_sets(self): # Create a ProductSet. - product_set = vision.types.ProductSet(display_name="display name") + product_set = vision.ProductSet(display_name="display name") product_set_id = "set" + unique_resource_id() product_set_path = self.ps_client.product_set_path( project=PROJECT_ID, location=self.location, product_set=product_set_id @@ -335,7 +336,7 @@ def test_list_product_sets(self): def test_update_product_set(self): # Create a ProductSet. - product_set = vision.types.ProductSet(display_name="display name") + product_set = vision.ProductSet(display_name="display name") product_set_id = "set" + unique_resource_id() product_set_path = self.ps_client.product_set_path( project=PROJECT_ID, location=self.location, product_set=product_set_id @@ -349,10 +350,10 @@ def test_update_product_set(self): self.assertEqual(response.name, product_set_path) # Update the ProductSet. new_display_name = "updated name" - updated_product_set_request = vision.types.ProductSet( + updated_product_set_request = vision.ProductSet( name=product_set_path, display_name=new_display_name ) - update_mask = vision.types.FieldMask(paths=["display_name"]) + update_mask = field_mask.FieldMask(paths=["display_name"]) updated_product_set = self.ps_client.update_product_set( product_set=updated_product_set_request, update_mask=update_mask ) @@ -360,7 +361,7 @@ def test_update_product_set(self): def test_create_product(self): # Create a Product. - product = vision.types.Product( + product = vision.Product( display_name="product display name", product_category="apparel" ) product_id = "product" + unique_resource_id() @@ -376,7 +377,7 @@ def test_create_product(self): def test_get_product(self): # Create a Product. - product = vision.types.Product( + product = vision.Product( display_name="product display name", product_category="apparel" ) product_id = "product" + unique_resource_id() @@ -394,7 +395,7 @@ def test_get_product(self): def test_update_product(self): # Create a Product. - product = vision.types.Product( + product = vision.Product( display_name="product display name", product_category="apparel" ) product_id = "product" + unique_resource_id() @@ -408,10 +409,10 @@ def test_update_product(self): self.assertEqual(response.name, product_path) # Update the Product. new_display_name = "updated product name" - updated_product_request = vision.types.Product( + updated_product_request = vision.Product( name=product_path, display_name=new_display_name ) - update_mask = vision.types.FieldMask(paths=["display_name"]) + update_mask = field_mask.FieldMask(paths=["display_name"]) updated_product = self.ps_client.update_product( product=updated_product_request, update_mask=update_mask ) @@ -419,7 +420,7 @@ def test_update_product(self): def test_list_products(self): # Create a Product. - product = vision.types.Product( + product = vision.Product( display_name="product display name", product_category="apparel" ) product_id = "product" + unique_resource_id() @@ -441,7 +442,7 @@ def test_list_products(self): def test_list_products_in_product_set(self): # Create a ProductSet. - product_set = vision.types.ProductSet(display_name="display name") + product_set = vision.ProductSet(display_name="display name") product_set_id = "set" + unique_resource_id() product_set_path = self.ps_client.product_set_path( project=PROJECT_ID, location=self.location, product_set=product_set_id @@ -454,7 +455,7 @@ def test_list_products_in_product_set(self): self.product_sets_to_delete.append(response.name) self.assertEqual(response.name, product_set_path) # Create a Product. - product = vision.types.Product( + product = vision.Product( display_name="product display name", product_category="apparel" ) product_id = "product" + unique_resource_id() @@ -483,7 +484,7 @@ def test_list_products_in_product_set(self): def test_reference_image(self): # Create a Product. - product = vision.types.Product( + product = vision.Product( display_name="product display name", product_category="apparel" ) product_id = "product" + unique_resource_id() @@ -507,7 +508,7 @@ def test_reference_image(self): product=product_id, reference_image=reference_image_id, ) - reference_image = vision.types.ReferenceImage(uri=gcs_uri) + reference_image = vision.ReferenceImage(uri=gcs_uri) response = self.ps_client.create_reference_image( parent=product_path, reference_image=reference_image, @@ -595,12 +596,12 @@ def test_import_product_sets(self): blob.upload_from_string(csv_data) # Make the import_product_sets request. - gcs_source = vision.types.ImportProductSetsGcsSource( + gcs_source = vision.ImportProductSetsGcsSource( csv_file_uri="gs://{bucket}/{blob}".format( bucket=self.test_bucket.name, blob=csv_filename ) ) - input_config = vision.types.ImportProductSetsInputConfig(gcs_source=gcs_source) + input_config = vision.ImportProductSetsInputConfig(gcs_source=gcs_source) response = self.ps_client.import_product_sets( parent=self.location_path, input_config=input_config ) @@ -625,8 +626,8 @@ def setUp(self): super(TestVisionClientProductSearchVpcsc, self).setUp() uniq = unique_resource_id() self.location = "us-west1" - self.location_path = self.ps_client.location_path( - project=vpcsc_config.project_outside, location=self.location + self.location_path = ( + f"projects/{vpcsc_config.project_outside}/locations/{self.location}" ) self.product_set_id = product_set_id = "set" + uniq self.product_set_path = self.ps_client.product_set_path( @@ -677,7 +678,7 @@ def test_list_product_sets_blocked(self): assert exc.value.message.startswith(_VPCSC_PROHIBITED_MESSAGE) def test_update_product_set_blocked(self): - product_set = vision.types.ProductSet(name=self.product_set_path) + product_set = vision.ProductSet(name=self.product_set_path) with pytest.raises(exceptions.PermissionDenied) as exc: self.ps_client.update_product_set(product_set=product_set) @@ -704,7 +705,7 @@ def test_delete_product_blocked(self): assert exc.value.message.startswith(_VPCSC_PROHIBITED_MESSAGE) def test_update_product_blocked(self): - product = vision.types.Product(name=self.product_path) + product = vision.Product(name=self.product_path) with pytest.raises(exceptions.PermissionDenied) as exc: self.ps_client.update_product(product=product) @@ -781,16 +782,16 @@ def setUp(self): self.gcs_read_error_message = "Error opening file: gs://" self.gcs_write_error_message = "Error writing final output to" self.location = "us-west1" - self.location_path = self.ps_client.location_path( - project=vpcsc_config.project_inside, location=self.location + self.location_path = ( + f"projects/{vpcsc_config.project_inside}/locations/{self.location}" ) def test_import_product_sets_blocked(self): # The csv file is outside the secure perimeter. - gcs_source = vision.types.ImportProductSetsGcsSource( + gcs_source = vision.ImportProductSetsGcsSource( csv_file_uri=self.gcs_uri_blocked_file ) - input_config = vision.types.ImportProductSetsInputConfig(gcs_source=gcs_source) + input_config = vision.ImportProductSetsInputConfig(gcs_source=gcs_source) with pytest.raises(exceptions.Forbidden) as exc: self.ps_client.import_product_sets( parent=self.location_path, input_config=input_config @@ -810,7 +811,7 @@ def test_async_batch_annotate_files_read_blocked(self): "gcs_source": {"uri": self.gcs_uri_blocked_file}, "mime_type": "application/pdf", }, - "features": [{"type": vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION}], + "features": [{"type_": vision.Feature.Type.DOCUMENT_TEXT_DETECTION}], "output_config": {"gcs_destination": {"uri": output_gcs_uri_prefix}}, } with pytest.raises(exceptions.Forbidden) as exc: @@ -840,7 +841,7 @@ def test_async_batch_annotate_files_write_blocked(self): }, "mime_type": "application/pdf", }, - "features": [{"type": vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION}], + "features": [{"type_": vision.Feature.Type.DOCUMENT_TEXT_DETECTION}], "output_config": {"gcs_destination": {"uri": output_gcs_uri_prefix}}, } response = self.client.async_batch_annotate_files([request]) @@ -860,7 +861,7 @@ def test_async_batch_annotate_files_write_blocked(self): def test_async_batch_annotate_images_read_blocked(self): request = { "image": {"source": {"image_uri": self.gcs_uri_blocked_file}}, - "features": [{"type": vision.enums.Feature.Type.LOGO_DETECTION}], + "features": [{"type_": vision.Feature.Type.LOGO_DETECTION}], } method_name = "test_async_batch_annotate_images_read_blocked" output_gcs_uri_prefix = "gs://{bucket}/{method_name}".format( @@ -895,7 +896,7 @@ def test_async_batch_annotate_images_read_blocked(self): def test_async_batch_annotate_images_write_blocked(self): request = { "image": {"source": {"image_uri": self.gcs_uri_blocked_file}}, - "features": [{"type": vision.enums.Feature.Type.LOGO_DETECTION}], + "features": [{"type_": vision.Feature.Type.LOGO_DETECTION}], } method_name = "test_async_batch_annotate_images_write_blocked" diff --git a/tests/unit/gapic/v1/test_image_annotator_client_v1.py b/tests/unit/gapic/v1/test_image_annotator_client_v1.py deleted file mode 100644 index d7975e51..00000000 --- a/tests/unit/gapic/v1/test_image_annotator_client_v1.py +++ /dev/null @@ -1,256 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.rpc import status_pb2 - -from google.cloud import vision_v1 -from google.cloud.vision_v1.proto import image_annotator_pb2 -from google.longrunning import operations_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestImageAnnotatorClient(object): - def test_batch_annotate_files(self): - # Setup Expected Response - expected_response = {} - expected_response = image_annotator_pb2.BatchAnnotateFilesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ImageAnnotatorClient() - - # Setup Request - requests = [] - - response = client.batch_annotate_files(requests) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = image_annotator_pb2.BatchAnnotateFilesRequest( - requests=requests - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_batch_annotate_files_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ImageAnnotatorClient() - - # Setup request - requests = [] - - with pytest.raises(CustomException): - client.batch_annotate_files(requests) - - def test_async_batch_annotate_images(self): - # Setup Expected Response - expected_response = {} - expected_response = image_annotator_pb2.AsyncBatchAnnotateImagesResponse( - **expected_response - ) - operation = operations_pb2.Operation( - name="operations/test_async_batch_annotate_images", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ImageAnnotatorClient() - - # Setup Request - requests = [] - output_config = {} - - response = client.async_batch_annotate_images(requests, output_config) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = image_annotator_pb2.AsyncBatchAnnotateImagesRequest( - requests=requests, output_config=output_config - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_async_batch_annotate_images_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_async_batch_annotate_images_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ImageAnnotatorClient() - - # Setup Request - requests = [] - output_config = {} - - response = client.async_batch_annotate_images(requests, output_config) - exception = response.exception() - assert exception.errors[0] == error - - def test_async_batch_annotate_files(self): - # Setup Expected Response - expected_response = {} - expected_response = image_annotator_pb2.AsyncBatchAnnotateFilesResponse( - **expected_response - ) - operation = operations_pb2.Operation( - name="operations/test_async_batch_annotate_files", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ImageAnnotatorClient() - - # Setup Request - requests = [] - - response = client.async_batch_annotate_files(requests) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = image_annotator_pb2.AsyncBatchAnnotateFilesRequest( - requests=requests - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_async_batch_annotate_files_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_async_batch_annotate_files_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ImageAnnotatorClient() - - # Setup Request - requests = [] - - response = client.async_batch_annotate_files(requests) - exception = response.exception() - assert exception.errors[0] == error - - def test_batch_annotate_images(self): - # Setup Expected Response - expected_response = {} - expected_response = image_annotator_pb2.BatchAnnotateImagesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ImageAnnotatorClient() - - # Setup Request - requests = [] - - response = client.batch_annotate_images(requests) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = image_annotator_pb2.BatchAnnotateImagesRequest( - requests=requests - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_batch_annotate_images_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ImageAnnotatorClient() - - # Setup request - requests = [] - - with pytest.raises(CustomException): - client.batch_annotate_images(requests) diff --git a/tests/unit/gapic/v1/test_product_search_client_v1.py b/tests/unit/gapic/v1/test_product_search_client_v1.py deleted file mode 100644 index 4326e3f3..00000000 --- a/tests/unit/gapic/v1/test_product_search_client_v1.py +++ /dev/null @@ -1,895 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.rpc import status_pb2 - -from google.cloud import vision_v1 -from google.cloud.vision_v1.proto import product_search_service_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestProductSearchClient(object): - def test_import_product_sets(self): - # Setup Expected Response - expected_response = {} - expected_response = product_search_service_pb2.ImportProductSetsResponse( - **expected_response - ) - operation = operations_pb2.Operation( - name="operations/test_import_product_sets", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - input_config = {} - - response = client.import_product_sets(parent, input_config) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.ImportProductSetsRequest( - parent=parent, input_config=input_config - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_import_product_sets_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_import_product_sets_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - input_config = {} - - response = client.import_product_sets(parent, input_config) - exception = response.exception() - assert exception.errors[0] == error - - def test_purge_products(self): - # Setup Expected Response - expected_response = {} - expected_response = empty_pb2.Empty(**expected_response) - operation = operations_pb2.Operation( - name="operations/test_purge_products", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - response = client.purge_products(parent) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.PurgeProductsRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_purge_products_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_purge_products_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - response = client.purge_products(parent) - exception = response.exception() - assert exception.errors[0] == error - - def test_create_product_set(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - expected_response = {"name": name, "display_name": display_name} - expected_response = product_search_service_pb2.ProductSet(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - product_set = {} - - response = client.create_product_set(parent, product_set) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.CreateProductSetRequest( - parent=parent, product_set=product_set - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - product_set = {} - - with pytest.raises(CustomException): - client.create_product_set(parent, product_set) - - def test_list_product_sets(self): - # Setup Expected Response - next_page_token = "" - product_sets_element = {} - product_sets = [product_sets_element] - expected_response = { - "next_page_token": next_page_token, - "product_sets": product_sets, - } - expected_response = product_search_service_pb2.ListProductSetsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_product_sets(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.product_sets[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.ListProductSetsRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_product_sets_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_product_sets(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_product_set(self): - # Setup Expected Response - name_2 = "name2-1052831874" - display_name = "displayName1615086568" - expected_response = {"name": name_2, "display_name": display_name} - expected_response = product_search_service_pb2.ProductSet(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - response = client.get_product_set(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.GetProductSetRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - with pytest.raises(CustomException): - client.get_product_set(name) - - def test_update_product_set(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - expected_response = {"name": name, "display_name": display_name} - expected_response = product_search_service_pb2.ProductSet(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - product_set = {} - - response = client.update_product_set(product_set) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.UpdateProductSetRequest( - product_set=product_set - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - product_set = {} - - with pytest.raises(CustomException): - client.update_product_set(product_set) - - def test_delete_product_set(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - client.delete_product_set(name) - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.DeleteProductSetRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - with pytest.raises(CustomException): - client.delete_product_set(name) - - def test_create_product(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - description = "description-1724546052" - product_category = "productCategory-1607451058" - expected_response = { - "name": name, - "display_name": display_name, - "description": description, - "product_category": product_category, - } - expected_response = product_search_service_pb2.Product(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - product = {} - - response = client.create_product(parent, product) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.CreateProductRequest( - parent=parent, product=product - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_product_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - product = {} - - with pytest.raises(CustomException): - client.create_product(parent, product) - - def test_list_products(self): - # Setup Expected Response - next_page_token = "" - products_element = {} - products = [products_element] - expected_response = {"next_page_token": next_page_token, "products": products} - expected_response = product_search_service_pb2.ListProductsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_products(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.products[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.ListProductsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_products_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_products(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_product(self): - # Setup Expected Response - name_2 = "name2-1052831874" - display_name = "displayName1615086568" - description = "description-1724546052" - product_category = "productCategory-1607451058" - expected_response = { - "name": name_2, - "display_name": display_name, - "description": description, - "product_category": product_category, - } - expected_response = product_search_service_pb2.Product(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - name = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - response = client.get_product(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.GetProductRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_product_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - name = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - with pytest.raises(CustomException): - client.get_product(name) - - def test_update_product(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - description = "description-1724546052" - product_category = "productCategory-1607451058" - expected_response = { - "name": name, - "display_name": display_name, - "description": description, - "product_category": product_category, - } - expected_response = product_search_service_pb2.Product(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - product = {} - - response = client.update_product(product) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.UpdateProductRequest( - product=product - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_product_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - product = {} - - with pytest.raises(CustomException): - client.update_product(product) - - def test_delete_product(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - name = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - client.delete_product(name) - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.DeleteProductRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_product_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - name = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - with pytest.raises(CustomException): - client.delete_product(name) - - def test_create_reference_image(self): - # Setup Expected Response - name = "name3373707" - uri = "uri116076" - expected_response = {"name": name, "uri": uri} - expected_response = product_search_service_pb2.ReferenceImage( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - parent = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - reference_image = {} - - response = client.create_reference_image(parent, reference_image) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.CreateReferenceImageRequest( - parent=parent, reference_image=reference_image - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_reference_image_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - parent = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - reference_image = {} - - with pytest.raises(CustomException): - client.create_reference_image(parent, reference_image) - - def test_delete_reference_image(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - name = client.reference_image_path( - "[PROJECT]", "[LOCATION]", "[PRODUCT]", "[REFERENCE_IMAGE]" - ) - - client.delete_reference_image(name) - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.DeleteReferenceImageRequest( - name=name - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_reference_image_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - name = client.reference_image_path( - "[PROJECT]", "[LOCATION]", "[PRODUCT]", "[REFERENCE_IMAGE]" - ) - - with pytest.raises(CustomException): - client.delete_reference_image(name) - - def test_list_reference_images(self): - # Setup Expected Response - page_size = 883849137 - next_page_token = "" - reference_images_element = {} - reference_images = [reference_images_element] - expected_response = { - "page_size": page_size, - "next_page_token": next_page_token, - "reference_images": reference_images, - } - expected_response = product_search_service_pb2.ListReferenceImagesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - parent = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - paged_list_response = client.list_reference_images(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.reference_images[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.ListReferenceImagesRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_reference_images_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - parent = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - paged_list_response = client.list_reference_images(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_reference_image(self): - # Setup Expected Response - name_2 = "name2-1052831874" - uri = "uri116076" - expected_response = {"name": name_2, "uri": uri} - expected_response = product_search_service_pb2.ReferenceImage( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - name = client.reference_image_path( - "[PROJECT]", "[LOCATION]", "[PRODUCT]", "[REFERENCE_IMAGE]" - ) - - response = client.get_reference_image(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.GetReferenceImageRequest( - name=name - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_reference_image_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - name = client.reference_image_path( - "[PROJECT]", "[LOCATION]", "[PRODUCT]", "[REFERENCE_IMAGE]" - ) - - with pytest.raises(CustomException): - client.get_reference_image(name) - - def test_add_product_to_product_set(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - product = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - client.add_product_to_product_set(name, product) - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.AddProductToProductSetRequest( - name=name, product=product - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_add_product_to_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - product = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - with pytest.raises(CustomException): - client.add_product_to_product_set(name, product) - - def test_remove_product_from_product_set(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - product = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - client.remove_product_from_product_set(name, product) - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.RemoveProductFromProductSetRequest( - name=name, product=product - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_remove_product_from_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - product = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - with pytest.raises(CustomException): - client.remove_product_from_product_set(name, product) - - def test_list_products_in_product_set(self): - # Setup Expected Response - next_page_token = "" - products_element = {} - products = [products_element] - expected_response = {"next_page_token": next_page_token, "products": products} - expected_response = product_search_service_pb2.ListProductsInProductSetResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup Request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - paged_list_response = client.list_products_in_product_set(name) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.products[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.ListProductsInProductSetRequest( - name=name - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_products_in_product_set_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1.ProductSearchClient() - - # Setup request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - paged_list_response = client.list_products_in_product_set(name) - with pytest.raises(CustomException): - list(paged_list_response) diff --git a/tests/unit/gapic/v1p1beta1/test_image_annotator_client_v1p1beta1.py b/tests/unit/gapic/v1p1beta1/test_image_annotator_client_v1p1beta1.py deleted file mode 100644 index 0b0b7fe0..00000000 --- a/tests/unit/gapic/v1p1beta1/test_image_annotator_client_v1p1beta1.py +++ /dev/null @@ -1,102 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.cloud import vision_v1p1beta1 -from google.cloud.vision_v1p1beta1.proto import image_annotator_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestImageAnnotatorClient(object): - def test_batch_annotate_images(self): - # Setup Expected Response - expected_response = {} - expected_response = image_annotator_pb2.BatchAnnotateImagesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p1beta1.ImageAnnotatorClient() - - # Setup Request - requests = [] - - response = client.batch_annotate_images(requests) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = image_annotator_pb2.BatchAnnotateImagesRequest( - requests=requests - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_batch_annotate_images_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p1beta1.ImageAnnotatorClient() - - # Setup request - requests = [] - - with pytest.raises(CustomException): - client.batch_annotate_images(requests) diff --git a/tests/unit/gapic/v1p2beta1/test_image_annotator_client_v1p2beta1.py b/tests/unit/gapic/v1p2beta1/test_image_annotator_client_v1p2beta1.py deleted file mode 100644 index 1c5ab408..00000000 --- a/tests/unit/gapic/v1p2beta1/test_image_annotator_client_v1p2beta1.py +++ /dev/null @@ -1,159 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.rpc import status_pb2 - -from google.cloud import vision_v1p2beta1 -from google.cloud.vision_v1p2beta1.proto import image_annotator_pb2 -from google.longrunning import operations_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestImageAnnotatorClient(object): - def test_async_batch_annotate_files(self): - # Setup Expected Response - expected_response = {} - expected_response = image_annotator_pb2.AsyncBatchAnnotateFilesResponse( - **expected_response - ) - operation = operations_pb2.Operation( - name="operations/test_async_batch_annotate_files", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p2beta1.ImageAnnotatorClient() - - # Setup Request - requests = [] - - response = client.async_batch_annotate_files(requests) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = image_annotator_pb2.AsyncBatchAnnotateFilesRequest( - requests=requests - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_async_batch_annotate_files_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_async_batch_annotate_files_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p2beta1.ImageAnnotatorClient() - - # Setup Request - requests = [] - - response = client.async_batch_annotate_files(requests) - exception = response.exception() - assert exception.errors[0] == error - - def test_batch_annotate_images(self): - # Setup Expected Response - expected_response = {} - expected_response = image_annotator_pb2.BatchAnnotateImagesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p2beta1.ImageAnnotatorClient() - - # Setup Request - requests = [] - - response = client.batch_annotate_images(requests) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = image_annotator_pb2.BatchAnnotateImagesRequest( - requests=requests - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_batch_annotate_images_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p2beta1.ImageAnnotatorClient() - - # Setup request - requests = [] - - with pytest.raises(CustomException): - client.batch_annotate_images(requests) diff --git a/tests/unit/gapic/v1p3beta1/test_image_annotator_client_v1p3beta1.py b/tests/unit/gapic/v1p3beta1/test_image_annotator_client_v1p3beta1.py deleted file mode 100644 index 2bb87588..00000000 --- a/tests/unit/gapic/v1p3beta1/test_image_annotator_client_v1p3beta1.py +++ /dev/null @@ -1,151 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.rpc import status_pb2 - -from google.cloud import vision_v1p3beta1 -from google.cloud.vision_v1p3beta1.proto import image_annotator_pb2 -from google.longrunning import operations_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestImageAnnotatorClient(object): - def test_batch_annotate_images(self): - # Setup Expected Response - expected_response = {} - expected_response = image_annotator_pb2.BatchAnnotateImagesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ImageAnnotatorClient() - - response = client.batch_annotate_images() - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = image_annotator_pb2.BatchAnnotateImagesRequest() - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_batch_annotate_images_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ImageAnnotatorClient() - - with pytest.raises(CustomException): - client.batch_annotate_images() - - def test_async_batch_annotate_files(self): - # Setup Expected Response - expected_response = {} - expected_response = image_annotator_pb2.AsyncBatchAnnotateFilesResponse( - **expected_response - ) - operation = operations_pb2.Operation( - name="operations/test_async_batch_annotate_files", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ImageAnnotatorClient() - - # Setup Request - requests = [] - - response = client.async_batch_annotate_files(requests) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = image_annotator_pb2.AsyncBatchAnnotateFilesRequest( - requests=requests - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_async_batch_annotate_files_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_async_batch_annotate_files_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ImageAnnotatorClient() - - # Setup Request - requests = [] - - response = client.async_batch_annotate_files(requests) - exception = response.exception() - assert exception.errors[0] == error diff --git a/tests/unit/gapic/v1p3beta1/test_product_search_client_v1p3beta1.py b/tests/unit/gapic/v1p3beta1/test_product_search_client_v1p3beta1.py deleted file mode 100644 index 1a38fc75..00000000 --- a/tests/unit/gapic/v1p3beta1/test_product_search_client_v1p3beta1.py +++ /dev/null @@ -1,843 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.rpc import status_pb2 - -from google.cloud import vision_v1p3beta1 -from google.cloud.vision_v1p3beta1.proto import product_search_service_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestProductSearchClient(object): - def test_import_product_sets(self): - # Setup Expected Response - expected_response = {} - expected_response = product_search_service_pb2.ImportProductSetsResponse( - **expected_response - ) - operation = operations_pb2.Operation( - name="operations/test_import_product_sets", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - input_config = {} - - response = client.import_product_sets(parent, input_config) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.ImportProductSetsRequest( - parent=parent, input_config=input_config - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_import_product_sets_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_import_product_sets_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - input_config = {} - - response = client.import_product_sets(parent, input_config) - exception = response.exception() - assert exception.errors[0] == error - - def test_create_product_set(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - expected_response = {"name": name, "display_name": display_name} - expected_response = product_search_service_pb2.ProductSet(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - product_set = {} - - response = client.create_product_set(parent, product_set) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.CreateProductSetRequest( - parent=parent, product_set=product_set - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - product_set = {} - - with pytest.raises(CustomException): - client.create_product_set(parent, product_set) - - def test_list_product_sets(self): - # Setup Expected Response - next_page_token = "" - product_sets_element = {} - product_sets = [product_sets_element] - expected_response = { - "next_page_token": next_page_token, - "product_sets": product_sets, - } - expected_response = product_search_service_pb2.ListProductSetsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_product_sets(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.product_sets[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.ListProductSetsRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_product_sets_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_product_sets(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_product_set(self): - # Setup Expected Response - name_2 = "name2-1052831874" - display_name = "displayName1615086568" - expected_response = {"name": name_2, "display_name": display_name} - expected_response = product_search_service_pb2.ProductSet(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - response = client.get_product_set(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.GetProductSetRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - with pytest.raises(CustomException): - client.get_product_set(name) - - def test_update_product_set(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - expected_response = {"name": name, "display_name": display_name} - expected_response = product_search_service_pb2.ProductSet(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - product_set = {} - - response = client.update_product_set(product_set) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.UpdateProductSetRequest( - product_set=product_set - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - product_set = {} - - with pytest.raises(CustomException): - client.update_product_set(product_set) - - def test_delete_product_set(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - client.delete_product_set(name) - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.DeleteProductSetRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - with pytest.raises(CustomException): - client.delete_product_set(name) - - def test_create_product(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - description = "description-1724546052" - product_category = "productCategory-1607451058" - expected_response = { - "name": name, - "display_name": display_name, - "description": description, - "product_category": product_category, - } - expected_response = product_search_service_pb2.Product(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - product = {} - - response = client.create_product(parent, product) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.CreateProductRequest( - parent=parent, product=product - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_product_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - product = {} - - with pytest.raises(CustomException): - client.create_product(parent, product) - - def test_list_products(self): - # Setup Expected Response - next_page_token = "" - products_element = {} - products = [products_element] - expected_response = {"next_page_token": next_page_token, "products": products} - expected_response = product_search_service_pb2.ListProductsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_products(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.products[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.ListProductsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_products_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_products(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_product(self): - # Setup Expected Response - name_2 = "name2-1052831874" - display_name = "displayName1615086568" - description = "description-1724546052" - product_category = "productCategory-1607451058" - expected_response = { - "name": name_2, - "display_name": display_name, - "description": description, - "product_category": product_category, - } - expected_response = product_search_service_pb2.Product(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - name = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - response = client.get_product(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.GetProductRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_product_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - name = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - with pytest.raises(CustomException): - client.get_product(name) - - def test_update_product(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - description = "description-1724546052" - product_category = "productCategory-1607451058" - expected_response = { - "name": name, - "display_name": display_name, - "description": description, - "product_category": product_category, - } - expected_response = product_search_service_pb2.Product(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - product = {} - - response = client.update_product(product) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.UpdateProductRequest( - product=product - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_product_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - product = {} - - with pytest.raises(CustomException): - client.update_product(product) - - def test_delete_product(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - name = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - client.delete_product(name) - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.DeleteProductRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_product_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - name = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - with pytest.raises(CustomException): - client.delete_product(name) - - def test_create_reference_image(self): - # Setup Expected Response - name = "name3373707" - uri = "uri116076" - expected_response = {"name": name, "uri": uri} - expected_response = product_search_service_pb2.ReferenceImage( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - parent = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - reference_image = {} - - response = client.create_reference_image(parent, reference_image) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.CreateReferenceImageRequest( - parent=parent, reference_image=reference_image - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_reference_image_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - parent = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - reference_image = {} - - with pytest.raises(CustomException): - client.create_reference_image(parent, reference_image) - - def test_delete_reference_image(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - name = client.reference_image_path( - "[PROJECT]", "[LOCATION]", "[PRODUCT]", "[REFERENCE_IMAGE]" - ) - - client.delete_reference_image(name) - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.DeleteReferenceImageRequest( - name=name - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_reference_image_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - name = client.reference_image_path( - "[PROJECT]", "[LOCATION]", "[PRODUCT]", "[REFERENCE_IMAGE]" - ) - - with pytest.raises(CustomException): - client.delete_reference_image(name) - - def test_list_reference_images(self): - # Setup Expected Response - page_size = 883849137 - next_page_token = "" - reference_images_element = {} - reference_images = [reference_images_element] - expected_response = { - "page_size": page_size, - "next_page_token": next_page_token, - "reference_images": reference_images, - } - expected_response = product_search_service_pb2.ListReferenceImagesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - parent = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - paged_list_response = client.list_reference_images(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.reference_images[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.ListReferenceImagesRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_reference_images_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - parent = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - paged_list_response = client.list_reference_images(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_reference_image(self): - # Setup Expected Response - name_2 = "name2-1052831874" - uri = "uri116076" - expected_response = {"name": name_2, "uri": uri} - expected_response = product_search_service_pb2.ReferenceImage( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - name = client.reference_image_path( - "[PROJECT]", "[LOCATION]", "[PRODUCT]", "[REFERENCE_IMAGE]" - ) - - response = client.get_reference_image(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.GetReferenceImageRequest( - name=name - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_reference_image_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - name = client.reference_image_path( - "[PROJECT]", "[LOCATION]", "[PRODUCT]", "[REFERENCE_IMAGE]" - ) - - with pytest.raises(CustomException): - client.get_reference_image(name) - - def test_add_product_to_product_set(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - product = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - client.add_product_to_product_set(name, product) - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.AddProductToProductSetRequest( - name=name, product=product - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_add_product_to_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - product = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - with pytest.raises(CustomException): - client.add_product_to_product_set(name, product) - - def test_remove_product_from_product_set(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - product = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - client.remove_product_from_product_set(name, product) - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.RemoveProductFromProductSetRequest( - name=name, product=product - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_remove_product_from_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - product = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - with pytest.raises(CustomException): - client.remove_product_from_product_set(name, product) - - def test_list_products_in_product_set(self): - # Setup Expected Response - next_page_token = "" - products_element = {} - products = [products_element] - expected_response = {"next_page_token": next_page_token, "products": products} - expected_response = product_search_service_pb2.ListProductsInProductSetResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup Request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - paged_list_response = client.list_products_in_product_set(name) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.products[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.ListProductsInProductSetRequest( - name=name - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_products_in_product_set_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p3beta1.ProductSearchClient() - - # Setup request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - paged_list_response = client.list_products_in_product_set(name) - with pytest.raises(CustomException): - list(paged_list_response) diff --git a/tests/unit/gapic/v1p4beta1/test_image_annotator_client_v1p4beta1.py b/tests/unit/gapic/v1p4beta1/test_image_annotator_client_v1p4beta1.py deleted file mode 100644 index 880665d7..00000000 --- a/tests/unit/gapic/v1p4beta1/test_image_annotator_client_v1p4beta1.py +++ /dev/null @@ -1,256 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.rpc import status_pb2 - -from google.cloud import vision_v1p4beta1 -from google.cloud.vision_v1p4beta1.proto import image_annotator_pb2 -from google.longrunning import operations_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestImageAnnotatorClient(object): - def test_async_batch_annotate_images(self): - # Setup Expected Response - expected_response = {} - expected_response = image_annotator_pb2.AsyncBatchAnnotateImagesResponse( - **expected_response - ) - operation = operations_pb2.Operation( - name="operations/test_async_batch_annotate_images", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ImageAnnotatorClient() - - # Setup Request - requests = [] - output_config = {} - - response = client.async_batch_annotate_images(requests, output_config) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = image_annotator_pb2.AsyncBatchAnnotateImagesRequest( - requests=requests, output_config=output_config - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_async_batch_annotate_images_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_async_batch_annotate_images_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ImageAnnotatorClient() - - # Setup Request - requests = [] - output_config = {} - - response = client.async_batch_annotate_images(requests, output_config) - exception = response.exception() - assert exception.errors[0] == error - - def test_async_batch_annotate_files(self): - # Setup Expected Response - expected_response = {} - expected_response = image_annotator_pb2.AsyncBatchAnnotateFilesResponse( - **expected_response - ) - operation = operations_pb2.Operation( - name="operations/test_async_batch_annotate_files", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ImageAnnotatorClient() - - # Setup Request - requests = [] - - response = client.async_batch_annotate_files(requests) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = image_annotator_pb2.AsyncBatchAnnotateFilesRequest( - requests=requests - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_async_batch_annotate_files_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_async_batch_annotate_files_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ImageAnnotatorClient() - - # Setup Request - requests = [] - - response = client.async_batch_annotate_files(requests) - exception = response.exception() - assert exception.errors[0] == error - - def test_batch_annotate_images(self): - # Setup Expected Response - expected_response = {} - expected_response = image_annotator_pb2.BatchAnnotateImagesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ImageAnnotatorClient() - - # Setup Request - requests = [] - - response = client.batch_annotate_images(requests) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = image_annotator_pb2.BatchAnnotateImagesRequest( - requests=requests - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_batch_annotate_images_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ImageAnnotatorClient() - - # Setup request - requests = [] - - with pytest.raises(CustomException): - client.batch_annotate_images(requests) - - def test_batch_annotate_files(self): - # Setup Expected Response - expected_response = {} - expected_response = image_annotator_pb2.BatchAnnotateFilesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ImageAnnotatorClient() - - # Setup Request - requests = [] - - response = client.batch_annotate_files(requests) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = image_annotator_pb2.BatchAnnotateFilesRequest( - requests=requests - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_batch_annotate_files_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ImageAnnotatorClient() - - # Setup request - requests = [] - - with pytest.raises(CustomException): - client.batch_annotate_files(requests) diff --git a/tests/unit/gapic/v1p4beta1/test_product_search_client_v1p4beta1.py b/tests/unit/gapic/v1p4beta1/test_product_search_client_v1p4beta1.py deleted file mode 100644 index b7a2c4d5..00000000 --- a/tests/unit/gapic/v1p4beta1/test_product_search_client_v1p4beta1.py +++ /dev/null @@ -1,895 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Unit tests.""" - -import mock -import pytest - -from google.rpc import status_pb2 - -from google.cloud import vision_v1p4beta1 -from google.cloud.vision_v1p4beta1.proto import product_search_service_pb2 -from google.longrunning import operations_pb2 -from google.protobuf import empty_pb2 - - -class MultiCallableStub(object): - """Stub for the grpc.UnaryUnaryMultiCallable interface.""" - - def __init__(self, method, channel_stub): - self.method = method - self.channel_stub = channel_stub - - def __call__(self, request, timeout=None, metadata=None, credentials=None): - self.channel_stub.requests.append((self.method, request)) - - response = None - if self.channel_stub.responses: - response = self.channel_stub.responses.pop() - - if isinstance(response, Exception): - raise response - - if response: - return response - - -class ChannelStub(object): - """Stub for the grpc.Channel interface.""" - - def __init__(self, responses=[]): - self.responses = responses - self.requests = [] - - def unary_unary(self, method, request_serializer=None, response_deserializer=None): - return MultiCallableStub(method, self) - - -class CustomException(Exception): - pass - - -class TestProductSearchClient(object): - def test_import_product_sets(self): - # Setup Expected Response - expected_response = {} - expected_response = product_search_service_pb2.ImportProductSetsResponse( - **expected_response - ) - operation = operations_pb2.Operation( - name="operations/test_import_product_sets", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - input_config = {} - - response = client.import_product_sets(parent, input_config) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.ImportProductSetsRequest( - parent=parent, input_config=input_config - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_import_product_sets_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_import_product_sets_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - input_config = {} - - response = client.import_product_sets(parent, input_config) - exception = response.exception() - assert exception.errors[0] == error - - def test_create_product_set(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - expected_response = {"name": name, "display_name": display_name} - expected_response = product_search_service_pb2.ProductSet(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - product_set = {} - - response = client.create_product_set(parent, product_set) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.CreateProductSetRequest( - parent=parent, product_set=product_set - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - product_set = {} - - with pytest.raises(CustomException): - client.create_product_set(parent, product_set) - - def test_list_product_sets(self): - # Setup Expected Response - next_page_token = "" - product_sets_element = {} - product_sets = [product_sets_element] - expected_response = { - "next_page_token": next_page_token, - "product_sets": product_sets, - } - expected_response = product_search_service_pb2.ListProductSetsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_product_sets(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.product_sets[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.ListProductSetsRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_product_sets_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_product_sets(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_product_set(self): - # Setup Expected Response - name_2 = "name2-1052831874" - display_name = "displayName1615086568" - expected_response = {"name": name_2, "display_name": display_name} - expected_response = product_search_service_pb2.ProductSet(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - response = client.get_product_set(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.GetProductSetRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - with pytest.raises(CustomException): - client.get_product_set(name) - - def test_update_product_set(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - expected_response = {"name": name, "display_name": display_name} - expected_response = product_search_service_pb2.ProductSet(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - product_set = {} - - response = client.update_product_set(product_set) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.UpdateProductSetRequest( - product_set=product_set - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - product_set = {} - - with pytest.raises(CustomException): - client.update_product_set(product_set) - - def test_delete_product_set(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - client.delete_product_set(name) - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.DeleteProductSetRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - with pytest.raises(CustomException): - client.delete_product_set(name) - - def test_create_product(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - description = "description-1724546052" - product_category = "productCategory-1607451058" - expected_response = { - "name": name, - "display_name": display_name, - "description": description, - "product_category": product_category, - } - expected_response = product_search_service_pb2.Product(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - product = {} - - response = client.create_product(parent, product) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.CreateProductRequest( - parent=parent, product=product - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_product_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - product = {} - - with pytest.raises(CustomException): - client.create_product(parent, product) - - def test_list_products(self): - # Setup Expected Response - next_page_token = "" - products_element = {} - products = [products_element] - expected_response = {"next_page_token": next_page_token, "products": products} - expected_response = product_search_service_pb2.ListProductsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_products(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.products[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.ListProductsRequest(parent=parent) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_products_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - paged_list_response = client.list_products(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_product(self): - # Setup Expected Response - name_2 = "name2-1052831874" - display_name = "displayName1615086568" - description = "description-1724546052" - product_category = "productCategory-1607451058" - expected_response = { - "name": name_2, - "display_name": display_name, - "description": description, - "product_category": product_category, - } - expected_response = product_search_service_pb2.Product(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - name = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - response = client.get_product(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.GetProductRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_product_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - name = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - with pytest.raises(CustomException): - client.get_product(name) - - def test_update_product(self): - # Setup Expected Response - name = "name3373707" - display_name = "displayName1615086568" - description = "description-1724546052" - product_category = "productCategory-1607451058" - expected_response = { - "name": name, - "display_name": display_name, - "description": description, - "product_category": product_category, - } - expected_response = product_search_service_pb2.Product(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - product = {} - - response = client.update_product(product) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.UpdateProductRequest( - product=product - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_update_product_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - product = {} - - with pytest.raises(CustomException): - client.update_product(product) - - def test_delete_product(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - name = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - client.delete_product(name) - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.DeleteProductRequest(name=name) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_product_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - name = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - with pytest.raises(CustomException): - client.delete_product(name) - - def test_create_reference_image(self): - # Setup Expected Response - name = "name3373707" - uri = "uri116076" - expected_response = {"name": name, "uri": uri} - expected_response = product_search_service_pb2.ReferenceImage( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - parent = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - reference_image = {} - - response = client.create_reference_image(parent, reference_image) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.CreateReferenceImageRequest( - parent=parent, reference_image=reference_image - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_create_reference_image_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - parent = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - reference_image = {} - - with pytest.raises(CustomException): - client.create_reference_image(parent, reference_image) - - def test_delete_reference_image(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - name = client.reference_image_path( - "[PROJECT]", "[LOCATION]", "[PRODUCT]", "[REFERENCE_IMAGE]" - ) - - client.delete_reference_image(name) - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.DeleteReferenceImageRequest( - name=name - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_delete_reference_image_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - name = client.reference_image_path( - "[PROJECT]", "[LOCATION]", "[PRODUCT]", "[REFERENCE_IMAGE]" - ) - - with pytest.raises(CustomException): - client.delete_reference_image(name) - - def test_list_reference_images(self): - # Setup Expected Response - page_size = 883849137 - next_page_token = "" - reference_images_element = {} - reference_images = [reference_images_element] - expected_response = { - "page_size": page_size, - "next_page_token": next_page_token, - "reference_images": reference_images, - } - expected_response = product_search_service_pb2.ListReferenceImagesResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - parent = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - paged_list_response = client.list_reference_images(parent) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.reference_images[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.ListReferenceImagesRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_reference_images_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - parent = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - paged_list_response = client.list_reference_images(parent) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_get_reference_image(self): - # Setup Expected Response - name_2 = "name2-1052831874" - uri = "uri116076" - expected_response = {"name": name_2, "uri": uri} - expected_response = product_search_service_pb2.ReferenceImage( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - name = client.reference_image_path( - "[PROJECT]", "[LOCATION]", "[PRODUCT]", "[REFERENCE_IMAGE]" - ) - - response = client.get_reference_image(name) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.GetReferenceImageRequest( - name=name - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_reference_image_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - name = client.reference_image_path( - "[PROJECT]", "[LOCATION]", "[PRODUCT]", "[REFERENCE_IMAGE]" - ) - - with pytest.raises(CustomException): - client.get_reference_image(name) - - def test_add_product_to_product_set(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - product = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - client.add_product_to_product_set(name, product) - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.AddProductToProductSetRequest( - name=name, product=product - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_add_product_to_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - product = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - with pytest.raises(CustomException): - client.add_product_to_product_set(name, product) - - def test_remove_product_from_product_set(self): - channel = ChannelStub() - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - product = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - client.remove_product_from_product_set(name, product) - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.RemoveProductFromProductSetRequest( - name=name, product=product - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_remove_product_from_product_set_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - product = client.product_path("[PROJECT]", "[LOCATION]", "[PRODUCT]") - - with pytest.raises(CustomException): - client.remove_product_from_product_set(name, product) - - def test_list_products_in_product_set(self): - # Setup Expected Response - next_page_token = "" - products_element = {} - products = [products_element] - expected_response = {"next_page_token": next_page_token, "products": products} - expected_response = product_search_service_pb2.ListProductsInProductSetResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - paged_list_response = client.list_products_in_product_set(name) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.products[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.ListProductsInProductSetRequest( - name=name - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_list_products_in_product_set_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup request - name = client.product_set_path("[PROJECT]", "[LOCATION]", "[PRODUCT_SET]") - - paged_list_response = client.list_products_in_product_set(name) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_purge_products(self): - # Setup Expected Response - expected_response = {} - expected_response = empty_pb2.Empty(**expected_response) - operation = operations_pb2.Operation( - name="operations/test_purge_products", done=True - ) - operation.response.Pack(expected_response) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - response = client.purge_products(parent) - result = response.result() - assert expected_response == result - - assert len(channel.requests) == 1 - expected_request = product_search_service_pb2.PurgeProductsRequest( - parent=parent - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_purge_products_exception(self): - # Setup Response - error = status_pb2.Status() - operation = operations_pb2.Operation( - name="operations/test_purge_products_exception", done=True - ) - operation.error.CopyFrom(error) - - # Mock the API response - channel = ChannelStub(responses=[operation]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = vision_v1p4beta1.ProductSearchClient() - - # Setup Request - parent = client.location_path("[PROJECT]", "[LOCATION]") - - response = client.purge_products(parent) - exception = response.exception() - assert exception.errors[0] == error diff --git a/tests/unit/gapic/vision_v1/__init__.py b/tests/unit/gapic/vision_v1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/vision_v1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/vision_v1/test_image_annotator.py b/tests/unit/gapic/vision_v1/test_image_annotator.py new file mode 100644 index 00000000..908a6726 --- /dev/null +++ b/tests/unit/gapic/vision_v1/test_image_annotator.py @@ -0,0 +1,1510 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.vision_v1.services.image_annotator import ImageAnnotatorAsyncClient +from google.cloud.vision_v1.services.image_annotator import ImageAnnotatorClient +from google.cloud.vision_v1.services.image_annotator import transports +from google.cloud.vision_v1.types import geometry +from google.cloud.vision_v1.types import image_annotator +from google.cloud.vision_v1.types import product_search +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.type import latlng_pb2 as latlng # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ImageAnnotatorClient._get_default_mtls_endpoint(None) is None + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient] +) +def test_image_annotator_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "vision.googleapis.com:443" + + +def test_image_annotator_client_get_transport_class(): + transport = ImageAnnotatorClient.get_transport_class() + assert transport == transports.ImageAnnotatorGrpcTransport + + transport = ImageAnnotatorClient.get_transport_class("grpc") + assert transport == transports.ImageAnnotatorGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + ImageAnnotatorClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorClient), +) +@mock.patch.object( + ImageAnnotatorAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorAsyncClient), +) +def test_image_annotator_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "true"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "false"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + ImageAnnotatorClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorClient), +) +@mock.patch.object( + ImageAnnotatorAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_image_annotator_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_image_annotator_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_image_annotator_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_image_annotator_client_client_options_from_dict(): + with mock.patch( + "google.cloud.vision_v1.services.image_annotator.transports.ImageAnnotatorGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ImageAnnotatorClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_batch_annotate_images( + transport: str = "grpc", request_type=image_annotator.BatchAnnotateImagesRequest +): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateImagesResponse() + + response = client.batch_annotate_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == image_annotator.BatchAnnotateImagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, image_annotator.BatchAnnotateImagesResponse) + + +def test_batch_annotate_images_from_dict(): + test_batch_annotate_images(request_type=dict) + + +@pytest.mark.asyncio +async def test_batch_annotate_images_async(transport: str = "grpc_asyncio"): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = image_annotator.BatchAnnotateImagesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + image_annotator.BatchAnnotateImagesResponse() + ) + + response = await client.batch_annotate_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, image_annotator.BatchAnnotateImagesResponse) + + +def test_batch_annotate_images_flattened(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateImagesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_annotate_images( + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ] + + +def test_batch_annotate_images_flattened_error(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_annotate_images( + image_annotator.BatchAnnotateImagesRequest(), + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + +@pytest.mark.asyncio +async def test_batch_annotate_images_flattened_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateImagesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + image_annotator.BatchAnnotateImagesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_annotate_images( + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ] + + +@pytest.mark.asyncio +async def test_batch_annotate_images_flattened_error_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_annotate_images( + image_annotator.BatchAnnotateImagesRequest(), + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + +def test_batch_annotate_files( + transport: str = "grpc", request_type=image_annotator.BatchAnnotateFilesRequest +): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateFilesResponse() + + response = client.batch_annotate_files(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == image_annotator.BatchAnnotateFilesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, image_annotator.BatchAnnotateFilesResponse) + + +def test_batch_annotate_files_from_dict(): + test_batch_annotate_files(request_type=dict) + + +@pytest.mark.asyncio +async def test_batch_annotate_files_async(transport: str = "grpc_asyncio"): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = image_annotator.BatchAnnotateFilesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + image_annotator.BatchAnnotateFilesResponse() + ) + + response = await client.batch_annotate_files(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, image_annotator.BatchAnnotateFilesResponse) + + +def test_batch_annotate_files_flattened(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateFilesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_annotate_files( + requests=[ + image_annotator.AnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ] + + +def test_batch_annotate_files_flattened_error(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_annotate_files( + image_annotator.BatchAnnotateFilesRequest(), + requests=[ + image_annotator.AnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + +@pytest.mark.asyncio +async def test_batch_annotate_files_flattened_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateFilesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + image_annotator.BatchAnnotateFilesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_annotate_files( + requests=[ + image_annotator.AnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ] + + +@pytest.mark.asyncio +async def test_batch_annotate_files_flattened_error_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_annotate_files( + image_annotator.BatchAnnotateFilesRequest(), + requests=[ + image_annotator.AnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + +def test_async_batch_annotate_images( + transport: str = "grpc", + request_type=image_annotator.AsyncBatchAnnotateImagesRequest, +): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.async_batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.async_batch_annotate_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == image_annotator.AsyncBatchAnnotateImagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_async_batch_annotate_images_from_dict(): + test_async_batch_annotate_images(request_type=dict) + + +@pytest.mark.asyncio +async def test_async_batch_annotate_images_async(transport: str = "grpc_asyncio"): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = image_annotator.AsyncBatchAnnotateImagesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.async_batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.async_batch_annotate_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_async_batch_annotate_images_flattened(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.async_batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.async_batch_annotate_images( + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + output_config=image_annotator.OutputConfig( + gcs_destination=image_annotator.GcsDestination(uri="uri_value") + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ] + + assert args[0].output_config == image_annotator.OutputConfig( + gcs_destination=image_annotator.GcsDestination(uri="uri_value") + ) + + +def test_async_batch_annotate_images_flattened_error(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.async_batch_annotate_images( + image_annotator.AsyncBatchAnnotateImagesRequest(), + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + output_config=image_annotator.OutputConfig( + gcs_destination=image_annotator.GcsDestination(uri="uri_value") + ), + ) + + +@pytest.mark.asyncio +async def test_async_batch_annotate_images_flattened_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.async_batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.async_batch_annotate_images( + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + output_config=image_annotator.OutputConfig( + gcs_destination=image_annotator.GcsDestination(uri="uri_value") + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ] + + assert args[0].output_config == image_annotator.OutputConfig( + gcs_destination=image_annotator.GcsDestination(uri="uri_value") + ) + + +@pytest.mark.asyncio +async def test_async_batch_annotate_images_flattened_error_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.async_batch_annotate_images( + image_annotator.AsyncBatchAnnotateImagesRequest(), + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + output_config=image_annotator.OutputConfig( + gcs_destination=image_annotator.GcsDestination(uri="uri_value") + ), + ) + + +def test_async_batch_annotate_files( + transport: str = "grpc", request_type=image_annotator.AsyncBatchAnnotateFilesRequest +): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.async_batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.async_batch_annotate_files(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == image_annotator.AsyncBatchAnnotateFilesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_async_batch_annotate_files_from_dict(): + test_async_batch_annotate_files(request_type=dict) + + +@pytest.mark.asyncio +async def test_async_batch_annotate_files_async(transport: str = "grpc_asyncio"): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = image_annotator.AsyncBatchAnnotateFilesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.async_batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.async_batch_annotate_files(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_async_batch_annotate_files_flattened(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.async_batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.async_batch_annotate_files( + requests=[ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ] + + +def test_async_batch_annotate_files_flattened_error(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.async_batch_annotate_files( + image_annotator.AsyncBatchAnnotateFilesRequest(), + requests=[ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + +@pytest.mark.asyncio +async def test_async_batch_annotate_files_flattened_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.async_batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.async_batch_annotate_files( + requests=[ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ] + + +@pytest.mark.asyncio +async def test_async_batch_annotate_files_flattened_error_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.async_batch_annotate_files( + image_annotator.AsyncBatchAnnotateFilesRequest(), + requests=[ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageAnnotatorClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageAnnotatorClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = ImageAnnotatorClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ImageAnnotatorGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.ImageAnnotatorGrpcTransport,) + + +def test_image_annotator_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.ImageAnnotatorTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_image_annotator_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.vision_v1.services.image_annotator.transports.ImageAnnotatorTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ImageAnnotatorTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "batch_annotate_images", + "batch_annotate_files", + "async_batch_annotate_images", + "async_batch_annotate_files", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_image_annotator_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.vision_v1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ImageAnnotatorTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +def test_image_annotator_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.vision_v1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ImageAnnotatorTransport() + adc.assert_called_once() + + +def test_image_annotator_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + ImageAnnotatorClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id=None, + ) + + +def test_image_annotator_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.ImageAnnotatorGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +def test_image_annotator_host_no_port(): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vision.googleapis.com" + ), + ) + assert client._transport._host == "vision.googleapis.com:443" + + +def test_image_annotator_host_with_port(): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vision.googleapis.com:8000" + ), + ) + assert client._transport._host == "vision.googleapis.com:8000" + + +def test_image_annotator_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ImageAnnotatorGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +def test_image_annotator_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ImageAnnotatorGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +def test_image_annotator_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +def test_image_annotator_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_image_annotator_grpc_lro_client(): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + transport = client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_image_annotator_grpc_lro_async_client(): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + transport = client._client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.ImageAnnotatorTransport, "_prep_wrapped_messages" + ) as prep: + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ImageAnnotatorTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ImageAnnotatorClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/vision_v1/test_product_search.py b/tests/unit/gapic/vision_v1/test_product_search.py new file mode 100644 index 00000000..2d15b41f --- /dev/null +++ b/tests/unit/gapic/vision_v1/test_product_search.py @@ -0,0 +1,5488 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.vision_v1.services.product_search import ProductSearchAsyncClient +from google.cloud.vision_v1.services.product_search import ProductSearchClient +from google.cloud.vision_v1.services.product_search import pagers +from google.cloud.vision_v1.services.product_search import transports +from google.cloud.vision_v1.types import geometry +from google.cloud.vision_v1.types import product_search_service +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 as gp_any # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ProductSearchClient._get_default_mtls_endpoint(None) is None + assert ( + ProductSearchClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + ProductSearchClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ProductSearchClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ProductSearchClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ProductSearchClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [ProductSearchClient, ProductSearchAsyncClient] +) +def test_product_search_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "vision.googleapis.com:443" + + +def test_product_search_client_get_transport_class(): + transport = ProductSearchClient.get_transport_class() + assert transport == transports.ProductSearchGrpcTransport + + transport = ProductSearchClient.get_transport_class("grpc") + assert transport == transports.ProductSearchGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), + ( + ProductSearchAsyncClient, + transports.ProductSearchGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + ProductSearchClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ProductSearchClient), +) +@mock.patch.object( + ProductSearchAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ProductSearchAsyncClient), +) +def test_product_search_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ProductSearchClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(ProductSearchClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "true"), + ( + ProductSearchAsyncClient, + transports.ProductSearchGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "false"), + ( + ProductSearchAsyncClient, + transports.ProductSearchGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + ProductSearchClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ProductSearchClient), +) +@mock.patch.object( + ProductSearchAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ProductSearchAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_product_search_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), + ( + ProductSearchAsyncClient, + transports.ProductSearchGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_product_search_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), + ( + ProductSearchAsyncClient, + transports.ProductSearchGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_product_search_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_product_search_client_client_options_from_dict(): + with mock.patch( + "google.cloud.vision_v1.services.product_search.transports.ProductSearchGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ProductSearchClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_create_product_set( + transport: str = "grpc", request_type=product_search_service.CreateProductSetRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + + response = client.create_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.CreateProductSetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_create_product_set_from_dict(): + test_create_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.CreateProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + ) + + response = await client.create_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_create_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateProductSetRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_product_set), "__call__" + ) as call: + call.return_value = product_search_service.ProductSet() + + client.create_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateProductSetRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + + await client.create_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_product_set( + parent="parent_value", + product_set=product_search_service.ProductSet(name="name_value"), + product_set_id="product_set_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].product_set == product_search_service.ProductSet( + name="name_value" + ) + + assert args[0].product_set_id == "product_set_id_value" + + +def test_create_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_product_set( + product_search_service.CreateProductSetRequest(), + parent="parent_value", + product_set=product_search_service.ProductSet(name="name_value"), + product_set_id="product_set_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_product_set( + parent="parent_value", + product_set=product_search_service.ProductSet(name="name_value"), + product_set_id="product_set_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].product_set == product_search_service.ProductSet( + name="name_value" + ) + + assert args[0].product_set_id == "product_set_id_value" + + +@pytest.mark.asyncio +async def test_create_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_product_set( + product_search_service.CreateProductSetRequest(), + parent="parent_value", + product_set=product_search_service.ProductSet(name="name_value"), + product_set_id="product_set_id_value", + ) + + +def test_list_product_sets( + transport: str = "grpc", request_type=product_search_service.ListProductSetsRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductSetsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.ListProductSetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductSetsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_product_sets_from_dict(): + test_list_product_sets(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_product_sets_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.ListProductSetsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductSetsResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductSetsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_product_sets_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductSetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_product_sets), "__call__" + ) as call: + call.return_value = product_search_service.ListProductSetsResponse() + + client.list_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_product_sets_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductSetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_product_sets), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductSetsResponse() + ) + + await client.list_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_product_sets_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductSetsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_product_sets(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_product_sets_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_product_sets( + product_search_service.ListProductSetsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_product_sets_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductSetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductSetsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_product_sets(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_product_sets_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_product_sets( + product_search_service.ListProductSetsRequest(), parent="parent_value", + ) + + +def test_list_product_sets_pager(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_product_sets), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + next_page_token="abc", + ), + product_search_service.ListProductSetsResponse( + product_sets=[], next_page_token="def", + ), + product_search_service.ListProductSetsResponse( + product_sets=[product_search_service.ProductSet(),], + next_page_token="ghi", + ), + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_product_sets(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, product_search_service.ProductSet) for i in results) + + +def test_list_product_sets_pages(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_product_sets), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + next_page_token="abc", + ), + product_search_service.ListProductSetsResponse( + product_sets=[], next_page_token="def", + ), + product_search_service.ListProductSetsResponse( + product_sets=[product_search_service.ProductSet(),], + next_page_token="ghi", + ), + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + ), + RuntimeError, + ) + pages = list(client.list_product_sets(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_product_sets_async_pager(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_product_sets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + next_page_token="abc", + ), + product_search_service.ListProductSetsResponse( + product_sets=[], next_page_token="def", + ), + product_search_service.ListProductSetsResponse( + product_sets=[product_search_service.ProductSet(),], + next_page_token="ghi", + ), + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_product_sets(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, product_search_service.ProductSet) for i in responses) + + +@pytest.mark.asyncio +async def test_list_product_sets_async_pages(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_product_sets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + next_page_token="abc", + ), + product_search_service.ListProductSetsResponse( + product_sets=[], next_page_token="def", + ), + product_search_service.ListProductSetsResponse( + product_sets=[product_search_service.ProductSet(),], + next_page_token="ghi", + ), + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_product_sets(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_product_set( + transport: str = "grpc", request_type=product_search_service.GetProductSetRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product_set), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + + response = client.get_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.GetProductSetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_get_product_set_from_dict(): + test_get_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.GetProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + ) + + response = await client.get_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_get_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product_set), "__call__") as call: + call.return_value = product_search_service.ProductSet() + + client.get_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + + await client.get_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product_set), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_product_set( + product_search_service.GetProductSetRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_product_set( + product_search_service.GetProductSetRequest(), name="name_value", + ) + + +def test_update_product_set( + transport: str = "grpc", request_type=product_search_service.UpdateProductSetRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.update_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + + response = client.update_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.UpdateProductSetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_update_product_set_from_dict(): + test_update_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.UpdateProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + ) + + response = await client.update_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_update_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.UpdateProductSetRequest() + request.product_set.name = "product_set.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.update_product_set), "__call__" + ) as call: + call.return_value = product_search_service.ProductSet() + + client.update_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "product_set.name=product_set.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.UpdateProductSetRequest() + request.product_set.name = "product_set.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + + await client.update_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "product_set.name=product_set.name/value",) in kw[ + "metadata" + ] + + +def test_update_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.update_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_product_set( + product_set=product_search_service.ProductSet(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].product_set == product_search_service.ProductSet( + name="name_value" + ) + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_product_set( + product_search_service.UpdateProductSetRequest(), + product_set=product_search_service.ProductSet(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_product_set( + product_set=product_search_service.ProductSet(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].product_set == product_search_service.ProductSet( + name="name_value" + ) + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_product_set( + product_search_service.UpdateProductSetRequest(), + product_set=product_search_service.ProductSet(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_product_set( + transport: str = "grpc", request_type=product_search_service.DeleteProductSetRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.DeleteProductSetRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_set_from_dict(): + test_delete_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.DeleteProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_product_set), "__call__" + ) as call: + call.return_value = None + + client.delete_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_product_set( + product_search_service.DeleteProductSetRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_product_set( + product_search_service.DeleteProductSetRequest(), name="name_value", + ) + + +def test_create_product( + transport: str = "grpc", request_type=product_search_service.CreateProductRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + + response = client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_create_product_from_dict(): + test_create_product(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_product_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.CreateProductRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + ) + + response = await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_create_product_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateProductRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_product), "__call__") as call: + call.return_value = product_search_service.Product() + + client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_product_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateProductRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + + await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_product_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_product( + parent="parent_value", + product=product_search_service.Product(name="name_value"), + product_id="product_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].product == product_search_service.Product(name="name_value") + + assert args[0].product_id == "product_id_value" + + +def test_create_product_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_product( + product_search_service.CreateProductRequest(), + parent="parent_value", + product=product_search_service.Product(name="name_value"), + product_id="product_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_product_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_product( + parent="parent_value", + product=product_search_service.Product(name="name_value"), + product_id="product_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].product == product_search_service.Product(name="name_value") + + assert args[0].product_id == "product_id_value" + + +@pytest.mark.asyncio +async def test_create_product_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_product( + product_search_service.CreateProductRequest(), + parent="parent_value", + product=product_search_service.Product(name="name_value"), + product_id="product_id_value", + ) + + +def test_list_products( + transport: str = "grpc", request_type=product_search_service.ListProductsRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_products_from_dict(): + test_list_products(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_products_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.ListProductsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_products_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_products), "__call__") as call: + call.return_value = product_search_service.ListProductsResponse() + + client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_products_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsResponse() + ) + + await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_products_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_products(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_products_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_products( + product_search_service.ListProductsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_products_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_products(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_products_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_products( + product_search_service.ListProductsRequest(), parent="parent_value", + ) + + +def test_list_products_pager(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_products), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_products(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, product_search_service.Product) for i in results) + + +def test_list_products_pages(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_products), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + pages = list(client.list_products(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_products_async_pager(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_products(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, product_search_service.Product) for i in responses) + + +@pytest.mark.asyncio +async def test_list_products_async_pages(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_products(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_product( + transport: str = "grpc", request_type=product_search_service.GetProductRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + + response = client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_get_product_from_dict(): + test_get_product(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_product_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.GetProductRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + ) + + response = await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_get_product_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetProductRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product), "__call__") as call: + call.return_value = product_search_service.Product() + + client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_product_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetProductRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + + await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_product_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_product(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_product_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_product( + product_search_service.GetProductRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_product_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_product(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_product_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_product( + product_search_service.GetProductRequest(), name="name_value", + ) + + +def test_update_product( + transport: str = "grpc", request_type=product_search_service.UpdateProductRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + + response = client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_update_product_from_dict(): + test_update_product(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_product_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.UpdateProductRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + ) + + response = await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_update_product_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.UpdateProductRequest() + request.product.name = "product.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_product), "__call__") as call: + call.return_value = product_search_service.Product() + + client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "product.name=product.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_product_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.UpdateProductRequest() + request.product.name = "product.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + + await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "product.name=product.name/value",) in kw[ + "metadata" + ] + + +def test_update_product_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_product( + product=product_search_service.Product(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].product == product_search_service.Product(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_product_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_product( + product_search_service.UpdateProductRequest(), + product=product_search_service.Product(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_product_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_product( + product=product_search_service.Product(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].product == product_search_service.Product(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_product_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_product( + product_search_service.UpdateProductRequest(), + product=product_search_service.Product(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_product( + transport: str = "grpc", request_type=product_search_service.DeleteProductRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_from_dict(): + test_delete_product(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_product_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.DeleteProductRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteProductRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_product), "__call__") as call: + call.return_value = None + + client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_product_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteProductRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_product_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_product(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_product_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_product( + product_search_service.DeleteProductRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_product_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_product(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_product_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_product( + product_search_service.DeleteProductRequest(), name="name_value", + ) + + +def test_create_reference_image( + transport: str = "grpc", + request_type=product_search_service.CreateReferenceImageRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage( + name="name_value", uri="uri_value", + ) + + response = client.create_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.CreateReferenceImageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ReferenceImage) + + assert response.name == "name_value" + + assert response.uri == "uri_value" + + +def test_create_reference_image_from_dict(): + test_create_reference_image(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_reference_image_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.CreateReferenceImageRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage(name="name_value", uri="uri_value",) + ) + + response = await client.create_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ReferenceImage) + + assert response.name == "name_value" + + assert response.uri == "uri_value" + + +def test_create_reference_image_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateReferenceImageRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_reference_image), "__call__" + ) as call: + call.return_value = product_search_service.ReferenceImage() + + client.create_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_reference_image_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateReferenceImageRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_reference_image), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage() + ) + + await client.create_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_reference_image_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_reference_image( + parent="parent_value", + reference_image=product_search_service.ReferenceImage(name="name_value"), + reference_image_id="reference_image_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].reference_image == product_search_service.ReferenceImage( + name="name_value" + ) + + assert args[0].reference_image_id == "reference_image_id_value" + + +def test_create_reference_image_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_reference_image( + product_search_service.CreateReferenceImageRequest(), + parent="parent_value", + reference_image=product_search_service.ReferenceImage(name="name_value"), + reference_image_id="reference_image_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_reference_image_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_reference_image( + parent="parent_value", + reference_image=product_search_service.ReferenceImage(name="name_value"), + reference_image_id="reference_image_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].reference_image == product_search_service.ReferenceImage( + name="name_value" + ) + + assert args[0].reference_image_id == "reference_image_id_value" + + +@pytest.mark.asyncio +async def test_create_reference_image_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_reference_image( + product_search_service.CreateReferenceImageRequest(), + parent="parent_value", + reference_image=product_search_service.ReferenceImage(name="name_value"), + reference_image_id="reference_image_id_value", + ) + + +def test_delete_reference_image( + transport: str = "grpc", + request_type=product_search_service.DeleteReferenceImageRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.DeleteReferenceImageRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_reference_image_from_dict(): + test_delete_reference_image(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_reference_image_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.DeleteReferenceImageRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_reference_image_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteReferenceImageRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_reference_image), "__call__" + ) as call: + call.return_value = None + + client.delete_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_reference_image_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteReferenceImageRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_reference_image), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_reference_image_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_reference_image(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_reference_image_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_reference_image( + product_search_service.DeleteReferenceImageRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_reference_image_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_reference_image(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_reference_image_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_reference_image( + product_search_service.DeleteReferenceImageRequest(), name="name_value", + ) + + +def test_list_reference_images( + transport: str = "grpc", + request_type=product_search_service.ListReferenceImagesRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_reference_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListReferenceImagesResponse( + page_size=951, next_page_token="next_page_token_value", + ) + + response = client.list_reference_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.ListReferenceImagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReferenceImagesPager) + + assert response.page_size == 951 + + assert response.next_page_token == "next_page_token_value" + + +def test_list_reference_images_from_dict(): + test_list_reference_images(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_reference_images_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.ListReferenceImagesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_reference_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListReferenceImagesResponse( + page_size=951, next_page_token="next_page_token_value", + ) + ) + + response = await client.list_reference_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReferenceImagesAsyncPager) + + assert response.page_size == 951 + + assert response.next_page_token == "next_page_token_value" + + +def test_list_reference_images_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListReferenceImagesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_reference_images), "__call__" + ) as call: + call.return_value = product_search_service.ListReferenceImagesResponse() + + client.list_reference_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_reference_images_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListReferenceImagesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_reference_images), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListReferenceImagesResponse() + ) + + await client.list_reference_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_reference_images_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_reference_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListReferenceImagesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_reference_images(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_reference_images_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_reference_images( + product_search_service.ListReferenceImagesRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_reference_images_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_reference_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListReferenceImagesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListReferenceImagesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_reference_images(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_reference_images_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_reference_images( + product_search_service.ListReferenceImagesRequest(), parent="parent_value", + ) + + +def test_list_reference_images_pager(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_reference_images), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + next_page_token="abc", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[], next_page_token="def", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[product_search_service.ReferenceImage(),], + next_page_token="ghi", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_reference_images(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all( + isinstance(i, product_search_service.ReferenceImage) for i in results + ) + + +def test_list_reference_images_pages(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_reference_images), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + next_page_token="abc", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[], next_page_token="def", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[product_search_service.ReferenceImage(),], + next_page_token="ghi", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + ), + RuntimeError, + ) + pages = list(client.list_reference_images(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_reference_images_async_pager(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_reference_images), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + next_page_token="abc", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[], next_page_token="def", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[product_search_service.ReferenceImage(),], + next_page_token="ghi", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_reference_images(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, product_search_service.ReferenceImage) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_reference_images_async_pages(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_reference_images), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + next_page_token="abc", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[], next_page_token="def", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[product_search_service.ReferenceImage(),], + next_page_token="ghi", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_reference_images(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_reference_image( + transport: str = "grpc", + request_type=product_search_service.GetReferenceImageRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage( + name="name_value", uri="uri_value", + ) + + response = client.get_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.GetReferenceImageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ReferenceImage) + + assert response.name == "name_value" + + assert response.uri == "uri_value" + + +def test_get_reference_image_from_dict(): + test_get_reference_image(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_reference_image_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.GetReferenceImageRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage(name="name_value", uri="uri_value",) + ) + + response = await client.get_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ReferenceImage) + + assert response.name == "name_value" + + assert response.uri == "uri_value" + + +def test_get_reference_image_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetReferenceImageRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_reference_image), "__call__" + ) as call: + call.return_value = product_search_service.ReferenceImage() + + client.get_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_reference_image_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetReferenceImageRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_reference_image), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage() + ) + + await client.get_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_reference_image_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_reference_image(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_reference_image_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_reference_image( + product_search_service.GetReferenceImageRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_reference_image_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_reference_image(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_reference_image_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_reference_image( + product_search_service.GetReferenceImageRequest(), name="name_value", + ) + + +def test_add_product_to_product_set( + transport: str = "grpc", + request_type=product_search_service.AddProductToProductSetRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.add_product_to_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.add_product_to_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.AddProductToProductSetRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_add_product_to_product_set_from_dict(): + test_add_product_to_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_add_product_to_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.AddProductToProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.add_product_to_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.add_product_to_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_add_product_to_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.AddProductToProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.add_product_to_product_set), "__call__" + ) as call: + call.return_value = None + + client.add_product_to_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_add_product_to_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.AddProductToProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.add_product_to_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.add_product_to_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_add_product_to_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.add_product_to_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_product_to_product_set( + name="name_value", product="product_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].product == "product_value" + + +def test_add_product_to_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_product_to_product_set( + product_search_service.AddProductToProductSetRequest(), + name="name_value", + product="product_value", + ) + + +@pytest.mark.asyncio +async def test_add_product_to_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.add_product_to_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_product_to_product_set( + name="name_value", product="product_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].product == "product_value" + + +@pytest.mark.asyncio +async def test_add_product_to_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_product_to_product_set( + product_search_service.AddProductToProductSetRequest(), + name="name_value", + product="product_value", + ) + + +def test_remove_product_from_product_set( + transport: str = "grpc", + request_type=product_search_service.RemoveProductFromProductSetRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.remove_product_from_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.remove_product_from_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.RemoveProductFromProductSetRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_remove_product_from_product_set_from_dict(): + test_remove_product_from_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_remove_product_from_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.RemoveProductFromProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.remove_product_from_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.remove_product_from_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_remove_product_from_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.RemoveProductFromProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.remove_product_from_product_set), "__call__" + ) as call: + call.return_value = None + + client.remove_product_from_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_remove_product_from_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.RemoveProductFromProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.remove_product_from_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.remove_product_from_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_remove_product_from_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.remove_product_from_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_product_from_product_set( + name="name_value", product="product_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].product == "product_value" + + +def test_remove_product_from_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_product_from_product_set( + product_search_service.RemoveProductFromProductSetRequest(), + name="name_value", + product="product_value", + ) + + +@pytest.mark.asyncio +async def test_remove_product_from_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.remove_product_from_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.remove_product_from_product_set( + name="name_value", product="product_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].product == "product_value" + + +@pytest.mark.asyncio +async def test_remove_product_from_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_product_from_product_set( + product_search_service.RemoveProductFromProductSetRequest(), + name="name_value", + product="product_value", + ) + + +def test_list_products_in_product_set( + transport: str = "grpc", + request_type=product_search_service.ListProductsInProductSetRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_products_in_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsInProductSetResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_products_in_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.ListProductsInProductSetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsInProductSetPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_products_in_product_set_from_dict(): + test_list_products_in_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.ListProductsInProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products_in_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsInProductSetResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_products_in_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsInProductSetAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_products_in_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductsInProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_products_in_product_set), "__call__" + ) as call: + call.return_value = product_search_service.ListProductsInProductSetResponse() + + client.list_products_in_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductsInProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products_in_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsInProductSetResponse() + ) + + await client.list_products_in_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_list_products_in_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_products_in_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsInProductSetResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_products_in_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_list_products_in_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_products_in_product_set( + product_search_service.ListProductsInProductSetRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products_in_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsInProductSetResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsInProductSetResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_products_in_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_products_in_product_set( + product_search_service.ListProductsInProductSetRequest(), name="name_value", + ) + + +def test_list_products_in_product_set_pager(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_products_in_product_set), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsInProductSetResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsInProductSetResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), + ) + pager = client.list_products_in_product_set(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, product_search_service.Product) for i in results) + + +def test_list_products_in_product_set_pages(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_products_in_product_set), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsInProductSetResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsInProductSetResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + pages = list(client.list_products_in_product_set(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_async_pager(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products_in_product_set), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsInProductSetResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsInProductSetResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_products_in_product_set(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, product_search_service.Product) for i in responses) + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_async_pages(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products_in_product_set), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsInProductSetResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsInProductSetResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_products_in_product_set(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_import_product_sets( + transport: str = "grpc", + request_type=product_search_service.ImportProductSetsRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.import_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.import_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.ImportProductSetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_product_sets_from_dict(): + test_import_product_sets(request_type=dict) + + +@pytest.mark.asyncio +async def test_import_product_sets_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.ImportProductSetsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.import_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.import_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_product_sets_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ImportProductSetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.import_product_sets), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + + client.import_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_import_product_sets_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ImportProductSetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.import_product_sets), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + + await client.import_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_import_product_sets_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.import_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.import_product_sets( + parent="parent_value", + input_config=product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[ + 0 + ].input_config == product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ) + + +def test_import_product_sets_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.import_product_sets( + product_search_service.ImportProductSetsRequest(), + parent="parent_value", + input_config=product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ), + ) + + +@pytest.mark.asyncio +async def test_import_product_sets_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.import_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.import_product_sets( + parent="parent_value", + input_config=product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[ + 0 + ].input_config == product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ) + + +@pytest.mark.asyncio +async def test_import_product_sets_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.import_product_sets( + product_search_service.ImportProductSetsRequest(), + parent="parent_value", + input_config=product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ), + ) + + +def test_purge_products( + transport: str = "grpc", request_type=product_search_service.PurgeProductsRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.purge_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.PurgeProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_products_from_dict(): + test_purge_products(request_type=dict) + + +@pytest.mark.asyncio +async def test_purge_products_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.PurgeProductsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.purge_products), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_products_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.PurgeProductsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.purge_products), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + + client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_purge_products_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.PurgeProductsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.purge_products), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + + await client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_purge_products_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.purge_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.purge_products(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_purge_products_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.purge_products( + product_search_service.PurgeProductsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_purge_products_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.purge_products), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.purge_products(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_purge_products_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.purge_products( + product_search_service.PurgeProductsRequest(), parent="parent_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProductSearchGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProductSearchGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductSearchClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProductSearchGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductSearchClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductSearchGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = ProductSearchClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductSearchGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductSearchGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.ProductSearchGrpcTransport,) + + +def test_product_search_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.ProductSearchTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_product_search_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.vision_v1.services.product_search.transports.ProductSearchTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ProductSearchTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_product_set", + "list_product_sets", + "get_product_set", + "update_product_set", + "delete_product_set", + "create_product", + "list_products", + "get_product", + "update_product", + "delete_product", + "create_reference_image", + "delete_reference_image", + "list_reference_images", + "get_reference_image", + "add_product_to_product_set", + "remove_product_from_product_set", + "list_products_in_product_set", + "import_product_sets", + "purge_products", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_product_search_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.vision_v1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ProductSearchTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +def test_product_search_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.vision_v1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ProductSearchTransport() + adc.assert_called_once() + + +def test_product_search_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + ProductSearchClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id=None, + ) + + +def test_product_search_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.ProductSearchGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +def test_product_search_host_no_port(): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vision.googleapis.com" + ), + ) + assert client._transport._host == "vision.googleapis.com:443" + + +def test_product_search_host_with_port(): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vision.googleapis.com:8000" + ), + ) + assert client._transport._host == "vision.googleapis.com:8000" + + +def test_product_search_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ProductSearchGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +def test_product_search_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ProductSearchGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + ], +) +def test_product_search_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + ], +) +def test_product_search_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_product_search_grpc_lro_client(): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + transport = client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_product_search_grpc_lro_async_client(): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + transport = client._client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_product_path(): + project = "squid" + location = "clam" + product = "whelk" + + expected = "projects/{project}/locations/{location}/products/{product}".format( + project=project, location=location, product=product, + ) + actual = ProductSearchClient.product_path(project, location, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "octopus", + "location": "oyster", + "product": "nudibranch", + } + path = ProductSearchClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = ProductSearchClient.parse_product_path(path) + assert expected == actual + + +def test_product_set_path(): + project = "squid" + location = "clam" + product_set = "whelk" + + expected = "projects/{project}/locations/{location}/productSets/{product_set}".format( + project=project, location=location, product_set=product_set, + ) + actual = ProductSearchClient.product_set_path(project, location, product_set) + assert expected == actual + + +def test_parse_product_set_path(): + expected = { + "project": "octopus", + "location": "oyster", + "product_set": "nudibranch", + } + path = ProductSearchClient.product_set_path(**expected) + + # Check that the path construction is reversible. + actual = ProductSearchClient.parse_product_set_path(path) + assert expected == actual + + +def test_reference_image_path(): + project = "squid" + location = "clam" + product = "whelk" + reference_image = "octopus" + + expected = "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( + project=project, + location=location, + product=product, + reference_image=reference_image, + ) + actual = ProductSearchClient.reference_image_path( + project, location, product, reference_image + ) + assert expected == actual + + +def test_parse_reference_image_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "product": "cuttlefish", + "reference_image": "mussel", + } + path = ProductSearchClient.reference_image_path(**expected) + + # Check that the path construction is reversible. + actual = ProductSearchClient.parse_reference_image_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.ProductSearchTransport, "_prep_wrapped_messages" + ) as prep: + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ProductSearchTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ProductSearchClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/vision_v1p1beta1/__init__.py b/tests/unit/gapic/vision_v1p1beta1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/vision_v1p1beta1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/vision_v1p1beta1/test_image_annotator.py b/tests/unit/gapic/vision_v1p1beta1/test_image_annotator.py new file mode 100644 index 00000000..18280372 --- /dev/null +++ b/tests/unit/gapic/vision_v1p1beta1/test_image_annotator.py @@ -0,0 +1,927 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.vision_v1p1beta1.services.image_annotator import ( + ImageAnnotatorAsyncClient, +) +from google.cloud.vision_v1p1beta1.services.image_annotator import ImageAnnotatorClient +from google.cloud.vision_v1p1beta1.services.image_annotator import transports +from google.cloud.vision_v1p1beta1.types import image_annotator +from google.oauth2 import service_account +from google.type import latlng_pb2 as latlng # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ImageAnnotatorClient._get_default_mtls_endpoint(None) is None + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient] +) +def test_image_annotator_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "vision.googleapis.com:443" + + +def test_image_annotator_client_get_transport_class(): + transport = ImageAnnotatorClient.get_transport_class() + assert transport == transports.ImageAnnotatorGrpcTransport + + transport = ImageAnnotatorClient.get_transport_class("grpc") + assert transport == transports.ImageAnnotatorGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + ImageAnnotatorClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorClient), +) +@mock.patch.object( + ImageAnnotatorAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorAsyncClient), +) +def test_image_annotator_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "true"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "false"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + ImageAnnotatorClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorClient), +) +@mock.patch.object( + ImageAnnotatorAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_image_annotator_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_image_annotator_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_image_annotator_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_image_annotator_client_client_options_from_dict(): + with mock.patch( + "google.cloud.vision_v1p1beta1.services.image_annotator.transports.ImageAnnotatorGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ImageAnnotatorClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_batch_annotate_images( + transport: str = "grpc", request_type=image_annotator.BatchAnnotateImagesRequest +): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateImagesResponse() + + response = client.batch_annotate_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == image_annotator.BatchAnnotateImagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, image_annotator.BatchAnnotateImagesResponse) + + +def test_batch_annotate_images_from_dict(): + test_batch_annotate_images(request_type=dict) + + +@pytest.mark.asyncio +async def test_batch_annotate_images_async(transport: str = "grpc_asyncio"): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = image_annotator.BatchAnnotateImagesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + image_annotator.BatchAnnotateImagesResponse() + ) + + response = await client.batch_annotate_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, image_annotator.BatchAnnotateImagesResponse) + + +def test_batch_annotate_images_flattened(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateImagesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_annotate_images( + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ] + + +def test_batch_annotate_images_flattened_error(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_annotate_images( + image_annotator.BatchAnnotateImagesRequest(), + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + +@pytest.mark.asyncio +async def test_batch_annotate_images_flattened_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateImagesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + image_annotator.BatchAnnotateImagesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_annotate_images( + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ] + + +@pytest.mark.asyncio +async def test_batch_annotate_images_flattened_error_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_annotate_images( + image_annotator.BatchAnnotateImagesRequest(), + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageAnnotatorClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageAnnotatorClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = ImageAnnotatorClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ImageAnnotatorGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.ImageAnnotatorGrpcTransport,) + + +def test_image_annotator_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.ImageAnnotatorTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_image_annotator_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.vision_v1p1beta1.services.image_annotator.transports.ImageAnnotatorTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ImageAnnotatorTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ("batch_annotate_images",) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_image_annotator_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.vision_v1p1beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ImageAnnotatorTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +def test_image_annotator_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.vision_v1p1beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ImageAnnotatorTransport() + adc.assert_called_once() + + +def test_image_annotator_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + ImageAnnotatorClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id=None, + ) + + +def test_image_annotator_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.ImageAnnotatorGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +def test_image_annotator_host_no_port(): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vision.googleapis.com" + ), + ) + assert client._transport._host == "vision.googleapis.com:443" + + +def test_image_annotator_host_with_port(): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vision.googleapis.com:8000" + ), + ) + assert client._transport._host == "vision.googleapis.com:8000" + + +def test_image_annotator_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ImageAnnotatorGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +def test_image_annotator_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ImageAnnotatorGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +def test_image_annotator_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +def test_image_annotator_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.ImageAnnotatorTransport, "_prep_wrapped_messages" + ) as prep: + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ImageAnnotatorTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ImageAnnotatorClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/vision_v1p2beta1/__init__.py b/tests/unit/gapic/vision_v1p2beta1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/vision_v1p2beta1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/vision_v1p2beta1/test_image_annotator.py b/tests/unit/gapic/vision_v1p2beta1/test_image_annotator.py new file mode 100644 index 00000000..10d5cc81 --- /dev/null +++ b/tests/unit/gapic/vision_v1p2beta1/test_image_annotator.py @@ -0,0 +1,1143 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.vision_v1p2beta1.services.image_annotator import ( + ImageAnnotatorAsyncClient, +) +from google.cloud.vision_v1p2beta1.services.image_annotator import ImageAnnotatorClient +from google.cloud.vision_v1p2beta1.services.image_annotator import transports +from google.cloud.vision_v1p2beta1.types import image_annotator +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.type import latlng_pb2 as latlng # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ImageAnnotatorClient._get_default_mtls_endpoint(None) is None + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient] +) +def test_image_annotator_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "vision.googleapis.com:443" + + +def test_image_annotator_client_get_transport_class(): + transport = ImageAnnotatorClient.get_transport_class() + assert transport == transports.ImageAnnotatorGrpcTransport + + transport = ImageAnnotatorClient.get_transport_class("grpc") + assert transport == transports.ImageAnnotatorGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + ImageAnnotatorClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorClient), +) +@mock.patch.object( + ImageAnnotatorAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorAsyncClient), +) +def test_image_annotator_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "true"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "false"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + ImageAnnotatorClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorClient), +) +@mock.patch.object( + ImageAnnotatorAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_image_annotator_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_image_annotator_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_image_annotator_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_image_annotator_client_client_options_from_dict(): + with mock.patch( + "google.cloud.vision_v1p2beta1.services.image_annotator.transports.ImageAnnotatorGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ImageAnnotatorClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_batch_annotate_images( + transport: str = "grpc", request_type=image_annotator.BatchAnnotateImagesRequest +): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateImagesResponse() + + response = client.batch_annotate_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == image_annotator.BatchAnnotateImagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, image_annotator.BatchAnnotateImagesResponse) + + +def test_batch_annotate_images_from_dict(): + test_batch_annotate_images(request_type=dict) + + +@pytest.mark.asyncio +async def test_batch_annotate_images_async(transport: str = "grpc_asyncio"): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = image_annotator.BatchAnnotateImagesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + image_annotator.BatchAnnotateImagesResponse() + ) + + response = await client.batch_annotate_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, image_annotator.BatchAnnotateImagesResponse) + + +def test_batch_annotate_images_flattened(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateImagesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_annotate_images( + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ] + + +def test_batch_annotate_images_flattened_error(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_annotate_images( + image_annotator.BatchAnnotateImagesRequest(), + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + +@pytest.mark.asyncio +async def test_batch_annotate_images_flattened_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateImagesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + image_annotator.BatchAnnotateImagesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_annotate_images( + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ] + + +@pytest.mark.asyncio +async def test_batch_annotate_images_flattened_error_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_annotate_images( + image_annotator.BatchAnnotateImagesRequest(), + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + +def test_async_batch_annotate_files( + transport: str = "grpc", request_type=image_annotator.AsyncBatchAnnotateFilesRequest +): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.async_batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.async_batch_annotate_files(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == image_annotator.AsyncBatchAnnotateFilesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_async_batch_annotate_files_from_dict(): + test_async_batch_annotate_files(request_type=dict) + + +@pytest.mark.asyncio +async def test_async_batch_annotate_files_async(transport: str = "grpc_asyncio"): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = image_annotator.AsyncBatchAnnotateFilesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.async_batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.async_batch_annotate_files(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_async_batch_annotate_files_flattened(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.async_batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.async_batch_annotate_files( + requests=[ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ] + + +def test_async_batch_annotate_files_flattened_error(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.async_batch_annotate_files( + image_annotator.AsyncBatchAnnotateFilesRequest(), + requests=[ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + +@pytest.mark.asyncio +async def test_async_batch_annotate_files_flattened_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.async_batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.async_batch_annotate_files( + requests=[ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ] + + +@pytest.mark.asyncio +async def test_async_batch_annotate_files_flattened_error_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.async_batch_annotate_files( + image_annotator.AsyncBatchAnnotateFilesRequest(), + requests=[ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageAnnotatorClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageAnnotatorClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = ImageAnnotatorClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ImageAnnotatorGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.ImageAnnotatorGrpcTransport,) + + +def test_image_annotator_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.ImageAnnotatorTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_image_annotator_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.vision_v1p2beta1.services.image_annotator.transports.ImageAnnotatorTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ImageAnnotatorTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "batch_annotate_images", + "async_batch_annotate_files", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_image_annotator_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.vision_v1p2beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ImageAnnotatorTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +def test_image_annotator_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.vision_v1p2beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ImageAnnotatorTransport() + adc.assert_called_once() + + +def test_image_annotator_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + ImageAnnotatorClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id=None, + ) + + +def test_image_annotator_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.ImageAnnotatorGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +def test_image_annotator_host_no_port(): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vision.googleapis.com" + ), + ) + assert client._transport._host == "vision.googleapis.com:443" + + +def test_image_annotator_host_with_port(): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vision.googleapis.com:8000" + ), + ) + assert client._transport._host == "vision.googleapis.com:8000" + + +def test_image_annotator_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ImageAnnotatorGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +def test_image_annotator_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ImageAnnotatorGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +def test_image_annotator_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +def test_image_annotator_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_image_annotator_grpc_lro_client(): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + transport = client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_image_annotator_grpc_lro_async_client(): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + transport = client._client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.ImageAnnotatorTransport, "_prep_wrapped_messages" + ) as prep: + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ImageAnnotatorTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ImageAnnotatorClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/vision_v1p3beta1/__init__.py b/tests/unit/gapic/vision_v1p3beta1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/vision_v1p3beta1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/vision_v1p3beta1/test_image_annotator.py b/tests/unit/gapic/vision_v1p3beta1/test_image_annotator.py new file mode 100644 index 00000000..ce7942fe --- /dev/null +++ b/tests/unit/gapic/vision_v1p3beta1/test_image_annotator.py @@ -0,0 +1,1145 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.vision_v1p3beta1.services.image_annotator import ( + ImageAnnotatorAsyncClient, +) +from google.cloud.vision_v1p3beta1.services.image_annotator import ImageAnnotatorClient +from google.cloud.vision_v1p3beta1.services.image_annotator import transports +from google.cloud.vision_v1p3beta1.types import geometry +from google.cloud.vision_v1p3beta1.types import image_annotator +from google.cloud.vision_v1p3beta1.types import product_search +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.type import latlng_pb2 as latlng # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ImageAnnotatorClient._get_default_mtls_endpoint(None) is None + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient] +) +def test_image_annotator_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "vision.googleapis.com:443" + + +def test_image_annotator_client_get_transport_class(): + transport = ImageAnnotatorClient.get_transport_class() + assert transport == transports.ImageAnnotatorGrpcTransport + + transport = ImageAnnotatorClient.get_transport_class("grpc") + assert transport == transports.ImageAnnotatorGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + ImageAnnotatorClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorClient), +) +@mock.patch.object( + ImageAnnotatorAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorAsyncClient), +) +def test_image_annotator_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "true"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "false"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + ImageAnnotatorClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorClient), +) +@mock.patch.object( + ImageAnnotatorAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_image_annotator_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_image_annotator_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_image_annotator_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_image_annotator_client_client_options_from_dict(): + with mock.patch( + "google.cloud.vision_v1p3beta1.services.image_annotator.transports.ImageAnnotatorGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ImageAnnotatorClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_batch_annotate_images( + transport: str = "grpc", request_type=image_annotator.BatchAnnotateImagesRequest +): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateImagesResponse() + + response = client.batch_annotate_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == image_annotator.BatchAnnotateImagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, image_annotator.BatchAnnotateImagesResponse) + + +def test_batch_annotate_images_from_dict(): + test_batch_annotate_images(request_type=dict) + + +@pytest.mark.asyncio +async def test_batch_annotate_images_async(transport: str = "grpc_asyncio"): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = image_annotator.BatchAnnotateImagesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + image_annotator.BatchAnnotateImagesResponse() + ) + + response = await client.batch_annotate_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, image_annotator.BatchAnnotateImagesResponse) + + +def test_batch_annotate_images_flattened(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateImagesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_annotate_images( + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ] + + +def test_batch_annotate_images_flattened_error(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_annotate_images( + image_annotator.BatchAnnotateImagesRequest(), + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + +@pytest.mark.asyncio +async def test_batch_annotate_images_flattened_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateImagesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + image_annotator.BatchAnnotateImagesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_annotate_images( + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ] + + +@pytest.mark.asyncio +async def test_batch_annotate_images_flattened_error_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_annotate_images( + image_annotator.BatchAnnotateImagesRequest(), + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + +def test_async_batch_annotate_files( + transport: str = "grpc", request_type=image_annotator.AsyncBatchAnnotateFilesRequest +): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.async_batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.async_batch_annotate_files(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == image_annotator.AsyncBatchAnnotateFilesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_async_batch_annotate_files_from_dict(): + test_async_batch_annotate_files(request_type=dict) + + +@pytest.mark.asyncio +async def test_async_batch_annotate_files_async(transport: str = "grpc_asyncio"): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = image_annotator.AsyncBatchAnnotateFilesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.async_batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.async_batch_annotate_files(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_async_batch_annotate_files_flattened(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.async_batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.async_batch_annotate_files( + requests=[ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ] + + +def test_async_batch_annotate_files_flattened_error(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.async_batch_annotate_files( + image_annotator.AsyncBatchAnnotateFilesRequest(), + requests=[ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + +@pytest.mark.asyncio +async def test_async_batch_annotate_files_flattened_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.async_batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.async_batch_annotate_files( + requests=[ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ] + + +@pytest.mark.asyncio +async def test_async_batch_annotate_files_flattened_error_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.async_batch_annotate_files( + image_annotator.AsyncBatchAnnotateFilesRequest(), + requests=[ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageAnnotatorClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageAnnotatorClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = ImageAnnotatorClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ImageAnnotatorGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.ImageAnnotatorGrpcTransport,) + + +def test_image_annotator_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.ImageAnnotatorTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_image_annotator_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.vision_v1p3beta1.services.image_annotator.transports.ImageAnnotatorTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ImageAnnotatorTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "batch_annotate_images", + "async_batch_annotate_files", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_image_annotator_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.vision_v1p3beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ImageAnnotatorTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +def test_image_annotator_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.vision_v1p3beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ImageAnnotatorTransport() + adc.assert_called_once() + + +def test_image_annotator_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + ImageAnnotatorClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id=None, + ) + + +def test_image_annotator_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.ImageAnnotatorGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +def test_image_annotator_host_no_port(): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vision.googleapis.com" + ), + ) + assert client._transport._host == "vision.googleapis.com:443" + + +def test_image_annotator_host_with_port(): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vision.googleapis.com:8000" + ), + ) + assert client._transport._host == "vision.googleapis.com:8000" + + +def test_image_annotator_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ImageAnnotatorGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +def test_image_annotator_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ImageAnnotatorGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +def test_image_annotator_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +def test_image_annotator_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_image_annotator_grpc_lro_client(): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + transport = client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_image_annotator_grpc_lro_async_client(): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + transport = client._client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.ImageAnnotatorTransport, "_prep_wrapped_messages" + ) as prep: + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ImageAnnotatorTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ImageAnnotatorClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/vision_v1p3beta1/test_product_search.py b/tests/unit/gapic/vision_v1p3beta1/test_product_search.py new file mode 100644 index 00000000..5e2e7d9d --- /dev/null +++ b/tests/unit/gapic/vision_v1p3beta1/test_product_search.py @@ -0,0 +1,5304 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.vision_v1p3beta1.services.product_search import ( + ProductSearchAsyncClient, +) +from google.cloud.vision_v1p3beta1.services.product_search import ProductSearchClient +from google.cloud.vision_v1p3beta1.services.product_search import pagers +from google.cloud.vision_v1p3beta1.services.product_search import transports +from google.cloud.vision_v1p3beta1.types import geometry +from google.cloud.vision_v1p3beta1.types import product_search_service +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 as gp_any # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ProductSearchClient._get_default_mtls_endpoint(None) is None + assert ( + ProductSearchClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + ProductSearchClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ProductSearchClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ProductSearchClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ProductSearchClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [ProductSearchClient, ProductSearchAsyncClient] +) +def test_product_search_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "vision.googleapis.com:443" + + +def test_product_search_client_get_transport_class(): + transport = ProductSearchClient.get_transport_class() + assert transport == transports.ProductSearchGrpcTransport + + transport = ProductSearchClient.get_transport_class("grpc") + assert transport == transports.ProductSearchGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), + ( + ProductSearchAsyncClient, + transports.ProductSearchGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + ProductSearchClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ProductSearchClient), +) +@mock.patch.object( + ProductSearchAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ProductSearchAsyncClient), +) +def test_product_search_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ProductSearchClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(ProductSearchClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "true"), + ( + ProductSearchAsyncClient, + transports.ProductSearchGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "false"), + ( + ProductSearchAsyncClient, + transports.ProductSearchGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + ProductSearchClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ProductSearchClient), +) +@mock.patch.object( + ProductSearchAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ProductSearchAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_product_search_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), + ( + ProductSearchAsyncClient, + transports.ProductSearchGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_product_search_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), + ( + ProductSearchAsyncClient, + transports.ProductSearchGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_product_search_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_product_search_client_client_options_from_dict(): + with mock.patch( + "google.cloud.vision_v1p3beta1.services.product_search.transports.ProductSearchGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ProductSearchClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_create_product_set( + transport: str = "grpc", request_type=product_search_service.CreateProductSetRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + + response = client.create_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.CreateProductSetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_create_product_set_from_dict(): + test_create_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.CreateProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + ) + + response = await client.create_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_create_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateProductSetRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_product_set), "__call__" + ) as call: + call.return_value = product_search_service.ProductSet() + + client.create_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateProductSetRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + + await client.create_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_product_set( + parent="parent_value", + product_set=product_search_service.ProductSet(name="name_value"), + product_set_id="product_set_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].product_set == product_search_service.ProductSet( + name="name_value" + ) + + assert args[0].product_set_id == "product_set_id_value" + + +def test_create_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_product_set( + product_search_service.CreateProductSetRequest(), + parent="parent_value", + product_set=product_search_service.ProductSet(name="name_value"), + product_set_id="product_set_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_product_set( + parent="parent_value", + product_set=product_search_service.ProductSet(name="name_value"), + product_set_id="product_set_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].product_set == product_search_service.ProductSet( + name="name_value" + ) + + assert args[0].product_set_id == "product_set_id_value" + + +@pytest.mark.asyncio +async def test_create_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_product_set( + product_search_service.CreateProductSetRequest(), + parent="parent_value", + product_set=product_search_service.ProductSet(name="name_value"), + product_set_id="product_set_id_value", + ) + + +def test_list_product_sets( + transport: str = "grpc", request_type=product_search_service.ListProductSetsRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductSetsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.ListProductSetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductSetsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_product_sets_from_dict(): + test_list_product_sets(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_product_sets_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.ListProductSetsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductSetsResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductSetsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_product_sets_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductSetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_product_sets), "__call__" + ) as call: + call.return_value = product_search_service.ListProductSetsResponse() + + client.list_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_product_sets_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductSetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_product_sets), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductSetsResponse() + ) + + await client.list_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_product_sets_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductSetsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_product_sets(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_product_sets_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_product_sets( + product_search_service.ListProductSetsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_product_sets_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductSetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductSetsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_product_sets(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_product_sets_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_product_sets( + product_search_service.ListProductSetsRequest(), parent="parent_value", + ) + + +def test_list_product_sets_pager(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_product_sets), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + next_page_token="abc", + ), + product_search_service.ListProductSetsResponse( + product_sets=[], next_page_token="def", + ), + product_search_service.ListProductSetsResponse( + product_sets=[product_search_service.ProductSet(),], + next_page_token="ghi", + ), + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_product_sets(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, product_search_service.ProductSet) for i in results) + + +def test_list_product_sets_pages(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_product_sets), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + next_page_token="abc", + ), + product_search_service.ListProductSetsResponse( + product_sets=[], next_page_token="def", + ), + product_search_service.ListProductSetsResponse( + product_sets=[product_search_service.ProductSet(),], + next_page_token="ghi", + ), + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + ), + RuntimeError, + ) + pages = list(client.list_product_sets(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_product_sets_async_pager(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_product_sets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + next_page_token="abc", + ), + product_search_service.ListProductSetsResponse( + product_sets=[], next_page_token="def", + ), + product_search_service.ListProductSetsResponse( + product_sets=[product_search_service.ProductSet(),], + next_page_token="ghi", + ), + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_product_sets(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, product_search_service.ProductSet) for i in responses) + + +@pytest.mark.asyncio +async def test_list_product_sets_async_pages(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_product_sets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + next_page_token="abc", + ), + product_search_service.ListProductSetsResponse( + product_sets=[], next_page_token="def", + ), + product_search_service.ListProductSetsResponse( + product_sets=[product_search_service.ProductSet(),], + next_page_token="ghi", + ), + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_product_sets(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_product_set( + transport: str = "grpc", request_type=product_search_service.GetProductSetRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product_set), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + + response = client.get_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.GetProductSetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_get_product_set_from_dict(): + test_get_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.GetProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + ) + + response = await client.get_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_get_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product_set), "__call__") as call: + call.return_value = product_search_service.ProductSet() + + client.get_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + + await client.get_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product_set), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_product_set( + product_search_service.GetProductSetRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_product_set( + product_search_service.GetProductSetRequest(), name="name_value", + ) + + +def test_update_product_set( + transport: str = "grpc", request_type=product_search_service.UpdateProductSetRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.update_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + + response = client.update_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.UpdateProductSetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_update_product_set_from_dict(): + test_update_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.UpdateProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + ) + + response = await client.update_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_update_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.UpdateProductSetRequest() + request.product_set.name = "product_set.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.update_product_set), "__call__" + ) as call: + call.return_value = product_search_service.ProductSet() + + client.update_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "product_set.name=product_set.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.UpdateProductSetRequest() + request.product_set.name = "product_set.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + + await client.update_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "product_set.name=product_set.name/value",) in kw[ + "metadata" + ] + + +def test_update_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.update_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_product_set( + product_set=product_search_service.ProductSet(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].product_set == product_search_service.ProductSet( + name="name_value" + ) + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_product_set( + product_search_service.UpdateProductSetRequest(), + product_set=product_search_service.ProductSet(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_product_set( + product_set=product_search_service.ProductSet(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].product_set == product_search_service.ProductSet( + name="name_value" + ) + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_product_set( + product_search_service.UpdateProductSetRequest(), + product_set=product_search_service.ProductSet(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_product_set( + transport: str = "grpc", request_type=product_search_service.DeleteProductSetRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.DeleteProductSetRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_set_from_dict(): + test_delete_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.DeleteProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_product_set), "__call__" + ) as call: + call.return_value = None + + client.delete_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_product_set( + product_search_service.DeleteProductSetRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_product_set( + product_search_service.DeleteProductSetRequest(), name="name_value", + ) + + +def test_create_product( + transport: str = "grpc", request_type=product_search_service.CreateProductRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + + response = client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_create_product_from_dict(): + test_create_product(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_product_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.CreateProductRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + ) + + response = await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_create_product_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateProductRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_product), "__call__") as call: + call.return_value = product_search_service.Product() + + client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_product_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateProductRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + + await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_product_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_product( + parent="parent_value", + product=product_search_service.Product(name="name_value"), + product_id="product_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].product == product_search_service.Product(name="name_value") + + assert args[0].product_id == "product_id_value" + + +def test_create_product_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_product( + product_search_service.CreateProductRequest(), + parent="parent_value", + product=product_search_service.Product(name="name_value"), + product_id="product_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_product_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_product( + parent="parent_value", + product=product_search_service.Product(name="name_value"), + product_id="product_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].product == product_search_service.Product(name="name_value") + + assert args[0].product_id == "product_id_value" + + +@pytest.mark.asyncio +async def test_create_product_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_product( + product_search_service.CreateProductRequest(), + parent="parent_value", + product=product_search_service.Product(name="name_value"), + product_id="product_id_value", + ) + + +def test_list_products( + transport: str = "grpc", request_type=product_search_service.ListProductsRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_products_from_dict(): + test_list_products(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_products_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.ListProductsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_products_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_products), "__call__") as call: + call.return_value = product_search_service.ListProductsResponse() + + client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_products_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsResponse() + ) + + await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_products_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_products(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_products_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_products( + product_search_service.ListProductsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_products_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_products(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_products_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_products( + product_search_service.ListProductsRequest(), parent="parent_value", + ) + + +def test_list_products_pager(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_products), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_products(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, product_search_service.Product) for i in results) + + +def test_list_products_pages(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_products), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + pages = list(client.list_products(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_products_async_pager(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_products(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, product_search_service.Product) for i in responses) + + +@pytest.mark.asyncio +async def test_list_products_async_pages(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_products(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_product( + transport: str = "grpc", request_type=product_search_service.GetProductRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + + response = client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_get_product_from_dict(): + test_get_product(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_product_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.GetProductRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + ) + + response = await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_get_product_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetProductRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product), "__call__") as call: + call.return_value = product_search_service.Product() + + client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_product_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetProductRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + + await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_product_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_product(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_product_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_product( + product_search_service.GetProductRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_product_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_product(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_product_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_product( + product_search_service.GetProductRequest(), name="name_value", + ) + + +def test_update_product( + transport: str = "grpc", request_type=product_search_service.UpdateProductRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + + response = client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_update_product_from_dict(): + test_update_product(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_product_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.UpdateProductRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + ) + + response = await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_update_product_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.UpdateProductRequest() + request.product.name = "product.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_product), "__call__") as call: + call.return_value = product_search_service.Product() + + client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "product.name=product.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_product_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.UpdateProductRequest() + request.product.name = "product.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + + await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "product.name=product.name/value",) in kw[ + "metadata" + ] + + +def test_update_product_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_product( + product=product_search_service.Product(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].product == product_search_service.Product(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_product_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_product( + product_search_service.UpdateProductRequest(), + product=product_search_service.Product(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_product_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_product( + product=product_search_service.Product(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].product == product_search_service.Product(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_product_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_product( + product_search_service.UpdateProductRequest(), + product=product_search_service.Product(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_product( + transport: str = "grpc", request_type=product_search_service.DeleteProductRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_from_dict(): + test_delete_product(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_product_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.DeleteProductRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteProductRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_product), "__call__") as call: + call.return_value = None + + client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_product_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteProductRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_product_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_product(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_product_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_product( + product_search_service.DeleteProductRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_product_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_product(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_product_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_product( + product_search_service.DeleteProductRequest(), name="name_value", + ) + + +def test_create_reference_image( + transport: str = "grpc", + request_type=product_search_service.CreateReferenceImageRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage( + name="name_value", uri="uri_value", + ) + + response = client.create_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.CreateReferenceImageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ReferenceImage) + + assert response.name == "name_value" + + assert response.uri == "uri_value" + + +def test_create_reference_image_from_dict(): + test_create_reference_image(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_reference_image_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.CreateReferenceImageRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage(name="name_value", uri="uri_value",) + ) + + response = await client.create_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ReferenceImage) + + assert response.name == "name_value" + + assert response.uri == "uri_value" + + +def test_create_reference_image_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateReferenceImageRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_reference_image), "__call__" + ) as call: + call.return_value = product_search_service.ReferenceImage() + + client.create_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_reference_image_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateReferenceImageRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_reference_image), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage() + ) + + await client.create_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_reference_image_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_reference_image( + parent="parent_value", + reference_image=product_search_service.ReferenceImage(name="name_value"), + reference_image_id="reference_image_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].reference_image == product_search_service.ReferenceImage( + name="name_value" + ) + + assert args[0].reference_image_id == "reference_image_id_value" + + +def test_create_reference_image_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_reference_image( + product_search_service.CreateReferenceImageRequest(), + parent="parent_value", + reference_image=product_search_service.ReferenceImage(name="name_value"), + reference_image_id="reference_image_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_reference_image_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_reference_image( + parent="parent_value", + reference_image=product_search_service.ReferenceImage(name="name_value"), + reference_image_id="reference_image_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].reference_image == product_search_service.ReferenceImage( + name="name_value" + ) + + assert args[0].reference_image_id == "reference_image_id_value" + + +@pytest.mark.asyncio +async def test_create_reference_image_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_reference_image( + product_search_service.CreateReferenceImageRequest(), + parent="parent_value", + reference_image=product_search_service.ReferenceImage(name="name_value"), + reference_image_id="reference_image_id_value", + ) + + +def test_delete_reference_image( + transport: str = "grpc", + request_type=product_search_service.DeleteReferenceImageRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.DeleteReferenceImageRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_reference_image_from_dict(): + test_delete_reference_image(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_reference_image_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.DeleteReferenceImageRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_reference_image_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteReferenceImageRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_reference_image), "__call__" + ) as call: + call.return_value = None + + client.delete_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_reference_image_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteReferenceImageRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_reference_image), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_reference_image_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_reference_image(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_reference_image_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_reference_image( + product_search_service.DeleteReferenceImageRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_reference_image_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_reference_image(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_reference_image_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_reference_image( + product_search_service.DeleteReferenceImageRequest(), name="name_value", + ) + + +def test_list_reference_images( + transport: str = "grpc", + request_type=product_search_service.ListReferenceImagesRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_reference_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListReferenceImagesResponse( + page_size=951, next_page_token="next_page_token_value", + ) + + response = client.list_reference_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.ListReferenceImagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReferenceImagesPager) + + assert response.page_size == 951 + + assert response.next_page_token == "next_page_token_value" + + +def test_list_reference_images_from_dict(): + test_list_reference_images(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_reference_images_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.ListReferenceImagesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_reference_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListReferenceImagesResponse( + page_size=951, next_page_token="next_page_token_value", + ) + ) + + response = await client.list_reference_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReferenceImagesAsyncPager) + + assert response.page_size == 951 + + assert response.next_page_token == "next_page_token_value" + + +def test_list_reference_images_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListReferenceImagesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_reference_images), "__call__" + ) as call: + call.return_value = product_search_service.ListReferenceImagesResponse() + + client.list_reference_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_reference_images_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListReferenceImagesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_reference_images), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListReferenceImagesResponse() + ) + + await client.list_reference_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_reference_images_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_reference_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListReferenceImagesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_reference_images(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_reference_images_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_reference_images( + product_search_service.ListReferenceImagesRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_reference_images_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_reference_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListReferenceImagesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListReferenceImagesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_reference_images(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_reference_images_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_reference_images( + product_search_service.ListReferenceImagesRequest(), parent="parent_value", + ) + + +def test_list_reference_images_pager(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_reference_images), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + next_page_token="abc", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[], next_page_token="def", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[product_search_service.ReferenceImage(),], + next_page_token="ghi", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_reference_images(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all( + isinstance(i, product_search_service.ReferenceImage) for i in results + ) + + +def test_list_reference_images_pages(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_reference_images), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + next_page_token="abc", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[], next_page_token="def", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[product_search_service.ReferenceImage(),], + next_page_token="ghi", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + ), + RuntimeError, + ) + pages = list(client.list_reference_images(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_reference_images_async_pager(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_reference_images), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + next_page_token="abc", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[], next_page_token="def", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[product_search_service.ReferenceImage(),], + next_page_token="ghi", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_reference_images(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, product_search_service.ReferenceImage) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_reference_images_async_pages(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_reference_images), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + next_page_token="abc", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[], next_page_token="def", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[product_search_service.ReferenceImage(),], + next_page_token="ghi", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_reference_images(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_reference_image( + transport: str = "grpc", + request_type=product_search_service.GetReferenceImageRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage( + name="name_value", uri="uri_value", + ) + + response = client.get_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.GetReferenceImageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ReferenceImage) + + assert response.name == "name_value" + + assert response.uri == "uri_value" + + +def test_get_reference_image_from_dict(): + test_get_reference_image(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_reference_image_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.GetReferenceImageRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage(name="name_value", uri="uri_value",) + ) + + response = await client.get_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ReferenceImage) + + assert response.name == "name_value" + + assert response.uri == "uri_value" + + +def test_get_reference_image_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetReferenceImageRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_reference_image), "__call__" + ) as call: + call.return_value = product_search_service.ReferenceImage() + + client.get_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_reference_image_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetReferenceImageRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_reference_image), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage() + ) + + await client.get_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_reference_image_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_reference_image(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_reference_image_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_reference_image( + product_search_service.GetReferenceImageRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_reference_image_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_reference_image(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_reference_image_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_reference_image( + product_search_service.GetReferenceImageRequest(), name="name_value", + ) + + +def test_add_product_to_product_set( + transport: str = "grpc", + request_type=product_search_service.AddProductToProductSetRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.add_product_to_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.add_product_to_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.AddProductToProductSetRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_add_product_to_product_set_from_dict(): + test_add_product_to_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_add_product_to_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.AddProductToProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.add_product_to_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.add_product_to_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_add_product_to_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.AddProductToProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.add_product_to_product_set), "__call__" + ) as call: + call.return_value = None + + client.add_product_to_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_add_product_to_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.AddProductToProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.add_product_to_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.add_product_to_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_add_product_to_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.add_product_to_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_product_to_product_set( + name="name_value", product="product_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].product == "product_value" + + +def test_add_product_to_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_product_to_product_set( + product_search_service.AddProductToProductSetRequest(), + name="name_value", + product="product_value", + ) + + +@pytest.mark.asyncio +async def test_add_product_to_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.add_product_to_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_product_to_product_set( + name="name_value", product="product_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].product == "product_value" + + +@pytest.mark.asyncio +async def test_add_product_to_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_product_to_product_set( + product_search_service.AddProductToProductSetRequest(), + name="name_value", + product="product_value", + ) + + +def test_remove_product_from_product_set( + transport: str = "grpc", + request_type=product_search_service.RemoveProductFromProductSetRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.remove_product_from_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.remove_product_from_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.RemoveProductFromProductSetRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_remove_product_from_product_set_from_dict(): + test_remove_product_from_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_remove_product_from_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.RemoveProductFromProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.remove_product_from_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.remove_product_from_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_remove_product_from_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.RemoveProductFromProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.remove_product_from_product_set), "__call__" + ) as call: + call.return_value = None + + client.remove_product_from_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_remove_product_from_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.RemoveProductFromProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.remove_product_from_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.remove_product_from_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_remove_product_from_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.remove_product_from_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_product_from_product_set( + name="name_value", product="product_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].product == "product_value" + + +def test_remove_product_from_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_product_from_product_set( + product_search_service.RemoveProductFromProductSetRequest(), + name="name_value", + product="product_value", + ) + + +@pytest.mark.asyncio +async def test_remove_product_from_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.remove_product_from_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.remove_product_from_product_set( + name="name_value", product="product_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].product == "product_value" + + +@pytest.mark.asyncio +async def test_remove_product_from_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_product_from_product_set( + product_search_service.RemoveProductFromProductSetRequest(), + name="name_value", + product="product_value", + ) + + +def test_list_products_in_product_set( + transport: str = "grpc", + request_type=product_search_service.ListProductsInProductSetRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_products_in_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsInProductSetResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_products_in_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.ListProductsInProductSetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsInProductSetPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_products_in_product_set_from_dict(): + test_list_products_in_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.ListProductsInProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products_in_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsInProductSetResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_products_in_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsInProductSetAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_products_in_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductsInProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_products_in_product_set), "__call__" + ) as call: + call.return_value = product_search_service.ListProductsInProductSetResponse() + + client.list_products_in_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductsInProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products_in_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsInProductSetResponse() + ) + + await client.list_products_in_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_list_products_in_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_products_in_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsInProductSetResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_products_in_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_list_products_in_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_products_in_product_set( + product_search_service.ListProductsInProductSetRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products_in_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsInProductSetResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsInProductSetResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_products_in_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_products_in_product_set( + product_search_service.ListProductsInProductSetRequest(), name="name_value", + ) + + +def test_list_products_in_product_set_pager(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_products_in_product_set), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsInProductSetResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsInProductSetResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), + ) + pager = client.list_products_in_product_set(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, product_search_service.Product) for i in results) + + +def test_list_products_in_product_set_pages(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_products_in_product_set), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsInProductSetResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsInProductSetResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + pages = list(client.list_products_in_product_set(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_async_pager(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products_in_product_set), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsInProductSetResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsInProductSetResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_products_in_product_set(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, product_search_service.Product) for i in responses) + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_async_pages(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products_in_product_set), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsInProductSetResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsInProductSetResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_products_in_product_set(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_import_product_sets( + transport: str = "grpc", + request_type=product_search_service.ImportProductSetsRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.import_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.import_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.ImportProductSetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_product_sets_from_dict(): + test_import_product_sets(request_type=dict) + + +@pytest.mark.asyncio +async def test_import_product_sets_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.ImportProductSetsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.import_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.import_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_product_sets_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ImportProductSetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.import_product_sets), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + + client.import_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_import_product_sets_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ImportProductSetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.import_product_sets), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + + await client.import_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_import_product_sets_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.import_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.import_product_sets( + parent="parent_value", + input_config=product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[ + 0 + ].input_config == product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ) + + +def test_import_product_sets_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.import_product_sets( + product_search_service.ImportProductSetsRequest(), + parent="parent_value", + input_config=product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ), + ) + + +@pytest.mark.asyncio +async def test_import_product_sets_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.import_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.import_product_sets( + parent="parent_value", + input_config=product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[ + 0 + ].input_config == product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ) + + +@pytest.mark.asyncio +async def test_import_product_sets_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.import_product_sets( + product_search_service.ImportProductSetsRequest(), + parent="parent_value", + input_config=product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProductSearchGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProductSearchGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductSearchClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProductSearchGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductSearchClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductSearchGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = ProductSearchClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductSearchGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductSearchGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.ProductSearchGrpcTransport,) + + +def test_product_search_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.ProductSearchTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_product_search_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.vision_v1p3beta1.services.product_search.transports.ProductSearchTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ProductSearchTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_product_set", + "list_product_sets", + "get_product_set", + "update_product_set", + "delete_product_set", + "create_product", + "list_products", + "get_product", + "update_product", + "delete_product", + "create_reference_image", + "delete_reference_image", + "list_reference_images", + "get_reference_image", + "add_product_to_product_set", + "remove_product_from_product_set", + "list_products_in_product_set", + "import_product_sets", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_product_search_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.vision_v1p3beta1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ProductSearchTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +def test_product_search_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.vision_v1p3beta1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ProductSearchTransport() + adc.assert_called_once() + + +def test_product_search_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + ProductSearchClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id=None, + ) + + +def test_product_search_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.ProductSearchGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +def test_product_search_host_no_port(): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vision.googleapis.com" + ), + ) + assert client._transport._host == "vision.googleapis.com:443" + + +def test_product_search_host_with_port(): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vision.googleapis.com:8000" + ), + ) + assert client._transport._host == "vision.googleapis.com:8000" + + +def test_product_search_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ProductSearchGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +def test_product_search_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ProductSearchGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + ], +) +def test_product_search_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + ], +) +def test_product_search_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_product_search_grpc_lro_client(): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + transport = client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_product_search_grpc_lro_async_client(): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + transport = client._client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_product_path(): + project = "squid" + location = "clam" + product = "whelk" + + expected = "projects/{project}/locations/{location}/products/{product}".format( + project=project, location=location, product=product, + ) + actual = ProductSearchClient.product_path(project, location, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "octopus", + "location": "oyster", + "product": "nudibranch", + } + path = ProductSearchClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = ProductSearchClient.parse_product_path(path) + assert expected == actual + + +def test_product_set_path(): + project = "squid" + location = "clam" + product_set = "whelk" + + expected = "projects/{project}/locations/{location}/productSets/{product_set}".format( + project=project, location=location, product_set=product_set, + ) + actual = ProductSearchClient.product_set_path(project, location, product_set) + assert expected == actual + + +def test_parse_product_set_path(): + expected = { + "project": "octopus", + "location": "oyster", + "product_set": "nudibranch", + } + path = ProductSearchClient.product_set_path(**expected) + + # Check that the path construction is reversible. + actual = ProductSearchClient.parse_product_set_path(path) + assert expected == actual + + +def test_reference_image_path(): + project = "squid" + location = "clam" + product = "whelk" + reference_image = "octopus" + + expected = "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( + project=project, + location=location, + product=product, + reference_image=reference_image, + ) + actual = ProductSearchClient.reference_image_path( + project, location, product, reference_image + ) + assert expected == actual + + +def test_parse_reference_image_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "product": "cuttlefish", + "reference_image": "mussel", + } + path = ProductSearchClient.reference_image_path(**expected) + + # Check that the path construction is reversible. + actual = ProductSearchClient.parse_reference_image_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.ProductSearchTransport, "_prep_wrapped_messages" + ) as prep: + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ProductSearchTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ProductSearchClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/vision_v1p4beta1/__init__.py b/tests/unit/gapic/vision_v1p4beta1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/vision_v1p4beta1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/vision_v1p4beta1/test_image_annotator.py b/tests/unit/gapic/vision_v1p4beta1/test_image_annotator.py new file mode 100644 index 00000000..3fe919f8 --- /dev/null +++ b/tests/unit/gapic/vision_v1p4beta1/test_image_annotator.py @@ -0,0 +1,1513 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.vision_v1p4beta1.services.image_annotator import ( + ImageAnnotatorAsyncClient, +) +from google.cloud.vision_v1p4beta1.services.image_annotator import ImageAnnotatorClient +from google.cloud.vision_v1p4beta1.services.image_annotator import transports +from google.cloud.vision_v1p4beta1.types import face +from google.cloud.vision_v1p4beta1.types import geometry +from google.cloud.vision_v1p4beta1.types import image_annotator +from google.cloud.vision_v1p4beta1.types import product_search +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.type import latlng_pb2 as latlng # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ImageAnnotatorClient._get_default_mtls_endpoint(None) is None + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ImageAnnotatorClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient] +) +def test_image_annotator_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "vision.googleapis.com:443" + + +def test_image_annotator_client_get_transport_class(): + transport = ImageAnnotatorClient.get_transport_class() + assert transport == transports.ImageAnnotatorGrpcTransport + + transport = ImageAnnotatorClient.get_transport_class("grpc") + assert transport == transports.ImageAnnotatorGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + ImageAnnotatorClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorClient), +) +@mock.patch.object( + ImageAnnotatorAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorAsyncClient), +) +def test_image_annotator_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(ImageAnnotatorClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "true"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc", "false"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + ImageAnnotatorClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorClient), +) +@mock.patch.object( + ImageAnnotatorAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ImageAnnotatorAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_image_annotator_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_image_annotator_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ImageAnnotatorClient, transports.ImageAnnotatorGrpcTransport, "grpc"), + ( + ImageAnnotatorAsyncClient, + transports.ImageAnnotatorGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_image_annotator_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_image_annotator_client_client_options_from_dict(): + with mock.patch( + "google.cloud.vision_v1p4beta1.services.image_annotator.transports.ImageAnnotatorGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ImageAnnotatorClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_batch_annotate_images( + transport: str = "grpc", request_type=image_annotator.BatchAnnotateImagesRequest +): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateImagesResponse() + + response = client.batch_annotate_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == image_annotator.BatchAnnotateImagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, image_annotator.BatchAnnotateImagesResponse) + + +def test_batch_annotate_images_from_dict(): + test_batch_annotate_images(request_type=dict) + + +@pytest.mark.asyncio +async def test_batch_annotate_images_async(transport: str = "grpc_asyncio"): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = image_annotator.BatchAnnotateImagesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + image_annotator.BatchAnnotateImagesResponse() + ) + + response = await client.batch_annotate_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, image_annotator.BatchAnnotateImagesResponse) + + +def test_batch_annotate_images_flattened(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateImagesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_annotate_images( + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ] + + +def test_batch_annotate_images_flattened_error(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_annotate_images( + image_annotator.BatchAnnotateImagesRequest(), + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + +@pytest.mark.asyncio +async def test_batch_annotate_images_flattened_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateImagesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + image_annotator.BatchAnnotateImagesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_annotate_images( + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ] + + +@pytest.mark.asyncio +async def test_batch_annotate_images_flattened_error_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_annotate_images( + image_annotator.BatchAnnotateImagesRequest(), + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + ) + + +def test_batch_annotate_files( + transport: str = "grpc", request_type=image_annotator.BatchAnnotateFilesRequest +): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateFilesResponse() + + response = client.batch_annotate_files(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == image_annotator.BatchAnnotateFilesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, image_annotator.BatchAnnotateFilesResponse) + + +def test_batch_annotate_files_from_dict(): + test_batch_annotate_files(request_type=dict) + + +@pytest.mark.asyncio +async def test_batch_annotate_files_async(transport: str = "grpc_asyncio"): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = image_annotator.BatchAnnotateFilesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + image_annotator.BatchAnnotateFilesResponse() + ) + + response = await client.batch_annotate_files(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, image_annotator.BatchAnnotateFilesResponse) + + +def test_batch_annotate_files_flattened(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateFilesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.batch_annotate_files( + requests=[ + image_annotator.AnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ] + + +def test_batch_annotate_files_flattened_error(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.batch_annotate_files( + image_annotator.BatchAnnotateFilesRequest(), + requests=[ + image_annotator.AnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + +@pytest.mark.asyncio +async def test_batch_annotate_files_flattened_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = image_annotator.BatchAnnotateFilesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + image_annotator.BatchAnnotateFilesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.batch_annotate_files( + requests=[ + image_annotator.AnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ] + + +@pytest.mark.asyncio +async def test_batch_annotate_files_flattened_error_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.batch_annotate_files( + image_annotator.BatchAnnotateFilesRequest(), + requests=[ + image_annotator.AnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + +def test_async_batch_annotate_images( + transport: str = "grpc", + request_type=image_annotator.AsyncBatchAnnotateImagesRequest, +): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.async_batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.async_batch_annotate_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == image_annotator.AsyncBatchAnnotateImagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_async_batch_annotate_images_from_dict(): + test_async_batch_annotate_images(request_type=dict) + + +@pytest.mark.asyncio +async def test_async_batch_annotate_images_async(transport: str = "grpc_asyncio"): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = image_annotator.AsyncBatchAnnotateImagesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.async_batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.async_batch_annotate_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_async_batch_annotate_images_flattened(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.async_batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.async_batch_annotate_images( + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + output_config=image_annotator.OutputConfig( + gcs_destination=image_annotator.GcsDestination(uri="uri_value") + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ] + + assert args[0].output_config == image_annotator.OutputConfig( + gcs_destination=image_annotator.GcsDestination(uri="uri_value") + ) + + +def test_async_batch_annotate_images_flattened_error(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.async_batch_annotate_images( + image_annotator.AsyncBatchAnnotateImagesRequest(), + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + output_config=image_annotator.OutputConfig( + gcs_destination=image_annotator.GcsDestination(uri="uri_value") + ), + ) + + +@pytest.mark.asyncio +async def test_async_batch_annotate_images_flattened_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.async_batch_annotate_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.async_batch_annotate_images( + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + output_config=image_annotator.OutputConfig( + gcs_destination=image_annotator.GcsDestination(uri="uri_value") + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ] + + assert args[0].output_config == image_annotator.OutputConfig( + gcs_destination=image_annotator.GcsDestination(uri="uri_value") + ) + + +@pytest.mark.asyncio +async def test_async_batch_annotate_images_flattened_error_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.async_batch_annotate_images( + image_annotator.AsyncBatchAnnotateImagesRequest(), + requests=[ + image_annotator.AnnotateImageRequest( + image=image_annotator.Image(content=b"content_blob") + ) + ], + output_config=image_annotator.OutputConfig( + gcs_destination=image_annotator.GcsDestination(uri="uri_value") + ), + ) + + +def test_async_batch_annotate_files( + transport: str = "grpc", request_type=image_annotator.AsyncBatchAnnotateFilesRequest +): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.async_batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.async_batch_annotate_files(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == image_annotator.AsyncBatchAnnotateFilesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_async_batch_annotate_files_from_dict(): + test_async_batch_annotate_files(request_type=dict) + + +@pytest.mark.asyncio +async def test_async_batch_annotate_files_async(transport: str = "grpc_asyncio"): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = image_annotator.AsyncBatchAnnotateFilesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.async_batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.async_batch_annotate_files(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_async_batch_annotate_files_flattened(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.async_batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.async_batch_annotate_files( + requests=[ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ] + + +def test_async_batch_annotate_files_flattened_error(): + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.async_batch_annotate_files( + image_annotator.AsyncBatchAnnotateFilesRequest(), + requests=[ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + +@pytest.mark.asyncio +async def test_async_batch_annotate_files_flattened_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.async_batch_annotate_files), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.async_batch_annotate_files( + requests=[ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].requests == [ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ] + + +@pytest.mark.asyncio +async def test_async_batch_annotate_files_flattened_error_async(): + client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.async_batch_annotate_files( + image_annotator.AsyncBatchAnnotateFilesRequest(), + requests=[ + image_annotator.AsyncAnnotateFileRequest( + input_config=image_annotator.InputConfig( + gcs_source=image_annotator.GcsSource(uri="uri_value") + ) + ) + ], + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageAnnotatorClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageAnnotatorClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = ImageAnnotatorClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ImageAnnotatorGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ImageAnnotatorGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.ImageAnnotatorGrpcTransport,) + + +def test_image_annotator_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.ImageAnnotatorTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_image_annotator_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.vision_v1p4beta1.services.image_annotator.transports.ImageAnnotatorTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ImageAnnotatorTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "batch_annotate_images", + "batch_annotate_files", + "async_batch_annotate_images", + "async_batch_annotate_files", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_image_annotator_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.vision_v1p4beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ImageAnnotatorTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +def test_image_annotator_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.vision_v1p4beta1.services.image_annotator.transports.ImageAnnotatorTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ImageAnnotatorTransport() + adc.assert_called_once() + + +def test_image_annotator_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + ImageAnnotatorClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id=None, + ) + + +def test_image_annotator_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.ImageAnnotatorGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +def test_image_annotator_host_no_port(): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vision.googleapis.com" + ), + ) + assert client._transport._host == "vision.googleapis.com:443" + + +def test_image_annotator_host_with_port(): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vision.googleapis.com:8000" + ), + ) + assert client._transport._host == "vision.googleapis.com:8000" + + +def test_image_annotator_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ImageAnnotatorGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +def test_image_annotator_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ImageAnnotatorGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +def test_image_annotator_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +def test_image_annotator_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_image_annotator_grpc_lro_client(): + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + transport = client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_image_annotator_grpc_lro_async_client(): + client = ImageAnnotatorAsyncClient( + credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + transport = client._client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.ImageAnnotatorTransport, "_prep_wrapped_messages" + ) as prep: + client = ImageAnnotatorClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ImageAnnotatorTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ImageAnnotatorClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/vision_v1p4beta1/test_product_search.py b/tests/unit/gapic/vision_v1p4beta1/test_product_search.py new file mode 100644 index 00000000..99f91b47 --- /dev/null +++ b/tests/unit/gapic/vision_v1p4beta1/test_product_search.py @@ -0,0 +1,5490 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.vision_v1p4beta1.services.product_search import ( + ProductSearchAsyncClient, +) +from google.cloud.vision_v1p4beta1.services.product_search import ProductSearchClient +from google.cloud.vision_v1p4beta1.services.product_search import pagers +from google.cloud.vision_v1p4beta1.services.product_search import transports +from google.cloud.vision_v1p4beta1.types import geometry +from google.cloud.vision_v1p4beta1.types import product_search_service +from google.longrunning import operations_pb2 +from google.oauth2 import service_account +from google.protobuf import any_pb2 as gp_any # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.rpc import status_pb2 as status # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ProductSearchClient._get_default_mtls_endpoint(None) is None + assert ( + ProductSearchClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + ProductSearchClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ProductSearchClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ProductSearchClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ProductSearchClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [ProductSearchClient, ProductSearchAsyncClient] +) +def test_product_search_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client._transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client._transport._credentials == creds + + assert client._transport._host == "vision.googleapis.com:443" + + +def test_product_search_client_get_transport_class(): + transport = ProductSearchClient.get_transport_class() + assert transport == transports.ProductSearchGrpcTransport + + transport = ProductSearchClient.get_transport_class("grpc") + assert transport == transports.ProductSearchGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), + ( + ProductSearchAsyncClient, + transports.ProductSearchGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + ProductSearchClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ProductSearchClient), +) +@mock.patch.object( + ProductSearchAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ProductSearchAsyncClient), +) +def test_product_search_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(ProductSearchClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(ProductSearchClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "true"), + ( + ProductSearchAsyncClient, + transports.ProductSearchGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc", "false"), + ( + ProductSearchAsyncClient, + transports.ProductSearchGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + ProductSearchClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ProductSearchClient), +) +@mock.patch.object( + ProductSearchAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ProductSearchAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_product_search_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), + ( + ProductSearchAsyncClient, + transports.ProductSearchGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_product_search_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ProductSearchClient, transports.ProductSearchGrpcTransport, "grpc"), + ( + ProductSearchAsyncClient, + transports.ProductSearchGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_product_search_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_product_search_client_client_options_from_dict(): + with mock.patch( + "google.cloud.vision_v1p4beta1.services.product_search.transports.ProductSearchGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = ProductSearchClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_create_product_set( + transport: str = "grpc", request_type=product_search_service.CreateProductSetRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + + response = client.create_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.CreateProductSetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_create_product_set_from_dict(): + test_create_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.CreateProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + ) + + response = await client.create_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_create_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateProductSetRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_product_set), "__call__" + ) as call: + call.return_value = product_search_service.ProductSet() + + client.create_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateProductSetRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + + await client.create_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_product_set( + parent="parent_value", + product_set=product_search_service.ProductSet(name="name_value"), + product_set_id="product_set_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].product_set == product_search_service.ProductSet( + name="name_value" + ) + + assert args[0].product_set_id == "product_set_id_value" + + +def test_create_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_product_set( + product_search_service.CreateProductSetRequest(), + parent="parent_value", + product_set=product_search_service.ProductSet(name="name_value"), + product_set_id="product_set_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_product_set( + parent="parent_value", + product_set=product_search_service.ProductSet(name="name_value"), + product_set_id="product_set_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].product_set == product_search_service.ProductSet( + name="name_value" + ) + + assert args[0].product_set_id == "product_set_id_value" + + +@pytest.mark.asyncio +async def test_create_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_product_set( + product_search_service.CreateProductSetRequest(), + parent="parent_value", + product_set=product_search_service.ProductSet(name="name_value"), + product_set_id="product_set_id_value", + ) + + +def test_list_product_sets( + transport: str = "grpc", request_type=product_search_service.ListProductSetsRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductSetsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.ListProductSetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductSetsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_product_sets_from_dict(): + test_list_product_sets(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_product_sets_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.ListProductSetsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductSetsResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductSetsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_product_sets_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductSetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_product_sets), "__call__" + ) as call: + call.return_value = product_search_service.ListProductSetsResponse() + + client.list_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_product_sets_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductSetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_product_sets), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductSetsResponse() + ) + + await client.list_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_product_sets_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductSetsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_product_sets(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_product_sets_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_product_sets( + product_search_service.ListProductSetsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_product_sets_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductSetsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductSetsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_product_sets(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_product_sets_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_product_sets( + product_search_service.ListProductSetsRequest(), parent="parent_value", + ) + + +def test_list_product_sets_pager(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_product_sets), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + next_page_token="abc", + ), + product_search_service.ListProductSetsResponse( + product_sets=[], next_page_token="def", + ), + product_search_service.ListProductSetsResponse( + product_sets=[product_search_service.ProductSet(),], + next_page_token="ghi", + ), + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_product_sets(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, product_search_service.ProductSet) for i in results) + + +def test_list_product_sets_pages(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_product_sets), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + next_page_token="abc", + ), + product_search_service.ListProductSetsResponse( + product_sets=[], next_page_token="def", + ), + product_search_service.ListProductSetsResponse( + product_sets=[product_search_service.ProductSet(),], + next_page_token="ghi", + ), + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + ), + RuntimeError, + ) + pages = list(client.list_product_sets(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_product_sets_async_pager(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_product_sets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + next_page_token="abc", + ), + product_search_service.ListProductSetsResponse( + product_sets=[], next_page_token="def", + ), + product_search_service.ListProductSetsResponse( + product_sets=[product_search_service.ProductSet(),], + next_page_token="ghi", + ), + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_product_sets(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, product_search_service.ProductSet) for i in responses) + + +@pytest.mark.asyncio +async def test_list_product_sets_async_pages(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_product_sets), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + next_page_token="abc", + ), + product_search_service.ListProductSetsResponse( + product_sets=[], next_page_token="def", + ), + product_search_service.ListProductSetsResponse( + product_sets=[product_search_service.ProductSet(),], + next_page_token="ghi", + ), + product_search_service.ListProductSetsResponse( + product_sets=[ + product_search_service.ProductSet(), + product_search_service.ProductSet(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_product_sets(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_product_set( + transport: str = "grpc", request_type=product_search_service.GetProductSetRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product_set), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + + response = client.get_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.GetProductSetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_get_product_set_from_dict(): + test_get_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.GetProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + ) + + response = await client.get_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_get_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product_set), "__call__") as call: + call.return_value = product_search_service.ProductSet() + + client.get_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + + await client.get_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product_set), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_product_set( + product_search_service.GetProductSetRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_product_set( + product_search_service.GetProductSetRequest(), name="name_value", + ) + + +def test_update_product_set( + transport: str = "grpc", request_type=product_search_service.UpdateProductSetRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.update_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + + response = client.update_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.UpdateProductSetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_update_product_set_from_dict(): + test_update_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.UpdateProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet( + name="name_value", display_name="display_name_value", + ) + ) + + response = await client.update_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ProductSet) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + +def test_update_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.UpdateProductSetRequest() + request.product_set.name = "product_set.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.update_product_set), "__call__" + ) as call: + call.return_value = product_search_service.ProductSet() + + client.update_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "product_set.name=product_set.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.UpdateProductSetRequest() + request.product_set.name = "product_set.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + + await client.update_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "product_set.name=product_set.name/value",) in kw[ + "metadata" + ] + + +def test_update_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.update_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_product_set( + product_set=product_search_service.ProductSet(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].product_set == product_search_service.ProductSet( + name="name_value" + ) + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_product_set( + product_search_service.UpdateProductSetRequest(), + product_set=product_search_service.ProductSet(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ProductSet() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ProductSet() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_product_set( + product_set=product_search_service.ProductSet(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].product_set == product_search_service.ProductSet( + name="name_value" + ) + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_product_set( + product_search_service.UpdateProductSetRequest(), + product_set=product_search_service.ProductSet(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_product_set( + transport: str = "grpc", request_type=product_search_service.DeleteProductSetRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.DeleteProductSetRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_set_from_dict(): + test_delete_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.DeleteProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_product_set), "__call__" + ) as call: + call.return_value = None + + client.delete_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_product_set( + product_search_service.DeleteProductSetRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_product_set( + product_search_service.DeleteProductSetRequest(), name="name_value", + ) + + +def test_create_product( + transport: str = "grpc", request_type=product_search_service.CreateProductRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + + response = client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.CreateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_create_product_from_dict(): + test_create_product(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_product_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.CreateProductRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + ) + + response = await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_create_product_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateProductRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_product), "__call__") as call: + call.return_value = product_search_service.Product() + + client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_product_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateProductRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + + await client.create_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_product_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.create_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_product( + parent="parent_value", + product=product_search_service.Product(name="name_value"), + product_id="product_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].product == product_search_service.Product(name="name_value") + + assert args[0].product_id == "product_id_value" + + +def test_create_product_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_product( + product_search_service.CreateProductRequest(), + parent="parent_value", + product=product_search_service.Product(name="name_value"), + product_id="product_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_product_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_product( + parent="parent_value", + product=product_search_service.Product(name="name_value"), + product_id="product_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].product == product_search_service.Product(name="name_value") + + assert args[0].product_id == "product_id_value" + + +@pytest.mark.asyncio +async def test_create_product_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_product( + product_search_service.CreateProductRequest(), + parent="parent_value", + product=product_search_service.Product(name="name_value"), + product_id="product_id_value", + ) + + +def test_list_products( + transport: str = "grpc", request_type=product_search_service.ListProductsRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.ListProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_products_from_dict(): + test_list_products(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_products_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.ListProductsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_products_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_products), "__call__") as call: + call.return_value = product_search_service.ListProductsResponse() + + client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_products_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsResponse() + ) + + await client.list_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_products_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_products(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_products_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_products( + product_search_service.ListProductsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_products_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_products(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_products_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_products( + product_search_service.ListProductsRequest(), parent="parent_value", + ) + + +def test_list_products_pager(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_products), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_products(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, product_search_service.Product) for i in results) + + +def test_list_products_pages(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.list_products), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + pages = list(client.list_products(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_products_async_pager(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_products(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, product_search_service.Product) for i in responses) + + +@pytest.mark.asyncio +async def test_list_products_async_pages(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_products(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_product( + transport: str = "grpc", request_type=product_search_service.GetProductRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + + response = client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.GetProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_get_product_from_dict(): + test_get_product(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_product_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.GetProductRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + ) + + response = await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_get_product_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetProductRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product), "__call__") as call: + call.return_value = product_search_service.Product() + + client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_product_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetProductRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + + await client.get_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_product_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.get_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_product(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_product_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_product( + product_search_service.GetProductRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_product_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_product(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_product_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_product( + product_search_service.GetProductRequest(), name="name_value", + ) + + +def test_update_product( + transport: str = "grpc", request_type=product_search_service.UpdateProductRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + + response = client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.UpdateProductRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_update_product_from_dict(): + test_update_product(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_product_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.UpdateProductRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product( + name="name_value", + display_name="display_name_value", + description="description_value", + product_category="product_category_value", + ) + ) + + response = await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.Product) + + assert response.name == "name_value" + + assert response.display_name == "display_name_value" + + assert response.description == "description_value" + + assert response.product_category == "product_category_value" + + +def test_update_product_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.UpdateProductRequest() + request.product.name = "product.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_product), "__call__") as call: + call.return_value = product_search_service.Product() + + client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "product.name=product.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_product_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.UpdateProductRequest() + request.product.name = "product.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + + await client.update_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "product.name=product.name/value",) in kw[ + "metadata" + ] + + +def test_update_product_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.update_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_product( + product=product_search_service.Product(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].product == product_search_service.Product(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_product_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_product( + product_search_service.UpdateProductRequest(), + product=product_search_service.Product(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_product_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.update_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.Product() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.Product() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_product( + product=product_search_service.Product(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].product == product_search_service.Product(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_product_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_product( + product_search_service.UpdateProductRequest(), + product=product_search_service.Product(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_product( + transport: str = "grpc", request_type=product_search_service.DeleteProductRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.DeleteProductRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_from_dict(): + test_delete_product(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_product_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.DeleteProductRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_product_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteProductRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_product), "__call__") as call: + call.return_value = None + + client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_product_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteProductRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_product(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_product_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.delete_product), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_product(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_product_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_product( + product_search_service.DeleteProductRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_product_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_product), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_product(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_product_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_product( + product_search_service.DeleteProductRequest(), name="name_value", + ) + + +def test_create_reference_image( + transport: str = "grpc", + request_type=product_search_service.CreateReferenceImageRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage( + name="name_value", uri="uri_value", + ) + + response = client.create_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.CreateReferenceImageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ReferenceImage) + + assert response.name == "name_value" + + assert response.uri == "uri_value" + + +def test_create_reference_image_from_dict(): + test_create_reference_image(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_reference_image_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.CreateReferenceImageRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage(name="name_value", uri="uri_value",) + ) + + response = await client.create_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ReferenceImage) + + assert response.name == "name_value" + + assert response.uri == "uri_value" + + +def test_create_reference_image_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateReferenceImageRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_reference_image), "__call__" + ) as call: + call.return_value = product_search_service.ReferenceImage() + + client.create_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_reference_image_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.CreateReferenceImageRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_reference_image), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage() + ) + + await client.create_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_reference_image_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.create_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_reference_image( + parent="parent_value", + reference_image=product_search_service.ReferenceImage(name="name_value"), + reference_image_id="reference_image_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].reference_image == product_search_service.ReferenceImage( + name="name_value" + ) + + assert args[0].reference_image_id == "reference_image_id_value" + + +def test_create_reference_image_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_reference_image( + product_search_service.CreateReferenceImageRequest(), + parent="parent_value", + reference_image=product_search_service.ReferenceImage(name="name_value"), + reference_image_id="reference_image_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_reference_image_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.create_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_reference_image( + parent="parent_value", + reference_image=product_search_service.ReferenceImage(name="name_value"), + reference_image_id="reference_image_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].reference_image == product_search_service.ReferenceImage( + name="name_value" + ) + + assert args[0].reference_image_id == "reference_image_id_value" + + +@pytest.mark.asyncio +async def test_create_reference_image_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_reference_image( + product_search_service.CreateReferenceImageRequest(), + parent="parent_value", + reference_image=product_search_service.ReferenceImage(name="name_value"), + reference_image_id="reference_image_id_value", + ) + + +def test_delete_reference_image( + transport: str = "grpc", + request_type=product_search_service.DeleteReferenceImageRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.DeleteReferenceImageRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_reference_image_from_dict(): + test_delete_reference_image(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_reference_image_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.DeleteReferenceImageRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_reference_image_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteReferenceImageRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_reference_image), "__call__" + ) as call: + call.return_value = None + + client.delete_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_reference_image_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.DeleteReferenceImageRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_reference_image), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_reference_image_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.delete_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_reference_image(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_reference_image_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_reference_image( + product_search_service.DeleteReferenceImageRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_reference_image_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.delete_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_reference_image(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_reference_image_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_reference_image( + product_search_service.DeleteReferenceImageRequest(), name="name_value", + ) + + +def test_list_reference_images( + transport: str = "grpc", + request_type=product_search_service.ListReferenceImagesRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_reference_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListReferenceImagesResponse( + page_size=951, next_page_token="next_page_token_value", + ) + + response = client.list_reference_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.ListReferenceImagesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReferenceImagesPager) + + assert response.page_size == 951 + + assert response.next_page_token == "next_page_token_value" + + +def test_list_reference_images_from_dict(): + test_list_reference_images(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_reference_images_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.ListReferenceImagesRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_reference_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListReferenceImagesResponse( + page_size=951, next_page_token="next_page_token_value", + ) + ) + + response = await client.list_reference_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReferenceImagesAsyncPager) + + assert response.page_size == 951 + + assert response.next_page_token == "next_page_token_value" + + +def test_list_reference_images_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListReferenceImagesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_reference_images), "__call__" + ) as call: + call.return_value = product_search_service.ListReferenceImagesResponse() + + client.list_reference_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_reference_images_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListReferenceImagesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_reference_images), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListReferenceImagesResponse() + ) + + await client.list_reference_images(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_reference_images_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_reference_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListReferenceImagesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_reference_images(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_reference_images_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_reference_images( + product_search_service.ListReferenceImagesRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_reference_images_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_reference_images), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListReferenceImagesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListReferenceImagesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_reference_images(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_reference_images_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_reference_images( + product_search_service.ListReferenceImagesRequest(), parent="parent_value", + ) + + +def test_list_reference_images_pager(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_reference_images), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + next_page_token="abc", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[], next_page_token="def", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[product_search_service.ReferenceImage(),], + next_page_token="ghi", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_reference_images(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all( + isinstance(i, product_search_service.ReferenceImage) for i in results + ) + + +def test_list_reference_images_pages(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_reference_images), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + next_page_token="abc", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[], next_page_token="def", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[product_search_service.ReferenceImage(),], + next_page_token="ghi", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + ), + RuntimeError, + ) + pages = list(client.list_reference_images(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_reference_images_async_pager(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_reference_images), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + next_page_token="abc", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[], next_page_token="def", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[product_search_service.ReferenceImage(),], + next_page_token="ghi", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_reference_images(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, product_search_service.ReferenceImage) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_reference_images_async_pages(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_reference_images), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + next_page_token="abc", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[], next_page_token="def", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[product_search_service.ReferenceImage(),], + next_page_token="ghi", + ), + product_search_service.ListReferenceImagesResponse( + reference_images=[ + product_search_service.ReferenceImage(), + product_search_service.ReferenceImage(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_reference_images(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_reference_image( + transport: str = "grpc", + request_type=product_search_service.GetReferenceImageRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage( + name="name_value", uri="uri_value", + ) + + response = client.get_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.GetReferenceImageRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ReferenceImage) + + assert response.name == "name_value" + + assert response.uri == "uri_value" + + +def test_get_reference_image_from_dict(): + test_get_reference_image(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_reference_image_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.GetReferenceImageRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage(name="name_value", uri="uri_value",) + ) + + response = await client.get_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, product_search_service.ReferenceImage) + + assert response.name == "name_value" + + assert response.uri == "uri_value" + + +def test_get_reference_image_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetReferenceImageRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_reference_image), "__call__" + ) as call: + call.return_value = product_search_service.ReferenceImage() + + client.get_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_reference_image_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.GetReferenceImageRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_reference_image), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage() + ) + + await client.get_reference_image(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_reference_image_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.get_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_reference_image(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_reference_image_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_reference_image( + product_search_service.GetReferenceImageRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_reference_image_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.get_reference_image), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ReferenceImage() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ReferenceImage() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_reference_image(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_reference_image_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_reference_image( + product_search_service.GetReferenceImageRequest(), name="name_value", + ) + + +def test_add_product_to_product_set( + transport: str = "grpc", + request_type=product_search_service.AddProductToProductSetRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.add_product_to_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.add_product_to_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.AddProductToProductSetRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_add_product_to_product_set_from_dict(): + test_add_product_to_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_add_product_to_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.AddProductToProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.add_product_to_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.add_product_to_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_add_product_to_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.AddProductToProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.add_product_to_product_set), "__call__" + ) as call: + call.return_value = None + + client.add_product_to_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_add_product_to_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.AddProductToProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.add_product_to_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.add_product_to_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_add_product_to_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.add_product_to_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_product_to_product_set( + name="name_value", product="product_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].product == "product_value" + + +def test_add_product_to_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_product_to_product_set( + product_search_service.AddProductToProductSetRequest(), + name="name_value", + product="product_value", + ) + + +@pytest.mark.asyncio +async def test_add_product_to_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.add_product_to_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_product_to_product_set( + name="name_value", product="product_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].product == "product_value" + + +@pytest.mark.asyncio +async def test_add_product_to_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_product_to_product_set( + product_search_service.AddProductToProductSetRequest(), + name="name_value", + product="product_value", + ) + + +def test_remove_product_from_product_set( + transport: str = "grpc", + request_type=product_search_service.RemoveProductFromProductSetRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.remove_product_from_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.remove_product_from_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.RemoveProductFromProductSetRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_remove_product_from_product_set_from_dict(): + test_remove_product_from_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_remove_product_from_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.RemoveProductFromProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.remove_product_from_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.remove_product_from_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_remove_product_from_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.RemoveProductFromProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.remove_product_from_product_set), "__call__" + ) as call: + call.return_value = None + + client.remove_product_from_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_remove_product_from_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.RemoveProductFromProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.remove_product_from_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.remove_product_from_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_remove_product_from_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.remove_product_from_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.remove_product_from_product_set( + name="name_value", product="product_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].product == "product_value" + + +def test_remove_product_from_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.remove_product_from_product_set( + product_search_service.RemoveProductFromProductSetRequest(), + name="name_value", + product="product_value", + ) + + +@pytest.mark.asyncio +async def test_remove_product_from_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.remove_product_from_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.remove_product_from_product_set( + name="name_value", product="product_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + assert args[0].product == "product_value" + + +@pytest.mark.asyncio +async def test_remove_product_from_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.remove_product_from_product_set( + product_search_service.RemoveProductFromProductSetRequest(), + name="name_value", + product="product_value", + ) + + +def test_list_products_in_product_set( + transport: str = "grpc", + request_type=product_search_service.ListProductsInProductSetRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_products_in_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsInProductSetResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_products_in_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.ListProductsInProductSetRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsInProductSetPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_products_in_product_set_from_dict(): + test_list_products_in_product_set(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.ListProductsInProductSetRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products_in_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsInProductSetResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_products_in_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProductsInProductSetAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_products_in_product_set_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductsInProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_products_in_product_set), "__call__" + ) as call: + call.return_value = product_search_service.ListProductsInProductSetResponse() + + client.list_products_in_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ListProductsInProductSetRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products_in_product_set), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsInProductSetResponse() + ) + + await client.list_products_in_product_set(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_list_products_in_product_set_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_products_in_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsInProductSetResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_products_in_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_list_products_in_product_set_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_products_in_product_set( + product_search_service.ListProductsInProductSetRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products_in_product_set), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = product_search_service.ListProductsInProductSetResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + product_search_service.ListProductsInProductSetResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_products_in_product_set(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_products_in_product_set( + product_search_service.ListProductsInProductSetRequest(), name="name_value", + ) + + +def test_list_products_in_product_set_pager(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_products_in_product_set), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsInProductSetResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsInProductSetResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), + ) + pager = client.list_products_in_product_set(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, product_search_service.Product) for i in results) + + +def test_list_products_in_product_set_pages(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.list_products_in_product_set), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsInProductSetResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsInProductSetResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + pages = list(client.list_products_in_product_set(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_async_pager(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products_in_product_set), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsInProductSetResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsInProductSetResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_products_in_product_set(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, product_search_service.Product) for i in responses) + + +@pytest.mark.asyncio +async def test_list_products_in_product_set_async_pages(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.list_products_in_product_set), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + product_search_service.Product(), + ], + next_page_token="abc", + ), + product_search_service.ListProductsInProductSetResponse( + products=[], next_page_token="def", + ), + product_search_service.ListProductsInProductSetResponse( + products=[product_search_service.Product(),], next_page_token="ghi", + ), + product_search_service.ListProductsInProductSetResponse( + products=[ + product_search_service.Product(), + product_search_service.Product(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_products_in_product_set(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_import_product_sets( + transport: str = "grpc", + request_type=product_search_service.ImportProductSetsRequest, +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.import_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.import_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.ImportProductSetsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_product_sets_from_dict(): + test_import_product_sets(request_type=dict) + + +@pytest.mark.asyncio +async def test_import_product_sets_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.ImportProductSetsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.import_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.import_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_import_product_sets_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ImportProductSetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.import_product_sets), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + + client.import_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_import_product_sets_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.ImportProductSetsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.import_product_sets), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + + await client.import_product_sets(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_import_product_sets_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._transport.import_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.import_product_sets( + parent="parent_value", + input_config=product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[ + 0 + ].input_config == product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ) + + +def test_import_product_sets_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.import_product_sets( + product_search_service.ImportProductSetsRequest(), + parent="parent_value", + input_config=product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ), + ) + + +@pytest.mark.asyncio +async def test_import_product_sets_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.import_product_sets), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.import_product_sets( + parent="parent_value", + input_config=product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[ + 0 + ].input_config == product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ) + + +@pytest.mark.asyncio +async def test_import_product_sets_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.import_product_sets( + product_search_service.ImportProductSetsRequest(), + parent="parent_value", + input_config=product_search_service.ImportProductSetsInputConfig( + gcs_source=product_search_service.ImportProductSetsGcsSource( + csv_file_uri="csv_file_uri_value" + ) + ), + ) + + +def test_purge_products( + transport: str = "grpc", request_type=product_search_service.PurgeProductsRequest +): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.purge_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + + response = client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == product_search_service.PurgeProductsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_products_from_dict(): + test_purge_products(request_type=dict) + + +@pytest.mark.asyncio +async def test_purge_products_async(transport: str = "grpc_asyncio"): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = product_search_service.PurgeProductsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.purge_products), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + + response = await client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_purge_products_field_headers(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.PurgeProductsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.purge_products), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + + client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_purge_products_field_headers_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = product_search_service.PurgeProductsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.purge_products), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + + await client.purge_products(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_purge_products_flattened(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client._transport.purge_products), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.purge_products(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_purge_products_flattened_error(): + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.purge_products( + product_search_service.PurgeProductsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_purge_products_flattened_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client._client._transport.purge_products), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.purge_products(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_purge_products_flattened_error_async(): + client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.purge_products( + product_search_service.PurgeProductsRequest(), parent="parent_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProductSearchGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProductSearchGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductSearchClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProductSearchGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProductSearchClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductSearchGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = ProductSearchClient(transport=transport) + assert client._transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProductSearchGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ProductSearchGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client._transport, transports.ProductSearchGrpcTransport,) + + +def test_product_search_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.ProductSearchTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_product_search_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.vision_v1p4beta1.services.product_search.transports.ProductSearchTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ProductSearchTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_product_set", + "list_product_sets", + "get_product_set", + "update_product_set", + "delete_product_set", + "create_product", + "list_products", + "get_product", + "update_product", + "delete_product", + "create_reference_image", + "delete_reference_image", + "list_reference_images", + "get_reference_image", + "add_product_to_product_set", + "remove_product_from_product_set", + "list_products_in_product_set", + "import_product_sets", + "purge_products", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + +def test_product_search_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.vision_v1p4beta1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ProductSearchTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +def test_product_search_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.vision_v1p4beta1.services.product_search.transports.ProductSearchTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.ProductSearchTransport() + adc.assert_called_once() + + +def test_product_search_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + ProductSearchClient() + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id=None, + ) + + +def test_product_search_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.ProductSearchGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +def test_product_search_host_no_port(): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vision.googleapis.com" + ), + ) + assert client._transport._host == "vision.googleapis.com:443" + + +def test_product_search_host_with_port(): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vision.googleapis.com:8000" + ), + ) + assert client._transport._host == "vision.googleapis.com:8000" + + +def test_product_search_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ProductSearchGrpcTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +def test_product_search_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.ProductSearchGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + ], +) +def test_product_search_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + ], +) +def test_product_search_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_product_search_grpc_lro_client(): + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), transport="grpc", + ) + transport = client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_product_search_grpc_lro_async_client(): + client = ProductSearchAsyncClient( + credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + ) + transport = client._client._transport + + # Ensure that we have a api-core operations client. + assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_product_path(): + project = "squid" + location = "clam" + product = "whelk" + + expected = "projects/{project}/locations/{location}/products/{product}".format( + project=project, location=location, product=product, + ) + actual = ProductSearchClient.product_path(project, location, product) + assert expected == actual + + +def test_parse_product_path(): + expected = { + "project": "octopus", + "location": "oyster", + "product": "nudibranch", + } + path = ProductSearchClient.product_path(**expected) + + # Check that the path construction is reversible. + actual = ProductSearchClient.parse_product_path(path) + assert expected == actual + + +def test_product_set_path(): + project = "squid" + location = "clam" + product_set = "whelk" + + expected = "projects/{project}/locations/{location}/productSets/{product_set}".format( + project=project, location=location, product_set=product_set, + ) + actual = ProductSearchClient.product_set_path(project, location, product_set) + assert expected == actual + + +def test_parse_product_set_path(): + expected = { + "project": "octopus", + "location": "oyster", + "product_set": "nudibranch", + } + path = ProductSearchClient.product_set_path(**expected) + + # Check that the path construction is reversible. + actual = ProductSearchClient.parse_product_set_path(path) + assert expected == actual + + +def test_reference_image_path(): + project = "squid" + location = "clam" + product = "whelk" + reference_image = "octopus" + + expected = "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( + project=project, + location=location, + product=product, + reference_image=reference_image, + ) + actual = ProductSearchClient.reference_image_path( + project, location, product, reference_image + ) + assert expected == actual + + +def test_parse_reference_image_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "product": "cuttlefish", + "reference_image": "mussel", + } + path = ProductSearchClient.reference_image_path(**expected) + + # Check that the path construction is reversible. + actual = ProductSearchClient.parse_reference_image_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.ProductSearchTransport, "_prep_wrapped_messages" + ) as prep: + client = ProductSearchClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ProductSearchTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ProductSearchClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/test_decorators.py b/tests/unit/test_decorators.py index c78707b2..2e6125d4 100644 --- a/tests/unit/test_decorators.py +++ b/tests/unit/test_decorators.py @@ -38,7 +38,7 @@ class A(object): def test_with_enums(self): class A(object): - enums = vision.enums + Feature = vision.Feature # There should not be detection methods yet. assert not hasattr(A, "face_detection") @@ -55,7 +55,7 @@ class A(object): class SingleFeatureMethodTests(unittest.TestCase): @mock.patch.object(vision.ImageAnnotatorClient, "annotate_image") def test_runs_generic_single_image(self, ai): - ai.return_value = vision.types.AnnotateImageResponse() + ai.return_value = vision.AnnotateImageResponse() # Prove that other aspects of the AnnotateImageRequest, such as the # image context, will be preserved. @@ -68,14 +68,14 @@ def test_runs_generic_single_image(self, ai): response = client.face_detection( image, image_context=SENTINEL, max_results=max_results ) - assert isinstance(response, vision.types.AnnotateImageResponse) + assert isinstance(response, vision.AnnotateImageResponse) # Assert that the single-image method was called as expected. ai.assert_called_once_with( { "features": [ { - "type": vision.enums.Feature.Type.FACE_DETECTION, + "type_": vision.Feature.Type.FACE_DETECTION, "max_results": max_results, } ], @@ -84,11 +84,12 @@ def test_runs_generic_single_image(self, ai): }, retry=None, timeout=None, + metadata=(), ) @mock.patch.object(vision.ImageAnnotatorClient, "annotate_image") def test_runs_generic_single_image_without_max_results(self, ai): - ai.return_value = vision.types.AnnotateImageResponse() + ai.return_value = vision.AnnotateImageResponse() # Prove that other aspects of the AnnotateImageRequest, such as the # image context, will be preserved. @@ -98,15 +99,16 @@ def test_runs_generic_single_image_without_max_results(self, ai): client = vision.ImageAnnotatorClient(credentials=mock.Mock(spec=Credentials)) image = {"source": {"image_uri": "gs://my-test-bucket/image.jpg"}} response = client.face_detection(image, image_context=SENTINEL) - assert isinstance(response, vision.types.AnnotateImageResponse) + assert isinstance(response, vision.AnnotateImageResponse) # Assert that the single-image method was called as expected. ai.assert_called_once_with( { - "features": [{"type": vision.enums.Feature.Type.FACE_DETECTION}], + "features": [{"type_": vision.Feature.Type.FACE_DETECTION}], "image": image, "image_context": SENTINEL, }, retry=None, timeout=None, + metadata=(), ) diff --git a/tests/unit/test_helpers.py b/tests/unit/test_helpers.py index 97239a14..cc46ca1e 100644 --- a/tests/unit/test_helpers.py +++ b/tests/unit/test_helpers.py @@ -13,6 +13,7 @@ # limitations under the License. from __future__ import absolute_import +import builtins import io import unittest @@ -21,7 +22,7 @@ from google.auth.credentials import Credentials from google.cloud.vision_v1 import ImageAnnotatorClient -from google.cloud.vision_v1 import types +import google.cloud.vision_v1 as vision_v1 class TestSingleImageHelper(unittest.TestCase): @@ -32,8 +33,8 @@ def setUp(self): @mock.patch.object(ImageAnnotatorClient, "batch_annotate_images") def test_all_features_default(self, batch_annotate): # Set up an image annotation request with no features. - image = types.Image(source={"image_uri": "http://foo.com/img.jpg"}) - request = types.AnnotateImageRequest(image=image) + image = vision_v1.Image(source={"image_uri": "http://foo.com/img.jpg"}) + request = vision_v1.AnnotateImageRequest(image=image) assert not request.features # Perform the single image request. @@ -44,24 +45,24 @@ def test_all_features_default(self, batch_annotate): _, args, kwargs = batch_annotate.mock_calls[0] # Only a single request object should be sent. - assert len(args[0]) == 1 + assert len(kwargs["requests"]) == 1 # Evalute the request object to ensure it looks correct. - request_sent = args[0][0] + request_sent = kwargs["requests"][0] all_features = self.client._get_all_features() - assert request_sent.image is request.image + assert request_sent.image == request.image assert len(request_sent.features) == len(all_features) @mock.patch.object(ImageAnnotatorClient, "batch_annotate_images") def test_explicit_features(self, batch_annotate): # Set up an image annotation request with no features. - image = types.Image(source={"image_uri": "http://foo.com/img.jpg"}) - request = types.AnnotateImageRequest( + image = vision_v1.Image(source={"image_uri": "http://foo.com/img.jpg"}) + request = vision_v1.AnnotateImageRequest( image=image, features=[ - types.Feature(type=1), - types.Feature(type=2), - types.Feature(type=3), + vision_v1.Feature(type_=1), + vision_v1.Feature(type_=2), + vision_v1.Feature(type_=3), ], ) @@ -73,14 +74,14 @@ def test_explicit_features(self, batch_annotate): _, args, kwargs = batch_annotate.mock_calls[0] # Only a single request object should be sent. - assert len(args[0]) == 1 + assert len(kwargs["requests"]) == 1 # Evalute the request object to ensure it looks correct. - request_sent = args[0][0] - assert request_sent.image is request.image + request_sent = kwargs["requests"][0] + assert request_sent.image == request.image assert len(request_sent.features) == 3 for feature, i in zip(request_sent.features, range(1, 4)): - assert feature.type == i + assert feature.type_ == i assert feature.max_results == 0 @mock.patch.object(ImageAnnotatorClient, "batch_annotate_images") @@ -96,14 +97,14 @@ def test_image_file_handler(self, batch_annotate): _, args, kwargs = batch_annotate.mock_calls[0] # Only a single request object should be sent. - assert len(args[0]) == 1 + assert len(kwargs["requests"]) == 1 # Evalute the request object to ensure it looks correct. - request_sent = args[0][0] + request_sent = kwargs["requests"][0] assert request_sent["image"]["content"] == b"bogus==" @mock.patch.object(ImageAnnotatorClient, "batch_annotate_images") - @mock.patch.object(io, "open") + @mock.patch.object(builtins, "open") def test_image_filename(self, io_open, batch_annotate): # Make io.open send back a mock with a read method. file_ = mock.MagicMock(spec=io.BytesIO) @@ -122,8 +123,8 @@ def test_image_filename(self, io_open, batch_annotate): _, args, kwargs = batch_annotate.mock_calls[0] # Only a single request object should be sent. - assert len(args[0]) == 1 + assert len(kwargs["requests"]) == 1 # Evalute the request object to ensure it looks correct. - request_sent = args[0][0] + request_sent = kwargs["requests"][0] assert request_sent["image"]["content"] == b"imagefile=="