diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml new file mode 100644 index 00000000..da616c91 --- /dev/null +++ b/.github/.OwlBot.lock.yaml @@ -0,0 +1,3 @@ +docker: + image: gcr.io/repo-automation-bots/owlbot-python:latest + digest: sha256:c66ba3c8d7bc8566f47df841f98cd0097b28fff0b1864c86f5817f4c8c3e8600 diff --git a/.github/.OwlBot.yaml b/.github/.OwlBot.yaml new file mode 100644 index 00000000..4628ccc9 --- /dev/null +++ b/.github/.OwlBot.yaml @@ -0,0 +1,26 @@ +# Copyright 2021 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. + +docker: + image: gcr.io/repo-automation-bots/owlbot-python:latest + +deep-remove-regex: + - /owl-bot-staging + +deep-copy-regex: + - source: /google/cloud/vision/(v.*)/.*-py/(.*) + dest: /owl-bot-staging/$1/$2 + +begin-after-commit-hash: e0ea8b51f30e2ff6104abd1e4c8d1eb67078c86a + diff --git a/.github/header-checker-lint.yml b/.github/header-checker-lint.yml index fc281c05..6fe78aa7 100644 --- a/.github/header-checker-lint.yml +++ b/.github/header-checker-lint.yml @@ -1,6 +1,6 @@ {"allowedCopyrightHolders": ["Google LLC"], "allowedLicenses": ["Apache-2.0", "MIT", "BSD-3"], - "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt"], + "ignoreFiles": ["**/requirements.txt", "**/requirements-test.txt", "**/__init__.py", "samples/**/constraints.txt", "samples/**/constraints-test.txt"], "sourceFileExtensions": [ "ts", "js", diff --git a/.kokoro/release.sh b/.kokoro/release.sh index 345a8dc0..15990123 100755 --- a/.kokoro/release.sh +++ b/.kokoro/release.sh @@ -26,7 +26,7 @@ python3 -m pip install --upgrade twine wheel setuptools export PYTHONUNBUFFERED=1 # Move into the package, build the distribution and upload. -TWINE_PASSWORD=$(cat "${KOKORO_KEYSTORE_DIR}/73713_google_cloud_pypi_password") +TWINE_PASSWORD=$(cat "${KOKORO_GFILE_DIR}/secret_manager/google-cloud-pypi-token") cd github/python-vision python3 setup.py sdist bdist_wheel -twine upload --username gcloudpypi --password "${TWINE_PASSWORD}" dist/* +twine upload --username __token__ --password "${TWINE_PASSWORD}" dist/* diff --git a/.kokoro/release/common.cfg b/.kokoro/release/common.cfg index f30aa774..de8ffad4 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,18 +23,8 @@ env_vars: { value: "github/python-vision/.kokoro/release.sh" } -# Fetch PyPI password -before_action { - fetch_keystore { - keystore_resource { - keystore_config_id: 73713 - keyname: "google_cloud_pypi_password" - } - } -} - # 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 + value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem,google-cloud-pypi-token" +} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8912e9b5..4f00c7cf 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -26,6 +26,6 @@ repos: hooks: - id: black - repo: https://gitlab.com/pycqa/flake8 - rev: 3.9.0 + rev: 3.9.2 hooks: - id: flake8 diff --git a/.repo-metadata.json b/.repo-metadata.json index 830b1e51..06c44beb 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -6,6 +6,7 @@ "issue_tracker": "https://issuetracker.google.com/issues?q=status:open%20componentid:187174", "release_level": "ga", "language": "python", + "library_type": "GAPIC_COMBO", "repo": "googleapis/python-vision", "distribution_name": "google-cloud-vision", "api_id": "vision.googleapis.com", diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cc6c4ef..05822f1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ [1]: https://pypi.org/project/google-cloud-vision/#history +### [2.3.2](https://www.github.com/googleapis/python-vision/compare/v2.3.1...v2.3.2) (2021-06-02) + + +### Bug Fixes + +* **deps:** add packaging requirement ([#147](https://www.github.com/googleapis/python-vision/issues/147)) ([41b88bd](https://www.github.com/googleapis/python-vision/commit/41b88bd482d4d6ec76fc6efc99aa9343496faf72)) + ### [2.3.1](https://www.github.com/googleapis/python-vision/compare/v2.3.0...v2.3.1) (2021-04-13) diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 539e30e6..2ce96118 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -160,21 +160,7 @@ Running System Tests auth settings and change some configuration in your project to run all the tests. -- System tests will be run against an actual project and - so you'll need to provide some environment variables to facilitate - authentication to your project: - - - ``GOOGLE_APPLICATION_CREDENTIALS``: The path to a JSON key file; - Such a file can be downloaded directly from the developer's console by clicking - "Generate new JSON key". See private key - `docs `__ - for more details. - -- Once you have downloaded your json keys, set the environment variable - ``GOOGLE_APPLICATION_CREDENTIALS`` to the absolute path of the json file:: - - $ export GOOGLE_APPLICATION_CREDENTIALS="/Users//path/to/app_credentials.json" - +- System tests will be run against an actual project. You should use local credentials from gcloud when possible. See `Best practices for application authentication `__. Some tests require a service account. For those tests see `Authenticating as a service account `__. ************* Test Coverage diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..8b58ae9c --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +# Security Policy + +To report a security issue, please use [g.co/vulnz](https://g.co/vulnz). + +The Google Security Team will respond within 5 working days of your report on g.co/vulnz. + +We use g.co/vulnz for our intake, and do coordination and disclosure here using GitHub Security Advisory to privately discuss and fix the issue. diff --git a/docs/conf.py b/docs/conf.py index b196e752..30dbcf00 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -363,6 +363,7 @@ "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,), "grpc": ("https://grpc.github.io/grpc/python/", None), "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), } diff --git a/docs/multiprocessing.rst b/docs/multiprocessing.rst index 1cb29d4c..536d17b2 100644 --- a/docs/multiprocessing.rst +++ b/docs/multiprocessing.rst @@ -1,7 +1,7 @@ .. note:: - Because this client uses :mod:`grpcio` library, it is safe to + Because this client uses :mod:`grpc` library, it is safe to share instances across threads. In multiprocessing scenarios, the best practice is to create client instances *after* the invocation of - :func:`os.fork` by :class:`multiprocessing.Pool` or + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or :class:`multiprocessing.Process`. diff --git a/docs/vision_v1/product_search.rst b/docs/vision_v1/product_search.rst index 64e5cd02..96f1c798 100644 --- a/docs/vision_v1/product_search.rst +++ b/docs/vision_v1/product_search.rst @@ -5,7 +5,6 @@ ProductSearch :members: :inherited-members: - .. automodule:: google.cloud.vision_v1.services.product_search.pagers :members: :inherited-members: diff --git a/docs/vision_v1p3beta1/product_search.rst b/docs/vision_v1p3beta1/product_search.rst index fd321a60..21e79602 100644 --- a/docs/vision_v1p3beta1/product_search.rst +++ b/docs/vision_v1p3beta1/product_search.rst @@ -5,7 +5,6 @@ ProductSearch :members: :inherited-members: - .. automodule:: google.cloud.vision_v1p3beta1.services.product_search.pagers :members: :inherited-members: diff --git a/docs/vision_v1p4beta1/product_search.rst b/docs/vision_v1p4beta1/product_search.rst index e46b54b0..895f0cba 100644 --- a/docs/vision_v1p4beta1/product_search.rst +++ b/docs/vision_v1p4beta1/product_search.rst @@ -5,7 +5,6 @@ ProductSearch :members: :inherited-members: - .. automodule:: google.cloud.vision_v1p4beta1.services.product_search.pagers :members: :inherited-members: diff --git a/google/cloud/vision_v1/__init__.py b/google/cloud/vision_v1/__init__.py index df7114a8..001f641a 100644 --- a/google/cloud/vision_v1/__init__.py +++ b/google/cloud/vision_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -19,7 +18,10 @@ from google.cloud.vision_helpers import VisionHelpers from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient +from .services.image_annotator import ImageAnnotatorAsyncClient from .services.product_search import ProductSearchClient +from .services.product_search import ProductSearchAsyncClient + from .types.geometry import BoundingPoly from .types.geometry import NormalizedVertex from .types.geometry import Position @@ -55,7 +57,6 @@ 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 @@ -64,6 +65,7 @@ from .types.image_annotator import SafeSearchAnnotation from .types.image_annotator import TextDetectionParams from .types.image_annotator import WebDetectionParams +from .types.image_annotator import Likelihood from .types.product_search import ProductSearchParams from .types.product_search import ProductSearchResults from .types.product_search_service import AddProductToProductSetRequest @@ -113,6 +115,8 @@ class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): __all__ = ( + "ImageAnnotatorAsyncClient", + "ProductSearchAsyncClient", "AddProductToProductSetRequest", "AnnotateFileRequest", "AnnotateFileResponse", @@ -152,6 +156,7 @@ class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): "GetReferenceImageRequest", "Image", "ImageAnnotationContext", + "ImageAnnotatorClient", "ImageContext", "ImageProperties", "ImageSource", @@ -198,5 +203,4 @@ class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): "WebDetection", "WebDetectionParams", "Word", - "ImageAnnotatorClient", ) diff --git a/google/cloud/vision_v1/proto/geometry.proto b/google/cloud/vision_v1/proto/geometry.proto deleted file mode 100644 index 376d2da3..00000000 --- a/google/cloud/vision_v1/proto/geometry.proto +++ /dev/null @@ -1,70 +0,0 @@ -// 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. - -syntax = "proto3"; - -package google.cloud.vision.v1; - -import "google/api/annotations.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1;vision"; -option java_multiple_files = true; -option java_outer_classname = "GeometryProto"; -option java_package = "com.google.cloud.vision.v1"; -option objc_class_prefix = "GCVN"; - -// A vertex represents a 2D point in the image. -// NOTE: the vertex coordinates are in the same scale as the original image. -message Vertex { - // X coordinate. - int32 x = 1; - - // Y coordinate. - int32 y = 2; -} - -// 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. -message NormalizedVertex { - // X coordinate. - float x = 1; - - // Y coordinate. - float y = 2; -} - -// A bounding polygon for the detected image annotation. -message BoundingPoly { - // The bounding polygon vertices. - repeated Vertex vertices = 1; - - // The bounding polygon normalized vertices. - repeated NormalizedVertex normalized_vertices = 2; -} - -// 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. -message Position { - // X coordinate. - float x = 1; - - // Y coordinate. - float y = 2; - - // Z coordinate (or depth). - float z = 3; -} diff --git a/google/cloud/vision_v1/proto/image_annotator.proto b/google/cloud/vision_v1/proto/image_annotator.proto deleted file mode 100644 index 3852bed7..00000000 --- a/google/cloud/vision_v1/proto/image_annotator.proto +++ /dev/null @@ -1,1073 +0,0 @@ -// 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. - -syntax = "proto3"; - -package google.cloud.vision.v1; - -import "google/api/annotations.proto"; -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; -import "google/cloud/vision/v1/geometry.proto"; -import "google/cloud/vision/v1/product_search.proto"; -import "google/cloud/vision/v1/text_annotation.proto"; -import "google/cloud/vision/v1/web_detection.proto"; -import "google/longrunning/operations.proto"; -import "google/protobuf/field_mask.proto"; -import "google/protobuf/timestamp.proto"; -import "google/rpc/status.proto"; -import "google/type/color.proto"; -import "google/type/latlng.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1;vision"; -option java_multiple_files = true; -option java_outer_classname = "ImageAnnotatorProto"; -option java_package = "com.google.cloud.vision.v1"; -option objc_class_prefix = "GCVN"; - -// 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 ImageAnnotator { - option (google.api.default_host) = "vision.googleapis.com"; - option (google.api.oauth_scopes) = - "https://www.googleapis.com/auth/cloud-platform," - "https://www.googleapis.com/auth/cloud-vision"; - - // Run image detection and annotation for a batch of images. - rpc BatchAnnotateImages(BatchAnnotateImagesRequest) - returns (BatchAnnotateImagesResponse) { - option (google.api.http) = { - post: "/v1/images:annotate" - body: "*" - additional_bindings { - post: "/v1/{parent=projects/*/locations/*}/images:annotate" - body: "*" - } - additional_bindings { - post: "/v1/{parent=projects/*}/images:annotate" - body: "*" - } - }; - option (google.api.method_signature) = "requests"; - } - - // 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. - rpc BatchAnnotateFiles(BatchAnnotateFilesRequest) - returns (BatchAnnotateFilesResponse) { - option (google.api.http) = { - post: "/v1/files:annotate" - body: "*" - additional_bindings { - post: "/v1/{parent=projects/*/locations/*}/files:annotate" - body: "*" - } - additional_bindings { - post: "/v1/{parent=projects/*}/files:annotate" - body: "*" - } - }; - option (google.api.method_signature) = "requests"; - } - - // 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. - rpc AsyncBatchAnnotateImages(AsyncBatchAnnotateImagesRequest) - returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v1/images:asyncBatchAnnotate" - body: "*" - additional_bindings { - post: "/v1/{parent=projects/*/locations/*}/images:asyncBatchAnnotate" - body: "*" - } - additional_bindings { - post: "/v1/{parent=projects/*}/images:asyncBatchAnnotate" - body: "*" - } - }; - option (google.api.method_signature) = "requests,output_config"; - option (google.longrunning.operation_info) = { - response_type: "AsyncBatchAnnotateImagesResponse" - metadata_type: "OperationMetadata" - }; - } - - // 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). - rpc AsyncBatchAnnotateFiles(AsyncBatchAnnotateFilesRequest) - returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v1/files:asyncBatchAnnotate" - body: "*" - additional_bindings { - post: "/v1/{parent=projects/*/locations/*}/files:asyncBatchAnnotate" - body: "*" - } - additional_bindings { - post: "/v1/{parent=projects/*}/files:asyncBatchAnnotate" - body: "*" - } - }; - option (google.api.method_signature) = "requests"; - option (google.longrunning.operation_info) = { - response_type: "AsyncBatchAnnotateFilesResponse" - metadata_type: "OperationMetadata" - }; - } -} - -// 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. -message Feature { - // Type of Google Cloud Vision API feature to be extracted. - enum Type { - // Unspecified feature type. - TYPE_UNSPECIFIED = 0; - - // Run face detection. - FACE_DETECTION = 1; - - // Run landmark detection. - LANDMARK_DETECTION = 2; - - // Run logo detection. - LOGO_DETECTION = 3; - - // Run label detection. - LABEL_DETECTION = 4; - - // 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. - TEXT_DETECTION = 5; - - // Run dense text document OCR. Takes precedence when both - // `DOCUMENT_TEXT_DETECTION` and `TEXT_DETECTION` are present. - DOCUMENT_TEXT_DETECTION = 11; - - // Run Safe Search to detect potentially unsafe - // or undesirable content. - SAFE_SEARCH_DETECTION = 6; - - // Compute a set of image properties, such as the - // image's dominant colors. - IMAGE_PROPERTIES = 7; - - // Run crop hints. - CROP_HINTS = 9; - - // Run web detection. - WEB_DETECTION = 10; - - // Run Product Search. - PRODUCT_SEARCH = 12; - - // Run localizer for object detection. - OBJECT_LOCALIZATION = 19; - } - - // The feature type. - Type type = 1; - - // Maximum number of results of this type. Does not apply to - // `TEXT_DETECTION`, `DOCUMENT_TEXT_DETECTION`, or `CROP_HINTS`. - int32 max_results = 2; - - // Model to use for the feature. - // Supported values: "builtin/stable" (the default if unset) and - // "builtin/latest". - string model = 3; -} - -// External image source (Google Cloud Storage or web URL image location). -message ImageSource { - // **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](https://cloud.google.com/storage/docs/reference-uris) for more info. - string gcs_image_uri = 1; - - // 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](https://cloud.google.com/storage/docs/reference-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. - string image_uri = 2; -} - -// Client image to perform Google Cloud Vision API tasks over. -message Image { - // 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. - // - // Currently, this field only works for BatchAnnotateImages requests. It does - // not work for AsyncBatchAnnotateImages requests. - bytes content = 1; - - // 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. - ImageSource source = 2; -} - -// A bucketized representation of likelihood, which is intended to give clients -// highly stable results across model upgrades. -enum Likelihood { - // Unknown likelihood. - UNKNOWN = 0; - - // It is very unlikely. - VERY_UNLIKELY = 1; - - // It is unlikely. - UNLIKELY = 2; - - // It is possible. - POSSIBLE = 3; - - // It is likely. - LIKELY = 4; - - // It is very likely. - VERY_LIKELY = 5; -} - -// A face annotation object contains the results of face detection. -message FaceAnnotation { - // A face-specific landmark (for example, a face feature). - message Landmark { - // 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. - enum Type { - // Unknown face landmark detected. Should not be filled. - UNKNOWN_LANDMARK = 0; - - // Left eye. - LEFT_EYE = 1; - - // Right eye. - RIGHT_EYE = 2; - - // Left of left eyebrow. - LEFT_OF_LEFT_EYEBROW = 3; - - // Right of left eyebrow. - RIGHT_OF_LEFT_EYEBROW = 4; - - // Left of right eyebrow. - LEFT_OF_RIGHT_EYEBROW = 5; - - // Right of right eyebrow. - RIGHT_OF_RIGHT_EYEBROW = 6; - - // Midpoint between eyes. - MIDPOINT_BETWEEN_EYES = 7; - - // Nose tip. - NOSE_TIP = 8; - - // Upper lip. - UPPER_LIP = 9; - - // Lower lip. - LOWER_LIP = 10; - - // Mouth left. - MOUTH_LEFT = 11; - - // Mouth right. - MOUTH_RIGHT = 12; - - // Mouth center. - MOUTH_CENTER = 13; - - // Nose, bottom right. - NOSE_BOTTOM_RIGHT = 14; - - // Nose, bottom left. - NOSE_BOTTOM_LEFT = 15; - - // Nose, bottom center. - NOSE_BOTTOM_CENTER = 16; - - // Left eye, top boundary. - LEFT_EYE_TOP_BOUNDARY = 17; - - // Left eye, right corner. - LEFT_EYE_RIGHT_CORNER = 18; - - // Left eye, bottom boundary. - LEFT_EYE_BOTTOM_BOUNDARY = 19; - - // Left eye, left corner. - LEFT_EYE_LEFT_CORNER = 20; - - // Right eye, top boundary. - RIGHT_EYE_TOP_BOUNDARY = 21; - - // Right eye, right corner. - RIGHT_EYE_RIGHT_CORNER = 22; - - // Right eye, bottom boundary. - RIGHT_EYE_BOTTOM_BOUNDARY = 23; - - // Right eye, left corner. - RIGHT_EYE_LEFT_CORNER = 24; - - // Left eyebrow, upper midpoint. - LEFT_EYEBROW_UPPER_MIDPOINT = 25; - - // Right eyebrow, upper midpoint. - RIGHT_EYEBROW_UPPER_MIDPOINT = 26; - - // Left ear tragion. - LEFT_EAR_TRAGION = 27; - - // Right ear tragion. - RIGHT_EAR_TRAGION = 28; - - // Left eye pupil. - LEFT_EYE_PUPIL = 29; - - // Right eye pupil. - RIGHT_EYE_PUPIL = 30; - - // Forehead glabella. - FOREHEAD_GLABELLA = 31; - - // Chin gnathion. - CHIN_GNATHION = 32; - - // Chin left gonion. - CHIN_LEFT_GONION = 33; - - // Chin right gonion. - CHIN_RIGHT_GONION = 34; - - // Left cheek center. - LEFT_CHEEK_CENTER = 35; - - // Right cheek center. - RIGHT_CHEEK_CENTER = 36; - } - - // Face landmark type. - Type type = 3; - - // Face landmark position. - Position position = 4; - } - - // 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. - BoundingPoly bounding_poly = 1; - - // 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. - BoundingPoly fd_bounding_poly = 2; - - // Detected face landmarks. - repeated Landmark landmarks = 3; - - // 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]. - float roll_angle = 4; - - // 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]. - float pan_angle = 5; - - // Pitch angle, which indicates the upwards/downwards angle that the face is - // pointing relative to the image's horizontal plane. Range [-180,180]. - float tilt_angle = 6; - - // Detection confidence. Range [0, 1]. - float detection_confidence = 7; - - // Face landmarking confidence. Range [0, 1]. - float landmarking_confidence = 8; - - // Joy likelihood. - Likelihood joy_likelihood = 9; - - // Sorrow likelihood. - Likelihood sorrow_likelihood = 10; - - // Anger likelihood. - Likelihood anger_likelihood = 11; - - // Surprise likelihood. - Likelihood surprise_likelihood = 12; - - // Under-exposed likelihood. - Likelihood under_exposed_likelihood = 13; - - // Blurred likelihood. - Likelihood blurred_likelihood = 14; - - // Headwear likelihood. - Likelihood headwear_likelihood = 15; -} - -// Detected entity location information. -message LocationInfo { - // lat/long location coordinates. - google.type.LatLng lat_lng = 1; -} - -// A `Property` consists of a user-supplied name/value pair. -message Property { - // Name of the property. - string name = 1; - - // Value of the property. - string value = 2; - - // Value of numeric properties. - uint64 uint64_value = 3; -} - -// Set of detected entity features. -message EntityAnnotation { - // Opaque entity ID. Some IDs may be available in - // [Google Knowledge Graph Search - // API](https://developers.google.com/knowledge-graph/). - string mid = 1; - - // The language code for the locale in which the entity textual - // `description` is expressed. - string locale = 2; - - // Entity textual description, expressed in its `locale` language. - string description = 3; - - // Overall score of the result. Range [0, 1]. - float score = 4; - - // **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]. - float confidence = 5 [deprecated = true]; - - // 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]. - float topicality = 6; - - // Image region to which this entity belongs. Not produced - // for `LABEL_DETECTION` features. - BoundingPoly bounding_poly = 7; - - // 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. - repeated LocationInfo locations = 8; - - // Some entities may have optional user-supplied `Property` (name/value) - // fields, such a score or string that qualifies the entity. - repeated Property properties = 9; -} - -// Set of detected objects with bounding boxes. -message LocalizedObjectAnnotation { - // Object ID that should align with EntityAnnotation mid. - string mid = 1; - - // 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. - string language_code = 2; - - // Object name, expressed in its `language_code` language. - string name = 3; - - // Score of the result. Range [0, 1]. - float score = 4; - - // Image region to which this object belongs. This must be populated. - BoundingPoly bounding_poly = 5; -} - -// Set of features pertaining to the image, computed by computer vision -// methods over safe-search verticals (for example, adult, spoof, medical, -// violence). -message SafeSearchAnnotation { - // Represents the adult content likelihood for the image. Adult content may - // contain elements such as nudity, pornographic images or cartoons, or - // sexual activities. - Likelihood adult = 1; - - // Spoof likelihood. The likelihood that an modification - // was made to the image's canonical version to make it appear - // funny or offensive. - Likelihood spoof = 2; - - // Likelihood that this is a medical image. - Likelihood medical = 3; - - // Likelihood that this image contains violent content. - Likelihood violence = 4; - - // 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. - Likelihood racy = 9; - - // Confidence of adult_score. Range [0, 1]. 0 means not confident, 1 means - // very confident. - float adult_confidence = 16 [deprecated = true]; - - // Confidence of spoof_score. Range [0, 1]. 0 means not confident, 1 means - // very confident. - float spoof_confidence = 18 [deprecated = true]; - - // Confidence of medical_score. Range [0, 1]. 0 means not confident, 1 means - // very confident. - float medical_confidence = 20 [deprecated = true]; - - // Confidence of violence_score. Range [0, 1]. 0 means not confident, 1 means - // very confident. - float violence_confidence = 22 [deprecated = true]; - - // Confidence of racy_score. Range [0, 1]. 0 means not confident, 1 means very - // confident. - float racy_confidence = 24 [deprecated = true]; - - // Confidence of nsfw_score. Range [0, 1]. 0 means not confident, 1 means very - // confident. - float nsfw_confidence = 26 [deprecated = true]; -} - -// Rectangle determined by min and max `LatLng` pairs. -message LatLongRect { - // Min lat/long pair. - google.type.LatLng min_lat_lng = 1; - - // Max lat/long pair. - google.type.LatLng max_lat_lng = 2; -} - -// Color information consists of RGB channels, score, and the fraction of -// the image that the color occupies in the image. -message ColorInfo { - // RGB components of the color. - google.type.Color color = 1; - - // Image-specific score for this color. Value in range [0, 1]. - float score = 2; - - // The fraction of pixels the color occupies in the image. - // Value in range [0, 1]. - float pixel_fraction = 3; -} - -// Set of dominant colors and their corresponding scores. -message DominantColorsAnnotation { - // RGB color values with their score and pixel fraction. - repeated ColorInfo colors = 1; -} - -// Stores image properties, such as dominant colors. -message ImageProperties { - // If present, dominant colors completed successfully. - DominantColorsAnnotation dominant_colors = 1; -} - -// Single crop hint that is used to generate a new crop when serving an image. -message CropHint { - // The bounding polygon for the crop region. The coordinates of the bounding - // box are in the original image's scale. - BoundingPoly bounding_poly = 1; - - // Confidence of this being a salient region. Range [0, 1]. - float confidence = 2; - - // Fraction of importance of this salient region with respect to the original - // image. - float importance_fraction = 3; -} - -// Set of crop hints that are used to generate new crops when serving images. -message CropHintsAnnotation { - // Crop hint results. - repeated CropHint crop_hints = 1; -} - -// Parameters for crop hints annotation request. -message CropHintsParams { - // 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. - repeated float aspect_ratios = 1; -} - -// Parameters for web detection request. -message WebDetectionParams { - // Whether to include results derived from the geo information in the image. - bool include_geo_results = 2; -} - -// Parameters for text detections. This is used to control TEXT_DETECTION and -// DOCUMENT_TEXT_DETECTION features. -message TextDetectionParams { - // By default, Cloud Vision API only includes confidence score for - // DOCUMENT_TEXT_DETECTION result. Set the flag to true to include confidence - // score for TEXT_DETECTION as well. - bool enable_text_detection_confidence_score = 9; -} - -// Image context and/or feature-specific parameters. -message ImageContext { - // Not used. - LatLongRect lat_long_rect = 1; - - // 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](https://cloud.google.com/vision/docs/languages). - repeated string language_hints = 2; - - // Parameters for crop hints annotation request. - CropHintsParams crop_hints_params = 4; - - // Parameters for product search. - ProductSearchParams product_search_params = 5; - - // Parameters for web detection. - WebDetectionParams web_detection_params = 6; - - // Parameters for text detection and document text detection. - TextDetectionParams text_detection_params = 12; -} - -// Request for performing Google Cloud Vision API tasks over a user-provided -// image, with user-requested features, and with context information. -message AnnotateImageRequest { - // The image to be processed. - Image image = 1; - - // Requested features. - repeated Feature features = 2; - - // Additional context that may accompany the image. - ImageContext image_context = 3; -} - -// If an image was produced from a file (e.g. a PDF), this message gives -// information about the source of that image. -message ImageAnnotationContext { - // The URI of the file used to produce the image. - string uri = 1; - - // If the file was a PDF or TIFF, this field gives the page number within - // the file used to produce the image. - int32 page_number = 2; -} - -// Response to an image annotation request. -message AnnotateImageResponse { - // If present, face detection has completed successfully. - repeated FaceAnnotation face_annotations = 1; - - // If present, landmark detection has completed successfully. - repeated EntityAnnotation landmark_annotations = 2; - - // If present, logo detection has completed successfully. - repeated EntityAnnotation logo_annotations = 3; - - // If present, label detection has completed successfully. - repeated EntityAnnotation label_annotations = 4; - - // If present, localized object detection has completed successfully. - // This will be sorted descending by confidence score. - repeated LocalizedObjectAnnotation localized_object_annotations = 22; - - // If present, text (OCR) detection has completed successfully. - repeated EntityAnnotation text_annotations = 5; - - // If present, text (OCR) detection or document (OCR) text detection has - // completed successfully. - // This annotation provides the structural hierarchy for the OCR detected - // text. - TextAnnotation full_text_annotation = 12; - - // If present, safe-search annotation has completed successfully. - SafeSearchAnnotation safe_search_annotation = 6; - - // If present, image properties were extracted successfully. - ImageProperties image_properties_annotation = 8; - - // If present, crop hints have completed successfully. - CropHintsAnnotation crop_hints_annotation = 11; - - // If present, web detection has completed successfully. - WebDetection web_detection = 13; - - // If present, product search has completed successfully. - ProductSearchResults product_search_results = 14; - - // 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. - google.rpc.Status error = 9; - - // If present, contextual information is needed to understand where this image - // comes from. - ImageAnnotationContext context = 21; -} - -// Multiple image annotation requests are batched into a single service call. -message BatchAnnotateImagesRequest { - // Required. Individual image annotation requests for this batch. - repeated AnnotateImageRequest requests = 1 - [(google.api.field_behavior) = REQUIRED]; - - // 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`. - string parent = 4; -} - -// Response to a batch image annotation request. -message BatchAnnotateImagesResponse { - // Individual responses to image annotation requests within the batch. - repeated AnnotateImageResponse responses = 1; -} - -// A request to annotate one single file, e.g. a PDF, TIFF or GIF file. -message AnnotateFileRequest { - // Required. Information about the input file. - InputConfig input_config = 1; - - // Required. Requested features. - repeated Feature features = 2; - - // Additional context that may accompany the image(s) in the file. - ImageContext image_context = 3; - - // 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. - repeated int32 pages = 4; -} - -// Response to a single file annotation request. A file may contain one or more -// images, which individually have their own responses. -message AnnotateFileResponse { - // Information about the file for which this response is generated. - InputConfig input_config = 1; - - // Individual responses to images found within the file. This field will be - // empty if the `error` field is set. - repeated AnnotateImageResponse responses = 2; - - // This field gives the total number of pages in the file. - int32 total_pages = 3; - - // If set, represents the error message for the failed request. The - // `responses` field will not be set in this case. - google.rpc.Status error = 4; -} - -// A list of requests to annotate files using the BatchAnnotateFiles API. -message BatchAnnotateFilesRequest { - // Required. The list of file annotation requests. Right now we support only - // one AnnotateFileRequest in BatchAnnotateFilesRequest. - repeated AnnotateFileRequest requests = 1 - [(google.api.field_behavior) = REQUIRED]; - - // 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`. - string parent = 3; -} - -// A list of file annotation responses. -message BatchAnnotateFilesResponse { - // The list of file annotation responses, each response corresponding to each - // AnnotateFileRequest in BatchAnnotateFilesRequest. - repeated AnnotateFileResponse responses = 1; -} - -// An offline file annotation request. -message AsyncAnnotateFileRequest { - // Required. Information about the input file. - InputConfig input_config = 1; - - // Required. Requested features. - repeated Feature features = 2; - - // Additional context that may accompany the image(s) in the file. - ImageContext image_context = 3; - - // Required. The desired output location and metadata (e.g. format). - OutputConfig output_config = 4; -} - -// The response for a single offline file annotation request. -message AsyncAnnotateFileResponse { - // The output location and metadata from AsyncAnnotateFileRequest. - OutputConfig output_config = 1; -} - -// Request for async image annotation for a list of images. -message AsyncBatchAnnotateImagesRequest { - // Required. Individual image annotation requests for this batch. - repeated AnnotateImageRequest requests = 1 - [(google.api.field_behavior) = REQUIRED]; - - // Required. The desired output location and metadata (e.g. format). - OutputConfig output_config = 2 [(google.api.field_behavior) = REQUIRED]; - - // 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`. - string parent = 4; -} - -// Response to an async batch image annotation request. -message AsyncBatchAnnotateImagesResponse { - // The output location and metadata from AsyncBatchAnnotateImagesRequest. - OutputConfig output_config = 1; -} - -// Multiple async file annotation requests are batched into a single service -// call. -message AsyncBatchAnnotateFilesRequest { - // Required. Individual async file annotation requests for this batch. - repeated AsyncAnnotateFileRequest requests = 1 - [(google.api.field_behavior) = REQUIRED]; - - // 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`. - string parent = 4; -} - -// Response to an async batch file annotation request. -message AsyncBatchAnnotateFilesResponse { - // The list of file annotation responses, one for each request in - // AsyncBatchAnnotateFilesRequest. - repeated AsyncAnnotateFileResponse responses = 1; -} - -// The desired input location and metadata. -message InputConfig { - // The Google Cloud Storage location to read the input from. - GcsSource gcs_source = 1; - - // 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. - bytes content = 3; - - // The type of the file. Currently only "application/pdf", "image/tiff" and - // "image/gif" are supported. Wildcards are not supported. - string mime_type = 2; -} - -// The desired output location and metadata. -message OutputConfig { - // The Google Cloud Storage location to write the output(s) to. - GcsDestination gcs_destination = 1; - - // 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. - int32 batch_size = 2; -} - -// The Google Cloud Storage location where the input will be read from. -message GcsSource { - // Google Cloud Storage URI for the input file. This must only be a - // Google Cloud Storage object. Wildcards are not currently supported. - string uri = 1; -} - -// The Google Cloud Storage location where the output will be written to. -message GcsDestination { - // 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. - string uri = 1; -} - -// Contains metadata for the BatchAnnotateImages operation. -message OperationMetadata { - // Batch operation states. - enum State { - // Invalid. - STATE_UNSPECIFIED = 0; - - // Request is received. - CREATED = 1; - - // Request is actively being processed. - RUNNING = 2; - - // The batch processing is done. - DONE = 3; - - // The batch processing was cancelled. - CANCELLED = 4; - } - - // Current state of the batch operation. - State state = 1; - - // The time when the batch request was received. - google.protobuf.Timestamp create_time = 5; - - // The time when the operation result was last updated. - google.protobuf.Timestamp update_time = 6; -} diff --git a/google/cloud/vision_v1/proto/product_search.proto b/google/cloud/vision_v1/proto/product_search.proto deleted file mode 100644 index 564925fe..00000000 --- a/google/cloud/vision_v1/proto/product_search.proto +++ /dev/null @@ -1,125 +0,0 @@ -// 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. - -syntax = "proto3"; - -package google.cloud.vision.v1; - -import "google/api/resource.proto"; -import "google/cloud/vision/v1/geometry.proto"; -import "google/cloud/vision/v1/product_search_service.proto"; -import "google/protobuf/timestamp.proto"; -import "google/api/annotations.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1;vision"; -option java_multiple_files = true; -option java_outer_classname = "ProductSearchProto"; -option java_package = "com.google.cloud.vision.v1"; -option objc_class_prefix = "GCVN"; - -// Parameters for a product search request. -message ProductSearchParams { - // The bounding polygon around the area of interest in the image. - // If it is not specified, system discretion will be applied. - BoundingPoly bounding_poly = 9; - - // 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`. - string product_set = 6 [(google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - }]; - - // 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. - 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. 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 '='. - string filter = 8; -} - -// Results for a product search request. -message ProductSearchResults { - // 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). - float score = 2; - - // The resource name of the image from the product that is the closest match - // to the query. - string image = 3; - } - - // Prediction for what the object in the bounding box is. - message ObjectAnnotation { - // Object ID that should align with EntityAnnotation mid. - string mid = 1; - - // 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. - string language_code = 2; - - // Object name, expressed in its `language_code` language. - string name = 3; - - // Score of the result. Range [0, 1]. - float score = 4; - } - - // Information about the products similar to a single product in a query - // image. - message GroupedResult { - // The bounding polygon around the product detected in the query image. - BoundingPoly bounding_poly = 1; - - // List of results, one for each product match. - repeated Result results = 2; - - // List of generic predictions for the object in the bounding box. - repeated ObjectAnnotation object_annotations = 3; - } - - // 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. - google.protobuf.Timestamp index_time = 2; - - // List of results, one for each product match. - repeated Result results = 5; - - // 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. - repeated GroupedResult product_grouped_results = 6; -} diff --git a/google/cloud/vision_v1/proto/product_search_service.proto b/google/cloud/vision_v1/proto/product_search_service.proto deleted file mode 100644 index 5a61f542..00000000 --- a/google/cloud/vision_v1/proto/product_search_service.proto +++ /dev/null @@ -1,1022 +0,0 @@ -// 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. - -syntax = "proto3"; - -package google.cloud.vision.v1; - -import "google/api/annotations.proto"; -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; -import "google/api/resource.proto"; -import "google/cloud/vision/v1/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/v1;vision"; -option java_multiple_files = true; -option java_outer_classname = "ProductSearchServiceProto"; -option java_package = "com.google.cloud.vision.v1"; -option objc_class_prefix = "GCVN"; - -// 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/*` -service ProductSearch { - option (google.api.default_host) = "vision.googleapis.com"; - option (google.api.oauth_scopes) = - "https://www.googleapis.com/auth/cloud-platform," - "https://www.googleapis.com/auth/cloud-vision"; - - // 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: "/v1/{parent=projects/*/locations/*}/productSets" - body: "product_set" - }; - option (google.api.method_signature) = "parent,product_set,product_set_id"; - } - - // 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: "/v1/{parent=projects/*/locations/*}/productSets" - }; - option (google.api.method_signature) = "parent"; - } - - // 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: "/v1/{name=projects/*/locations/*/productSets/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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: "/v1/{product_set.name=projects/*/locations/*/productSets/*}" - body: "product_set" - }; - option (google.api.method_signature) = "product_set,update_mask"; - } - - // Permanently deletes a ProductSet. Products and ReferenceImages in the - // ProductSet are not deleted. - // - // The actual image files are not deleted from Google Cloud Storage. - rpc DeleteProductSet(DeleteProductSetRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v1/{name=projects/*/locations/*/productSets/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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: "/v1/{parent=projects/*/locations/*}/products" - body: "product" - }; - option (google.api.method_signature) = "parent,product,product_id"; - } - - // 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: "/v1/{parent=projects/*/locations/*}/products" - }; - option (google.api.method_signature) = "parent"; - } - - // 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: "/v1/{name=projects/*/locations/*/products/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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. - rpc UpdateProduct(UpdateProductRequest) returns (Product) { - option (google.api.http) = { - patch: "/v1/{product.name=projects/*/locations/*/products/*}" - body: "product" - }; - option (google.api.method_signature) = "product,update_mask"; - } - - // 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. - rpc DeleteProduct(DeleteProductRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v1/{name=projects/*/locations/*/products/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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: "/v1/{parent=projects/*/locations/*/products/*}/referenceImages" - body: "reference_image" - }; - option (google.api.method_signature) = "parent,reference_image,reference_image_id"; - } - - // 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. - rpc DeleteReferenceImage(DeleteReferenceImageRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v1/{name=projects/*/locations/*/products/*/referenceImages/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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: "/v1/{parent=projects/*/locations/*/products/*}/referenceImages" - }; - option (google.api.method_signature) = "parent"; - } - - // 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: "/v1/{name=projects/*/locations/*/products/*/referenceImages/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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: "/v1/{name=projects/*/locations/*/productSets/*}:addProduct" - body: "*" - }; - option (google.api.method_signature) = "name,product"; - } - - // Removes a Product from the specified ProductSet. - rpc RemoveProductFromProductSet(RemoveProductFromProductSetRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - post: "/v1/{name=projects/*/locations/*/productSets/*}:removeProduct" - body: "*" - }; - option (google.api.method_signature) = "name,product"; - } - - // 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: "/v1/{name=projects/*/locations/*/productSets/*}/products" - }; - option (google.api.method_signature) = "name"; - } - - // 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]. - rpc ImportProductSets(ImportProductSetsRequest) returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v1/{parent=projects/*/locations/*}/productSets:import" - body: "*" - }; - option (google.api.method_signature) = "parent,input_config"; - option (google.longrunning.operation_info) = { - response_type: "ImportProductSetsResponse" - metadata_type: "BatchOperationMetadata" - }; - } - - // 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) - rpc PurgeProducts(PurgeProductsRequest) returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v1/{parent=projects/*/locations/*}/products:purge" - body: "*" - }; - option (google.api.method_signature) = "parent"; - option (google.longrunning.operation_info) = { - response_type: "google.protobuf.Empty" - metadata_type: "BatchOperationMetadata" - }; - } -} - -// A Product contains ReferenceImages. -message Product { - option (google.api.resource) = { - type: "vision.googleapis.com/Product" - pattern: "projects/{project}/locations/{location}/products/{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; - - // Immutable. The category for the product identified by the reference image. This should - // be one of "homegoods-v2", "apparel-v2", "toys-v2", "packagedgoods-v1" or - // "general-v1". The legacy categories "homegoods", "apparel", and "toys" are - // still supported, but these should not be used for new products. - string product_category = 4 [(google.api.field_behavior) = IMMUTABLE]; - - // 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. - 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 { - option (google.api.resource) = { - type: "vision.googleapis.com/ProductSet" - pattern: "projects/{project}/locations/{location}/productSets/{product_set}" - }; - - // 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 timestamp is the default value - // "1970-01-01T00:00:00Z". - // - // This field is ignored when creating a ProductSet. - google.protobuf.Timestamp index_time = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; - - // 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 [(google.api.field_behavior) = OUTPUT_ONLY]; -} - -// A `ReferenceImage` represents a product image and its associated metadata, -// such as bounding boxes. -message ReferenceImage { - option (google.api.resource) = { - type: "vision.googleapis.com/ReferenceImage" - pattern: "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}" - }; - - // 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; - - // Required. The Google Cloud Storage URI of the reference image. - // - // The URI must start with `gs://`. - string uri = 2 [(google.api.field_behavior) = REQUIRED]; - - // 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). - repeated BoundingPoly bounding_polys = 3 [(google.api.field_behavior) = OPTIONAL]; -} - -// Request message for the `CreateProduct` method. -message CreateProductRequest { - // Required. The project in which the Product should be created. - // - // Format is - // `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Required. The product to create. - Product product = 2 [(google.api.field_behavior) = REQUIRED]; - - // 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 { - // Required. The project OR ProductSet from which Products should be listed. - // - // Format: - // `projects/PROJECT_ID/locations/LOC_ID` - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // 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 { - // Required. Resource name of the Product to get. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/Product" - } - ]; -} - -// Request message for the `UpdateProduct` method. -message UpdateProductRequest { - // Required. The Product resource which replaces the one on the server. - // product.name is immutable. - Product product = 1 [(google.api.field_behavior) = REQUIRED]; - - // 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 { - // Required. Resource name of product to delete. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/Product" - } - ]; -} - -// Request message for the `CreateProductSet` method. -message CreateProductSetRequest { - // Required. The project in which the ProductSet should be created. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Required. The ProductSet to create. - ProductSet product_set = 2 [(google.api.field_behavior) = REQUIRED]; - - // 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 { - // Required. The project from which ProductSets should be listed. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // 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 { - // Required. Resource name of the ProductSet to get. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - } - ]; -} - -// Request message for the `UpdateProductSet` method. -message UpdateProductSetRequest { - // Required. The ProductSet resource which replaces the one on the server. - ProductSet product_set = 1 [(google.api.field_behavior) = REQUIRED]; - - // 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 { - // Required. Resource name of the ProductSet to delete. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - } - ]; -} - -// Request message for the `CreateReferenceImage` method. -message CreateReferenceImageRequest { - // Required. 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 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/Product" - } - ]; - - // Required. The reference image to create. - // If an image ID is specified, it is ignored. - ReferenceImage reference_image = 2 [(google.api.field_behavior) = REQUIRED]; - - // 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 { - // Required. Resource name of the product containing the reference images. - // - // Format is - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/Product" - } - ]; - - // 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 { - // Required. 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 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ReferenceImage" - } - ]; -} - -// Request message for the `DeleteReferenceImage` method. -message DeleteReferenceImageRequest { - // Required. 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 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ReferenceImage" - } - ]; -} - -// Request message for the `AddProductToProductSet` method. -message AddProductToProductSetRequest { - // Required. The resource name for the ProductSet to modify. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - } - ]; - - // Required. 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 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/Product" - } - ]; -} - -// Request message for the `RemoveProductFromProductSet` method. -message RemoveProductFromProductSetRequest { - // Required. The resource name for the ProductSet to modify. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - } - ]; - - // Required. 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 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/Product" - } - ]; -} - -// Request message for the `ListProductsInProductSet` method. -message ListProductsInProductSetRequest { - // Required. The ProductSet resource for which to retrieve Products. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - } - ]; - - // 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 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). - 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 { - // Required. The project in which the ProductSets should be imported. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Required. The input content for the list of requests. - ImportProductSetsInputConfig input_config = 2 [(google.api.field_behavior) = REQUIRED]; -} - -// 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; -} - -// Config to control which ProductSet contains the Products to be deleted. -message ProductSetPurgeConfig { - // 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. - string product_set_id = 1; -} - -// Request message for the `PurgeProducts` method. -message PurgeProductsRequest { - // The Products to delete. - oneof target { - // Specify which ProductSet contains the Products to be deleted. - ProductSetPurgeConfig product_set_purge_config = 2; - - // If delete_orphan_products is true, all Products that are not in any - // ProductSet will be deleted. - bool delete_orphan_products = 3; - } - - // Required. The project and location in which the Products should be deleted. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // The default value is false. Override this value to true to actually perform - // the purge. - bool force = 4; -} diff --git a/google/cloud/vision_v1/proto/text_annotation.proto b/google/cloud/vision_v1/proto/text_annotation.proto deleted file mode 100644 index db3bbdc5..00000000 --- a/google/cloud/vision_v1/proto/text_annotation.proto +++ /dev/null @@ -1,259 +0,0 @@ -// 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. - -syntax = "proto3"; - -package google.cloud.vision.v1; - -import "google/cloud/vision/v1/geometry.proto"; -import "google/api/annotations.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1;vision"; -option java_multiple_files = true; -option java_outer_classname = "TextAnnotationProto"; -option java_package = "com.google.cloud.vision.v1"; -option objc_class_prefix = "GCVN"; - -// 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. -message TextAnnotation { - // Detected language for a structural component. - message DetectedLanguage { - // 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. - string language_code = 1; - - // Confidence of detected language. Range [0, 1]. - float confidence = 2; - } - - // Detected start or end of a structural component. - message DetectedBreak { - // Enum to denote the type of break found. New line, space etc. - enum BreakType { - // Unknown break label type. - UNKNOWN = 0; - - // Regular space. - SPACE = 1; - - // Sure space (very wide). - SURE_SPACE = 2; - - // Line-wrapping break. - EOL_SURE_SPACE = 3; - - // End-line hyphen that is not present in text; does not co-occur with - // `SPACE`, `LEADER_SPACE`, or `LINE_BREAK`. - HYPHEN = 4; - - // Line break that ends a paragraph. - LINE_BREAK = 5; - } - - // Detected break type. - BreakType type = 1; - - // True if break prepends the element. - bool is_prefix = 2; - } - - // Additional information detected on the structural component. - message TextProperty { - // A list of detected languages together with confidence. - repeated DetectedLanguage detected_languages = 1; - - // Detected start or end of a text segment. - DetectedBreak detected_break = 2; - } - - // List of pages detected by OCR. - repeated Page pages = 1; - - // UTF-8 text detected on the pages. - string text = 2; -} - -// Detected page from OCR. -message Page { - // Additional information detected on the page. - TextAnnotation.TextProperty property = 1; - - // Page width. For PDFs the unit is points. For images (including - // TIFFs) the unit is pixels. - int32 width = 2; - - // Page height. For PDFs the unit is points. For images (including - // TIFFs) the unit is pixels. - int32 height = 3; - - // List of blocks of text, images etc on this page. - repeated Block blocks = 4; - - // Confidence of the OCR results on the page. Range [0, 1]. - float confidence = 5; -} - -// Logical element on the page. -message Block { - // Type of a block (text, image etc) as identified by OCR. - enum BlockType { - // Unknown block type. - UNKNOWN = 0; - - // Regular text block. - TEXT = 1; - - // Table block. - TABLE = 2; - - // Image block. - PICTURE = 3; - - // Horizontal/vertical line box. - RULER = 4; - - // Barcode block. - BARCODE = 5; - } - - // Additional information detected for the block. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // List of paragraphs in this block (if this blocks is of type text). - repeated Paragraph paragraphs = 3; - - // Detected block type (text, image etc) for this block. - BlockType block_type = 4; - - // Confidence of the OCR results on the block. Range [0, 1]. - float confidence = 5; -} - -// Structural unit of text representing a number of words in certain order. -message Paragraph { - // Additional information detected for the paragraph. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // List of all words in this paragraph. - repeated Word words = 3; - - // Confidence of the OCR results for the paragraph. Range [0, 1]. - float confidence = 4; -} - -// A word representation. -message Word { - // Additional information detected for the word. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // List of symbols in the word. - // The order of the symbols follows the natural reading order. - repeated Symbol symbols = 3; - - // Confidence of the OCR results for the word. Range [0, 1]. - float confidence = 4; -} - -// A single symbol representation. -message Symbol { - // Additional information detected for the symbol. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // The actual UTF-8 representation of the symbol. - string text = 3; - - // Confidence of the OCR results for the symbol. Range [0, 1]. - float confidence = 4; -} diff --git a/google/cloud/vision_v1/proto/web_detection.proto b/google/cloud/vision_v1/proto/web_detection.proto deleted file mode 100644 index 5d239b89..00000000 --- a/google/cloud/vision_v1/proto/web_detection.proto +++ /dev/null @@ -1,106 +0,0 @@ -// 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. - -syntax = "proto3"; - -package google.cloud.vision.v1; - -import "google/api/annotations.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1;vision"; -option java_multiple_files = true; -option java_outer_classname = "WebDetectionProto"; -option java_package = "com.google.cloud.vision.v1"; -option objc_class_prefix = "GCVN"; - -// Relevant information for the image from the Internet. -message WebDetection { - // Entity deduced from similar images on the Internet. - message WebEntity { - // Opaque entity ID. - string entity_id = 1; - - // Overall relevancy score for the entity. - // Not normalized and not comparable across different image queries. - float score = 2; - - // Canonical description of the entity, in English. - string description = 3; - } - - // Metadata for online images. - message WebImage { - // The result image URL. - string url = 1; - - // (Deprecated) Overall relevancy score for the image. - float score = 2; - } - - // Metadata for web pages. - message WebPage { - // The result web page URL. - string url = 1; - - // (Deprecated) Overall relevancy score for the web page. - float score = 2; - - // Title for the web page, may contain HTML markups. - string page_title = 3; - - // Fully matching images on the page. - // Can include resized copies of the query image. - repeated WebImage full_matching_images = 4; - - // 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. - repeated WebImage partial_matching_images = 5; - } - - // Label to provide extra metadata for the web detection. - message WebLabel { - // Label for extra metadata. - string label = 1; - - // 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. - string language_code = 2; - } - - // Deduced entities from similar images on the Internet. - repeated WebEntity web_entities = 1; - - // Fully matching images from the Internet. - // Can include resized copies of the query image. - repeated WebImage full_matching_images = 2; - - // 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. - repeated WebImage partial_matching_images = 3; - - // Web pages containing the matching images from the Internet. - repeated WebPage pages_with_matching_images = 4; - - // The visually similar image results. - repeated WebImage visually_similar_images = 6; - - // The service's best guess as to the topic of the request image. - // Inferred from similar images on the open web. - repeated WebLabel best_guess_labels = 8; -} diff --git a/google/cloud/vision_v1/services/__init__.py b/google/cloud/vision_v1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/vision_v1/services/__init__.py +++ b/google/cloud/vision_v1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/vision_v1/services/image_annotator/__init__.py b/google/cloud/vision_v1/services/image_annotator/__init__.py index 2b601881..422732ba 100644 --- a/google/cloud/vision_v1/services/image_annotator/__init__.py +++ b/google/cloud/vision_v1/services/image_annotator/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ImageAnnotatorClient from .async_client import ImageAnnotatorAsyncClient diff --git a/google/cloud/vision_v1/services/image_annotator/async_client.py b/google/cloud/vision_v1/services/image_annotator/async_client.py index 1a5ea404..311d3df4 100644 --- a/google/cloud/vision_v1/services/image_annotator/async_client.py +++ b/google/cloud/vision_v1/services/image_annotator/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,16 +20,15 @@ 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 exceptions as core_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 import credentials as ga_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.types import image_annotator - from .transports.base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ImageAnnotatorGrpcAsyncIOTransport from .client import ImageAnnotatorClient @@ -53,31 +50,26 @@ class ImageAnnotatorAsyncClient: parse_product_path = staticmethod(ImageAnnotatorClient.parse_product_path) product_set_path = staticmethod(ImageAnnotatorClient.product_set_path) parse_product_set_path = staticmethod(ImageAnnotatorClient.parse_product_set_path) - common_billing_account_path = staticmethod( ImageAnnotatorClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ImageAnnotatorClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ImageAnnotatorClient.common_folder_path) parse_common_folder_path = staticmethod( ImageAnnotatorClient.parse_common_folder_path ) - common_organization_path = staticmethod( ImageAnnotatorClient.common_organization_path ) parse_common_organization_path = staticmethod( ImageAnnotatorClient.parse_common_organization_path ) - common_project_path = staticmethod(ImageAnnotatorClient.common_project_path) parse_common_project_path = staticmethod( ImageAnnotatorClient.parse_common_project_path ) - common_location_path = staticmethod(ImageAnnotatorClient.common_location_path) parse_common_location_path = staticmethod( ImageAnnotatorClient.parse_common_location_path @@ -85,7 +77,8 @@ class ImageAnnotatorAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -100,7 +93,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -117,7 +110,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ImageAnnotatorTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ImageAnnotatorTransport: The transport used by the client instance. @@ -131,12 +124,12 @@ def transport(self) -> ImageAnnotatorTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_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. + """Instantiates the image annotator client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -168,7 +161,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ImageAnnotatorClient( credentials=credentials, transport=transport, @@ -199,7 +191,6 @@ async def batch_annotate_images( 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. @@ -226,7 +217,6 @@ async def batch_annotate_images( # If we have keyword arguments corresponding to fields on the # request, apply these. - if requests: request.requests.extend(requests) @@ -239,7 +229,8 @@ async def batch_annotate_images( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -284,7 +275,6 @@ async def batch_annotate_files( 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. @@ -309,7 +299,6 @@ async def batch_annotate_files( # If we have keyword arguments corresponding to fields on the # request, apply these. - if requests: request.requests.extend(requests) @@ -322,7 +311,8 @@ async def batch_annotate_files( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -377,7 +367,6 @@ async def async_batch_annotate_images( 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. @@ -407,10 +396,8 @@ async def async_batch_annotate_images( # If we have keyword arguments corresponding to fields on the # request, apply these. - if output_config is not None: request.output_config = output_config - if requests: request.requests.extend(requests) @@ -423,7 +410,8 @@ async def async_batch_annotate_images( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -473,7 +461,6 @@ async def async_batch_annotate_files( 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. @@ -503,7 +490,6 @@ async def async_batch_annotate_files( # If we have keyword arguments corresponding to fields on the # request, apply these. - if requests: request.requests.extend(requests) @@ -516,7 +502,8 @@ async def async_batch_annotate_files( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), diff --git a/google/cloud/vision_v1/services/image_annotator/client.py b/google/cloud/vision_v1/services/image_annotator/client.py index 9bf982c9..02cf671e 100644 --- a/google/cloud/vision_v1/services/image_annotator/client.py +++ b/google/cloud/vision_v1/services/image_annotator/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ 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 exceptions as core_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 import credentials as ga_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 @@ -35,7 +33,6 @@ 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 @@ -56,7 +53,7 @@ class ImageAnnotatorClientMeta(type): _transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ImageAnnotatorTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -83,7 +80,8 @@ class ImageAnnotatorClient(metaclass=ImageAnnotatorClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -117,7 +115,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -134,7 +133,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -153,23 +152,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ImageAnnotatorTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ImageAnnotatorTransport: The transport used by the client instance. + ImageAnnotatorTransport: The transport used by the client + instance. """ return self._transport @staticmethod def product_path(project: str, location: str, product: str,) -> str: - """Return a fully-qualified product string.""" + """Returns 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.""" + """Parses a product path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", path, @@ -178,14 +178,14 @@ def parse_product_path(path: str) -> Dict[str, str]: @staticmethod def product_set_path(project: str, location: str, product_set: str,) -> str: - """Return a fully-qualified product_set string.""" + """Returns 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.""" + """Parses a product_set path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", path, @@ -194,7 +194,7 @@ def parse_product_set_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -207,7 +207,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -218,7 +218,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -229,7 +229,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -240,7 +240,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -254,12 +254,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_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. + """Instantiates the image annotator client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -314,9 +314,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -328,12 +329,14 @@ def __init__( 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 - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -348,8 +351,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -387,7 +390,6 @@ def batch_annotate_images( 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. @@ -419,10 +421,8 @@ def batch_annotate_images( 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 @@ -467,7 +467,6 @@ def batch_annotate_files( 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. @@ -497,10 +496,8 @@ def batch_annotate_files( 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 @@ -555,7 +552,6 @@ def async_batch_annotate_images( 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. @@ -590,10 +586,8 @@ def async_batch_annotate_images( 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: @@ -647,7 +641,6 @@ def async_batch_annotate_files( 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. @@ -682,10 +675,8 @@ def async_batch_annotate_files( 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 diff --git a/google/cloud/vision_v1/services/image_annotator/transports/__init__.py b/google/cloud/vision_v1/services/image_annotator/transports/__init__.py index e2a0c3ea..419b4293 100644 --- a/google/cloud/vision_v1/services/image_annotator/transports/__init__.py +++ b/google/cloud/vision_v1/services/image_annotator/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/vision_v1/services/image_annotator/transports/base.py b/google/cloud/vision_v1/services/image_annotator/transports/base.py index 97293fb0..4ba8b4ad 100644 --- a/google/cloud/vision_v1/services/image_annotator/transports/base.py +++ b/google/cloud/vision_v1/services/image_annotator/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_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.auth import credentials as ga_credentials # type: ignore from google.cloud.vision_v1.types import image_annotator -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -37,6 +36,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ImageAnnotatorTransport(abc.ABC): """Abstract transport class for ImageAnnotator.""" @@ -46,21 +56,24 @@ class ImageAnnotatorTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-vision", ) + DEFAULT_HOST: str = "vision.googleapis.com" + 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, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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. + 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 @@ -69,7 +82,7 @@ def __init__( 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. + scopes (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): @@ -83,29 +96,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -116,7 +176,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -130,7 +191,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -144,7 +206,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -158,7 +221,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -175,11 +239,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def batch_annotate_images( self, - ) -> typing.Callable[ + ) -> Callable[ [image_annotator.BatchAnnotateImagesRequest], - typing.Union[ + Union[ image_annotator.BatchAnnotateImagesResponse, - typing.Awaitable[image_annotator.BatchAnnotateImagesResponse], + Awaitable[image_annotator.BatchAnnotateImagesResponse], ], ]: raise NotImplementedError() @@ -187,11 +251,11 @@ def batch_annotate_images( @property def batch_annotate_files( self, - ) -> typing.Callable[ + ) -> Callable[ [image_annotator.BatchAnnotateFilesRequest], - typing.Union[ + Union[ image_annotator.BatchAnnotateFilesResponse, - typing.Awaitable[image_annotator.BatchAnnotateFilesResponse], + Awaitable[image_annotator.BatchAnnotateFilesResponse], ], ]: raise NotImplementedError() @@ -199,18 +263,18 @@ def batch_annotate_files( @property def async_batch_annotate_images( self, - ) -> typing.Callable[ + ) -> Callable[ [image_annotator.AsyncBatchAnnotateImagesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def async_batch_annotate_files( self, - ) -> typing.Callable[ + ) -> Callable[ [image_annotator.AsyncBatchAnnotateFilesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/vision_v1/services/image_annotator/transports/grpc.py b/google/cloud/vision_v1/services/image_annotator/transports/grpc.py index 81f91a2e..052e73a4 100644 --- a/google/cloud/vision_v1/services/image_annotator/transports/grpc.py +++ b/google/cloud/vision_v1/services/image_annotator/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # 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 typing import Callable, Dict, Optional, Sequence, Tuple, Union 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 +import google.auth # type: ignore +from google.auth import credentials as ga_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 google.longrunning import operations_pb2 # type: ignore from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -180,7 +178,7 @@ def __init__( def create_channel( cls, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -211,13 +209,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -311,7 +311,7 @@ def batch_annotate_files( def async_batch_annotate_images( self, ) -> Callable[ - [image_annotator.AsyncBatchAnnotateImagesRequest], operations.Operation + [image_annotator.AsyncBatchAnnotateImagesRequest], operations_pb2.Operation ]: r"""Return a callable for the async batch annotate images method over gRPC. @@ -342,7 +342,7 @@ def async_batch_annotate_images( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["async_batch_annotate_images"] @@ -350,7 +350,7 @@ def async_batch_annotate_images( def async_batch_annotate_files( self, ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], operations.Operation + [image_annotator.AsyncBatchAnnotateFilesRequest], operations_pb2.Operation ]: r"""Return a callable for the async batch annotate files method over gRPC. @@ -376,7 +376,7 @@ def async_batch_annotate_files( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["async_batch_annotate_files"] 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 index 90ecf41e..e03003bf 100644 --- a/google/cloud/vision_v1/services/image_annotator/transports/grpc_asyncio.py +++ b/google/cloud/vision_v1/services/image_annotator/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union 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 import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version 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 google.longrunning import operations_pb2 # type: ignore from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .grpc import ImageAnnotatorGrpcTransport @@ -58,7 +55,7 @@ class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): def create_channel( cls, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -172,7 +172,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -318,7 +317,7 @@ def async_batch_annotate_images( self, ) -> Callable[ [image_annotator.AsyncBatchAnnotateImagesRequest], - Awaitable[operations.Operation], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the async batch annotate images method over gRPC. @@ -349,7 +348,7 @@ def async_batch_annotate_images( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["async_batch_annotate_images"] @@ -358,7 +357,7 @@ def async_batch_annotate_files( self, ) -> Callable[ [image_annotator.AsyncBatchAnnotateFilesRequest], - Awaitable[operations.Operation], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the async batch annotate files method over gRPC. @@ -384,7 +383,7 @@ def async_batch_annotate_files( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["async_batch_annotate_files"] diff --git a/google/cloud/vision_v1/services/product_search/__init__.py b/google/cloud/vision_v1/services/product_search/__init__.py index e82b5909..f357996e 100644 --- a/google/cloud/vision_v1/services/product_search/__init__.py +++ b/google/cloud/vision_v1/services/product_search/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ProductSearchClient from .async_client import 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 index c6b6cc7b..e8c3bdb8 100644 --- a/google/cloud/vision_v1/services/product_search/async_client.py +++ b/google/cloud/vision_v1/services/product_search/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ 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 exceptions as core_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 import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -33,11 +31,10 @@ 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 google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport from .client import ProductSearchClient @@ -77,31 +74,26 @@ class ProductSearchAsyncClient: parse_reference_image_path = staticmethod( ProductSearchClient.parse_reference_image_path ) - common_billing_account_path = staticmethod( ProductSearchClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ProductSearchClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ProductSearchClient.common_folder_path) parse_common_folder_path = staticmethod( ProductSearchClient.parse_common_folder_path ) - common_organization_path = staticmethod( ProductSearchClient.common_organization_path ) parse_common_organization_path = staticmethod( ProductSearchClient.parse_common_organization_path ) - common_project_path = staticmethod(ProductSearchClient.common_project_path) parse_common_project_path = staticmethod( ProductSearchClient.parse_common_project_path ) - common_location_path = staticmethod(ProductSearchClient.common_location_path) parse_common_location_path = staticmethod( ProductSearchClient.parse_common_location_path @@ -109,7 +101,8 @@ class ProductSearchAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -124,7 +117,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -141,7 +134,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ProductSearchTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ProductSearchTransport: The transport used by the client instance. @@ -155,12 +148,12 @@ def transport(self) -> ProductSearchTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_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. + """Instantiates the product search client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -192,7 +185,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ProductSearchClient( credentials=credentials, transport=transport, @@ -246,7 +238,6 @@ async def create_product_set( 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. @@ -276,7 +267,6 @@ async def create_product_set( # 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: @@ -340,7 +330,6 @@ async def list_product_sets( 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. @@ -369,7 +358,6 @@ async def list_product_sets( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -382,7 +370,8 @@ async def list_product_sets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -436,7 +425,6 @@ async def get_product_set( 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. @@ -466,7 +454,6 @@ async def get_product_set( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -479,7 +466,8 @@ async def get_product_set( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -504,7 +492,7 @@ async def update_product_set( request: product_search_service.UpdateProductSetRequest = None, *, product_set: product_search_service.ProductSet = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -539,7 +527,6 @@ async def update_product_set( 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. @@ -569,7 +556,6 @@ async def update_product_set( # 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: @@ -584,7 +570,8 @@ async def update_product_set( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -633,7 +620,6 @@ async def delete_product_set( 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. @@ -654,7 +640,6 @@ async def delete_product_set( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -667,7 +652,8 @@ async def delete_product_set( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -736,7 +722,6 @@ async def create_product( 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. @@ -761,7 +746,6 @@ async def create_product( # 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: @@ -825,7 +809,6 @@ async def list_products( 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. @@ -854,7 +837,6 @@ async def list_products( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -867,7 +849,8 @@ async def list_products( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -921,7 +904,6 @@ async def get_product( 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. @@ -946,7 +928,6 @@ async def get_product( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -959,7 +940,8 @@ async def get_product( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -984,7 +966,7 @@ async def update_product( request: product_search_service.UpdateProductRequest = None, *, product: product_search_service.Product = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1028,7 +1010,6 @@ async def update_product( 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. @@ -1053,7 +1034,6 @@ async def update_product( # 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: @@ -1068,7 +1048,8 @@ async def update_product( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1119,7 +1100,6 @@ async def delete_product( 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. @@ -1140,7 +1120,6 @@ async def delete_product( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1153,7 +1132,8 @@ async def delete_product( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1238,7 +1218,6 @@ async def create_reference_image( 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. @@ -1265,7 +1244,6 @@ async def create_reference_image( # 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: @@ -1331,7 +1309,6 @@ async def delete_reference_image( 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. @@ -1352,7 +1329,6 @@ async def delete_reference_image( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1365,7 +1341,8 @@ async def delete_reference_image( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1415,7 +1392,6 @@ async def list_reference_images( 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. @@ -1444,7 +1420,6 @@ async def list_reference_images( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1457,7 +1432,8 @@ async def list_reference_images( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1512,7 +1488,6 @@ async def get_reference_image( 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. @@ -1539,7 +1514,6 @@ async def get_reference_image( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1552,7 +1526,8 @@ async def get_reference_image( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1616,7 +1591,6 @@ async def add_product_to_product_set( 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. @@ -1637,7 +1611,6 @@ async def add_product_to_product_set( # 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: @@ -1652,7 +1625,8 @@ async def add_product_to_product_set( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1707,7 +1681,6 @@ async def remove_product_from_product_set( 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. @@ -1728,7 +1701,6 @@ async def remove_product_from_product_set( # 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: @@ -1743,7 +1715,8 @@ async def remove_product_from_product_set( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1794,7 +1767,6 @@ async def list_products_in_product_set( 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. @@ -1824,7 +1796,6 @@ async def list_products_in_product_set( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1837,7 +1808,8 @@ async def list_products_in_product_set( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1906,7 +1878,6 @@ async def import_product_sets( 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. @@ -1942,7 +1913,6 @@ async def import_product_sets( # 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: @@ -2033,7 +2003,6 @@ async def purge_products( 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. @@ -2073,7 +2042,6 @@ async def purge_products( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -2105,7 +2073,7 @@ async def purge_products( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=product_search_service.BatchOperationMetadata, ) diff --git a/google/cloud/vision_v1/services/product_search/client.py b/google/cloud/vision_v1/services/product_search/client.py index 86b6a2a6..bb74fd4c 100644 --- a/google/cloud/vision_v1/services/product_search/client.py +++ b/google/cloud/vision_v1/services/product_search/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ 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 exceptions as core_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 import credentials as ga_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 @@ -37,11 +35,10 @@ 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 google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ProductSearchGrpcTransport from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport @@ -60,7 +57,7 @@ class ProductSearchClientMeta(type): _transport_registry["grpc_asyncio"] = ProductSearchGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ProductSearchTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -101,7 +98,8 @@ class ProductSearchClient(metaclass=ProductSearchClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -135,7 +133,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -152,7 +151,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -171,23 +170,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ProductSearchTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ProductSearchTransport: The transport used by the client instance. + ProductSearchTransport: The transport used by the client + instance. """ return self._transport @staticmethod def product_path(project: str, location: str, product: str,) -> str: - """Return a fully-qualified product string.""" + """Returns 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.""" + """Parses a product path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", path, @@ -196,14 +196,14 @@ def parse_product_path(path: str) -> Dict[str, str]: @staticmethod def product_set_path(project: str, location: str, product_set: str,) -> str: - """Return a fully-qualified product_set string.""" + """Returns 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.""" + """Parses a product_set path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", path, @@ -214,7 +214,7 @@ def parse_product_set_path(path: str) -> Dict[str, str]: def reference_image_path( project: str, location: str, product: str, reference_image: str, ) -> str: - """Return a fully-qualified reference_image string.""" + """Returns a fully-qualified reference_image string.""" return "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( project=project, location=location, @@ -224,7 +224,7 @@ def reference_image_path( @staticmethod def parse_reference_image_path(path: str) -> Dict[str, str]: - """Parse a reference_image path into its component segments.""" + """Parses a reference_image path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)/referenceImages/(?P.+?)$", path, @@ -233,7 +233,7 @@ def parse_reference_image_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -246,7 +246,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -257,7 +257,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -268,7 +268,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -279,7 +279,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -293,12 +293,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_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. + """Instantiates the product search client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -353,9 +353,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -367,12 +368,14 @@ def __init__( 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 - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -387,8 +390,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -449,7 +452,6 @@ def create_product_set( 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. @@ -481,10 +483,8 @@ def create_product_set( # 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: @@ -537,7 +537,6 @@ def list_product_sets( 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. @@ -568,10 +567,8 @@ def list_product_sets( # 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 @@ -625,7 +622,6 @@ def get_product_set( 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. @@ -657,10 +653,8 @@ def get_product_set( # 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 @@ -685,7 +679,7 @@ def update_product_set( request: product_search_service.UpdateProductSetRequest = None, *, product_set: product_search_service.ProductSet = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -720,7 +714,6 @@ def update_product_set( 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. @@ -752,10 +745,8 @@ def update_product_set( # 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: @@ -806,7 +797,6 @@ def delete_product_set( 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. @@ -829,10 +819,8 @@ def delete_product_set( # 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 @@ -901,7 +889,6 @@ def create_product( 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. @@ -928,10 +915,8 @@ def create_product( # 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: @@ -984,7 +969,6 @@ def list_products( 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. @@ -1015,10 +999,8 @@ def list_products( # 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 @@ -1072,7 +1054,6 @@ def get_product( 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. @@ -1099,10 +1080,8 @@ def get_product( # 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 @@ -1127,7 +1106,7 @@ def update_product( request: product_search_service.UpdateProductRequest = None, *, product: product_search_service.Product = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1171,7 +1150,6 @@ def update_product( 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. @@ -1198,10 +1176,8 @@ def update_product( # 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: @@ -1254,7 +1230,6 @@ def delete_product( 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. @@ -1277,10 +1252,8 @@ def delete_product( # 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 @@ -1365,7 +1338,6 @@ def create_reference_image( 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. @@ -1394,10 +1366,8 @@ def create_reference_image( # 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: @@ -1452,7 +1422,6 @@ def delete_reference_image( 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. @@ -1475,10 +1444,8 @@ def delete_reference_image( # 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 @@ -1528,7 +1495,6 @@ def list_reference_images( 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. @@ -1559,10 +1525,8 @@ def list_reference_images( # 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 @@ -1617,7 +1581,6 @@ def get_reference_image( 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. @@ -1646,10 +1609,8 @@ def get_reference_image( # 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 @@ -1713,7 +1674,6 @@ def add_product_to_product_set( 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. @@ -1738,10 +1698,8 @@ def add_product_to_product_set( 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: @@ -1800,7 +1758,6 @@ def remove_product_from_product_set( 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. @@ -1825,10 +1782,8 @@ def remove_product_from_product_set( 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: @@ -1883,7 +1838,6 @@ def list_products_in_product_set( 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. @@ -1917,10 +1871,8 @@ def list_products_in_product_set( 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 @@ -1991,7 +1943,6 @@ def import_product_sets( 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. @@ -2029,10 +1980,8 @@ def import_product_sets( # 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: @@ -2112,7 +2061,6 @@ def purge_products( 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. @@ -2154,10 +2102,8 @@ def purge_products( # 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 @@ -2178,7 +2124,7 @@ def purge_products( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=product_search_service.BatchOperationMetadata, ) diff --git a/google/cloud/vision_v1/services/product_search/pagers.py b/google/cloud/vision_v1/services/product_search/pagers.py index 8d317b18..96c17cdd 100644 --- a/google/cloud/vision_v1/services/product_search/pagers.py +++ b/google/cloud/vision_v1/services/product_search/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -249,7 +247,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -379,7 +377,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -513,7 +511,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/vision_v1/services/product_search/transports/__init__.py b/google/cloud/vision_v1/services/product_search/transports/__init__.py index 8295a6de..f38d3aef 100644 --- a/google/cloud/vision_v1/services/product_search/transports/__init__.py +++ b/google/cloud/vision_v1/services/product_search/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/vision_v1/services/product_search/transports/base.py b/google/cloud/vision_v1/services/product_search/transports/base.py index 851225f1..a9fae78e 100644 --- a/google/cloud/vision_v1/services/product_search/transports/base.py +++ b/google/cloud/vision_v1/services/product_search/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_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.auth import credentials as ga_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 - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -38,6 +37,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ProductSearchTransport(abc.ABC): """Abstract transport class for ProductSearch.""" @@ -47,21 +57,24 @@ class ProductSearchTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-vision", ) + DEFAULT_HOST: str = "vision.googleapis.com" + 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, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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. + 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 @@ -70,7 +83,7 @@ def __init__( 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. + scopes (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): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -129,7 +189,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -143,7 +204,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -157,7 +219,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -171,7 +234,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -197,7 +261,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -211,7 +276,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -225,7 +291,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -239,7 +306,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -265,7 +333,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -279,7 +348,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -293,7 +363,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -307,7 +378,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -321,7 +393,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -335,7 +408,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -376,11 +450,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def create_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.CreateProductSetRequest], - typing.Union[ + Union[ product_search_service.ProductSet, - typing.Awaitable[product_search_service.ProductSet], + Awaitable[product_search_service.ProductSet], ], ]: raise NotImplementedError() @@ -388,11 +462,11 @@ def create_product_set( @property def list_product_sets( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.ListProductSetsRequest], - typing.Union[ + Union[ product_search_service.ListProductSetsResponse, - typing.Awaitable[product_search_service.ListProductSetsResponse], + Awaitable[product_search_service.ListProductSetsResponse], ], ]: raise NotImplementedError() @@ -400,11 +474,11 @@ def list_product_sets( @property def get_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.GetProductSetRequest], - typing.Union[ + Union[ product_search_service.ProductSet, - typing.Awaitable[product_search_service.ProductSet], + Awaitable[product_search_service.ProductSet], ], ]: raise NotImplementedError() @@ -412,11 +486,11 @@ def get_product_set( @property def update_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.UpdateProductSetRequest], - typing.Union[ + Union[ product_search_service.ProductSet, - typing.Awaitable[product_search_service.ProductSet], + Awaitable[product_search_service.ProductSet], ], ]: raise NotImplementedError() @@ -424,20 +498,19 @@ def update_product_set( @property def delete_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.DeleteProductSetRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def create_product( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.CreateProductRequest], - typing.Union[ - product_search_service.Product, - typing.Awaitable[product_search_service.Product], + Union[ + product_search_service.Product, Awaitable[product_search_service.Product] ], ]: raise NotImplementedError() @@ -445,11 +518,11 @@ def create_product( @property def list_products( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.ListProductsRequest], - typing.Union[ + Union[ product_search_service.ListProductsResponse, - typing.Awaitable[product_search_service.ListProductsResponse], + Awaitable[product_search_service.ListProductsResponse], ], ]: raise NotImplementedError() @@ -457,11 +530,10 @@ def list_products( @property def get_product( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.GetProductRequest], - typing.Union[ - product_search_service.Product, - typing.Awaitable[product_search_service.Product], + Union[ + product_search_service.Product, Awaitable[product_search_service.Product] ], ]: raise NotImplementedError() @@ -469,11 +541,10 @@ def get_product( @property def update_product( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.UpdateProductRequest], - typing.Union[ - product_search_service.Product, - typing.Awaitable[product_search_service.Product], + Union[ + product_search_service.Product, Awaitable[product_search_service.Product] ], ]: raise NotImplementedError() @@ -481,20 +552,20 @@ def update_product( @property def delete_product( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.DeleteProductRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def create_reference_image( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.CreateReferenceImageRequest], - typing.Union[ + Union[ product_search_service.ReferenceImage, - typing.Awaitable[product_search_service.ReferenceImage], + Awaitable[product_search_service.ReferenceImage], ], ]: raise NotImplementedError() @@ -502,20 +573,20 @@ def create_reference_image( @property def delete_reference_image( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.DeleteReferenceImageRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def list_reference_images( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.ListReferenceImagesRequest], - typing.Union[ + Union[ product_search_service.ListReferenceImagesResponse, - typing.Awaitable[product_search_service.ListReferenceImagesResponse], + Awaitable[product_search_service.ListReferenceImagesResponse], ], ]: raise NotImplementedError() @@ -523,11 +594,11 @@ def list_reference_images( @property def get_reference_image( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.GetReferenceImageRequest], - typing.Union[ + Union[ product_search_service.ReferenceImage, - typing.Awaitable[product_search_service.ReferenceImage], + Awaitable[product_search_service.ReferenceImage], ], ]: raise NotImplementedError() @@ -535,29 +606,29 @@ def get_reference_image( @property def add_product_to_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.AddProductToProductSetRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def remove_product_from_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.RemoveProductFromProductSetRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def list_products_in_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.ListProductsInProductSetRequest], - typing.Union[ + Union[ product_search_service.ListProductsInProductSetResponse, - typing.Awaitable[product_search_service.ListProductsInProductSetResponse], + Awaitable[product_search_service.ListProductsInProductSetResponse], ], ]: raise NotImplementedError() @@ -565,18 +636,18 @@ def list_products_in_product_set( @property def import_product_sets( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.ImportProductSetsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def purge_products( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.PurgeProductsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/vision_v1/services/product_search/transports/grpc.py b/google/cloud/vision_v1/services/product_search/transports/grpc.py index 48c62d94..0bc4a2d3 100644 --- a/google/cloud/vision_v1/services/product_search/transports/grpc.py +++ b/google/cloud/vision_v1/services/product_search/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # 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 typing import Callable, Dict, Optional, Sequence, Tuple, Union 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 +import google.auth # type: ignore +from google.auth import credentials as ga_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 google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO @@ -70,7 +67,7 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -84,7 +81,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -195,7 +193,7 @@ def __init__( def create_channel( cls, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -226,13 +224,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -396,7 +396,7 @@ def update_product_set( @property def delete_product_set( self, - ) -> Callable[[product_search_service.DeleteProductSetRequest], empty.Empty]: + ) -> Callable[[product_search_service.DeleteProductSetRequest], empty_pb2.Empty]: r"""Return a callable for the delete product set method over gRPC. Permanently deletes a ProductSet. Products and @@ -418,7 +418,7 @@ def delete_product_set( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_product_set"] @@ -571,7 +571,7 @@ def update_product( @property def delete_product( self, - ) -> Callable[[product_search_service.DeleteProductRequest], empty.Empty]: + ) -> Callable[[product_search_service.DeleteProductRequest], empty_pb2.Empty]: r"""Return a callable for the delete product method over gRPC. Permanently deletes a product and its reference @@ -595,7 +595,7 @@ def delete_product( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_product"] @@ -652,7 +652,9 @@ def create_reference_image( @property def delete_reference_image( self, - ) -> Callable[[product_search_service.DeleteReferenceImageRequest], empty.Empty]: + ) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], empty_pb2.Empty + ]: r"""Return a callable for the delete reference image method over gRPC. Permanently deletes a reference image. @@ -677,7 +679,7 @@ def delete_reference_image( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_reference_image"] @@ -752,7 +754,9 @@ def get_reference_image( @property def add_product_to_product_set( self, - ) -> Callable[[product_search_service.AddProductToProductSetRequest], empty.Empty]: + ) -> Callable[ + [product_search_service.AddProductToProductSetRequest], empty_pb2.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 @@ -779,7 +783,7 @@ def add_product_to_product_set( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["add_product_to_product_set"] @@ -787,7 +791,7 @@ def add_product_to_product_set( def remove_product_from_product_set( self, ) -> Callable[ - [product_search_service.RemoveProductFromProductSetRequest], empty.Empty + [product_search_service.RemoveProductFromProductSetRequest], empty_pb2.Empty ]: r"""Return a callable for the remove product from product set method over gRPC. @@ -810,7 +814,7 @@ def 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["remove_product_from_product_set"] @@ -854,7 +858,7 @@ def list_products_in_product_set( def import_product_sets( self, ) -> Callable[ - [product_search_service.ImportProductSetsRequest], operations.Operation + [product_search_service.ImportProductSetsRequest], operations_pb2.Operation ]: r"""Return a callable for the import product sets method over gRPC. @@ -885,14 +889,16 @@ def import_product_sets( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_product_sets"] @property def purge_products( self, - ) -> Callable[[product_search_service.PurgeProductsRequest], operations.Operation]: + ) -> Callable[ + [product_search_service.PurgeProductsRequest], operations_pb2.Operation + ]: r"""Return a callable for the purge products method over gRPC. Asynchronous API to delete all Products in a ProductSet or all @@ -937,7 +943,7 @@ def purge_products( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["purge_products"] 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 index 765e0f9e..46e4c36b 100644 --- a/google/cloud/vision_v1/services/product_search/transports/grpc_asyncio.py +++ b/google/cloud/vision_v1/services/product_search/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union 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 import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version 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 google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .grpc import ProductSearchGrpcTransport @@ -73,7 +70,7 @@ class ProductSearchGrpcAsyncIOTransport(ProductSearchTransport): def create_channel( cls, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -100,13 +97,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -114,7 +113,7 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -128,7 +127,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -187,7 +187,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -404,7 +403,7 @@ def update_product_set( def delete_product_set( self, ) -> Callable[ - [product_search_service.DeleteProductSetRequest], Awaitable[empty.Empty] + [product_search_service.DeleteProductSetRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete product set method over gRPC. @@ -427,7 +426,7 @@ def delete_product_set( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_product_set"] @@ -584,7 +583,7 @@ def update_product( def delete_product( self, ) -> Callable[ - [product_search_service.DeleteProductRequest], Awaitable[empty.Empty] + [product_search_service.DeleteProductRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete product method over gRPC. @@ -609,7 +608,7 @@ def delete_product( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_product"] @@ -667,7 +666,7 @@ def create_reference_image( def delete_reference_image( self, ) -> Callable[ - [product_search_service.DeleteReferenceImageRequest], Awaitable[empty.Empty] + [product_search_service.DeleteReferenceImageRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete reference image method over gRPC. @@ -693,7 +692,7 @@ def delete_reference_image( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_reference_image"] @@ -769,7 +768,8 @@ def get_reference_image( def add_product_to_product_set( self, ) -> Callable[ - [product_search_service.AddProductToProductSetRequest], Awaitable[empty.Empty] + [product_search_service.AddProductToProductSetRequest], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the add product to product set method over gRPC. @@ -797,7 +797,7 @@ def add_product_to_product_set( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["add_product_to_product_set"] @@ -806,7 +806,7 @@ def remove_product_from_product_set( self, ) -> Callable[ [product_search_service.RemoveProductFromProductSetRequest], - Awaitable[empty.Empty], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the remove product from product set method over gRPC. @@ -829,7 +829,7 @@ def 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["remove_product_from_product_set"] @@ -874,7 +874,7 @@ def import_product_sets( self, ) -> Callable[ [product_search_service.ImportProductSetsRequest], - Awaitable[operations.Operation], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the import product sets method over gRPC. @@ -905,7 +905,7 @@ def import_product_sets( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_product_sets"] @@ -913,7 +913,8 @@ def import_product_sets( def purge_products( self, ) -> Callable[ - [product_search_service.PurgeProductsRequest], Awaitable[operations.Operation] + [product_search_service.PurgeProductsRequest], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the purge products method over gRPC. @@ -959,7 +960,7 @@ def purge_products( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["purge_products"] diff --git a/google/cloud/vision_v1/types/__init__.py b/google/cloud/vision_v1/types/__init__.py index 1bb08bbd..497df9a2 100644 --- a/google/cloud/vision_v1/types/__init__.py +++ b/google/cloud/vision_v1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .geometry import ( BoundingPoly, NormalizedVertex, diff --git a/google/cloud/vision_v1/types/geometry.py b/google/cloud/vision_v1/types/geometry.py index 05db4f69..c30f0162 100644 --- a/google/cloud/vision_v1/types/geometry.py +++ b/google/cloud/vision_v1/types/geometry.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -36,9 +34,8 @@ class Vertex(proto.Message): Y coordinate. """ - x = proto.Field(proto.INT32, number=1) - - y = proto.Field(proto.INT32, number=2) + x = proto.Field(proto.INT32, number=1,) + y = proto.Field(proto.INT32, number=2,) class NormalizedVertex(proto.Message): @@ -53,14 +50,12 @@ class NormalizedVertex(proto.Message): Y coordinate. """ - x = proto.Field(proto.FLOAT, number=1) - - y = proto.Field(proto.FLOAT, number=2) + 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[google.cloud.vision_v1.types.Vertex]): The bounding polygon vertices. @@ -69,7 +64,6 @@ class BoundingPoly(proto.Message): """ vertices = proto.RepeatedField(proto.MESSAGE, number=1, message="Vertex",) - normalized_vertices = proto.RepeatedField( proto.MESSAGE, number=2, message="NormalizedVertex", ) @@ -90,11 +84,9 @@ class Position(proto.Message): 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) + 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 index 2a69494e..6ae4d5ae 100644 --- a/google/cloud/vision_v1/types/image_annotator.py +++ b/google/cloud/vision_v1/types/image_annotator.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,18 +13,16 @@ # 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 +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import color_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore __protobuf__ = proto.module( @@ -122,10 +119,8 @@ class Type(proto.Enum): 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) + max_results = proto.Field(proto.INT32, number=2,) + model = proto.Field(proto.STRING, number=3,) class ImageSource(proto.Message): @@ -163,14 +158,12 @@ class ImageSource(proto.Message): ``image_uri`` takes precedence. """ - gcs_image_uri = proto.Field(proto.STRING, number=1) - - image_uri = proto.Field(proto.STRING, number=2) + 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 @@ -187,8 +180,7 @@ class Image(proto.Message): perform the image annotation request. """ - content = proto.Field(proto.BYTES, number=1) - + content = proto.Field(proto.BYTES, number=1,) source = proto.Field(proto.MESSAGE, number=2, message="ImageSource",) @@ -250,7 +242,6 @@ class FaceAnnotation(proto.Message): class Landmark(proto.Message): r"""A face-specific landmark (for example, a face feature). - Attributes: type_ (google.cloud.vision_v1.types.FaceAnnotation.Landmark.Type): Face landmark type. @@ -303,56 +294,39 @@ class Type(proto.Enum): RIGHT_CHEEK_CENTER = 36 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) - + 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 (google.type.latlng_pb2.LatLng): lat/long location coordinates. """ - lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng.LatLng,) + lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng_pb2.LatLng,) class Property(proto.Message): r"""A ``Property`` consists of a user-supplied name/value pair. - Attributes: name (str): Name of the property. @@ -362,16 +336,13 @@ class Property(proto.Message): 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) + 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 @@ -414,28 +385,19 @@ class EntityAnnotation(proto.Message): 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) - + 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 @@ -453,14 +415,10 @@ class LocalizedObjectAnnotation(proto.Message): 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) - + 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,) @@ -512,31 +470,20 @@ class SafeSearchAnnotation(proto.Message): """ 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) + 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 (google.type.latlng_pb2.LatLng): Min lat/long pair. @@ -544,9 +491,8 @@ class LatLongRect(proto.Message): 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,) + min_lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng_pb2.LatLng,) + max_lat_lng = proto.Field(proto.MESSAGE, number=2, message=latlng_pb2.LatLng,) class ColorInfo(proto.Message): @@ -563,16 +509,13 @@ class ColorInfo(proto.Message): 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) + color = proto.Field(proto.MESSAGE, number=1, message=color_pb2.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[google.cloud.vision_v1.types.ColorInfo]): RGB color values with their score and pixel @@ -584,7 +527,6 @@ class DominantColorsAnnotation(proto.Message): class ImageProperties(proto.Message): r"""Stores image properties, such as dominant colors. - Attributes: dominant_colors (google.cloud.vision_v1.types.DominantColorsAnnotation): If present, dominant colors completed @@ -613,10 +555,8 @@ class CropHint(proto.Message): """ 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) + confidence = proto.Field(proto.FLOAT, number=2,) + importance_fraction = proto.Field(proto.FLOAT, number=3,) class CropHintsAnnotation(proto.Message): @@ -633,7 +573,6 @@ class CropHintsAnnotation(proto.Message): class CropHintsParams(proto.Message): r"""Parameters for crop hints annotation request. - Attributes: aspect_ratios (Sequence[float]): Aspect ratios in floats, representing the @@ -646,19 +585,18 @@ class CropHintsParams(proto.Message): provided after the 16th are ignored. """ - aspect_ratios = proto.RepeatedField(proto.FLOAT, number=1) + 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) + include_geo_results = proto.Field(proto.BOOL, number=2,) class TextDetectionParams(proto.Message): @@ -672,12 +610,11 @@ class TextDetectionParams(proto.Message): include confidence score for TEXT_DETECTION as well. """ - enable_text_detection_confidence_score = proto.Field(proto.BOOL, number=9) + enable_text_detection_confidence_score = proto.Field(proto.BOOL, number=9,) class ImageContext(proto.Message): r"""Image context and/or feature-specific parameters. - Attributes: lat_long_rect (google.cloud.vision_v1.types.LatLongRect): Not used. @@ -704,19 +641,14 @@ class ImageContext(proto.Message): """ lat_long_rect = proto.Field(proto.MESSAGE, number=1, message="LatLongRect",) - - language_hints = proto.RepeatedField(proto.STRING, number=2) - + 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", ) - text_detection_params = proto.Field( proto.MESSAGE, number=12, message="TextDetectionParams", ) @@ -738,9 +670,7 @@ class AnnotateImageRequest(proto.Message): """ 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",) @@ -758,14 +688,12 @@ class ImageAnnotationContext(proto.Message): produce the image. """ - uri = proto.Field(proto.STRING, number=1) - - page_number = proto.Field(proto.INT32, number=2) + 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[google.cloud.vision_v1.types.FaceAnnotation]): If present, face detection has completed @@ -818,53 +746,40 @@ class AnnotateImageResponse(proto.Message): 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,) - + error = proto.Field(proto.MESSAGE, number=9, message=status_pb2.Status,) context = proto.Field(proto.MESSAGE, number=21, message="ImageAnnotationContext",) @@ -894,13 +809,11 @@ class BatchAnnotateImagesRequest(proto.Message): requests = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateImageRequest", ) - - parent = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=4,) class BatchAnnotateImagesResponse(proto.Message): r"""Response to a batch image annotation request. - Attributes: responses (Sequence[google.cloud.vision_v1.types.AnnotateImageResponse]): Individual responses to image annotation @@ -943,12 +856,9 @@ class AnnotateFileRequest(proto.Message): """ 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) + pages = proto.RepeatedField(proto.INT32, number=4,) class AnnotateFileResponse(proto.Message): @@ -972,14 +882,11 @@ class AnnotateFileResponse(proto.Message): """ 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,) + total_pages = proto.Field(proto.INT32, number=3,) + error = proto.Field(proto.MESSAGE, number=4, message=status_pb2.Status,) class BatchAnnotateFilesRequest(proto.Message): @@ -1010,13 +917,11 @@ class BatchAnnotateFilesRequest(proto.Message): requests = proto.RepeatedField( proto.MESSAGE, number=1, message="AnnotateFileRequest", ) - - parent = proto.Field(proto.STRING, number=3) + parent = proto.Field(proto.STRING, number=3,) class BatchAnnotateFilesResponse(proto.Message): r"""A list of file annotation responses. - Attributes: responses (Sequence[google.cloud.vision_v1.types.AnnotateFileResponse]): The list of file annotation responses, each @@ -1032,7 +937,6 @@ class BatchAnnotateFilesResponse(proto.Message): class AsyncAnnotateFileRequest(proto.Message): r"""An offline file annotation request. - Attributes: input_config (google.cloud.vision_v1.types.InputConfig): Required. Information about the input file. @@ -1047,17 +951,13 @@ class AsyncAnnotateFileRequest(proto.Message): """ 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 (google.cloud.vision_v1.types.OutputConfig): The output location and metadata from @@ -1069,7 +969,6 @@ class AsyncAnnotateFileResponse(proto.Message): class AsyncBatchAnnotateImagesRequest(proto.Message): r"""Request for async image annotation for a list of images. - Attributes: requests (Sequence[google.cloud.vision_v1.types.AnnotateImageRequest]): Required. Individual image annotation @@ -1095,15 +994,12 @@ class AsyncBatchAnnotateImagesRequest(proto.Message): 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) + parent = proto.Field(proto.STRING, number=4,) class AsyncBatchAnnotateImagesResponse(proto.Message): r"""Response to an async batch image annotation request. - Attributes: output_config (google.cloud.vision_v1.types.OutputConfig): The output location and metadata from @@ -1139,13 +1035,11 @@ class AsyncBatchAnnotateFilesRequest(proto.Message): requests = proto.RepeatedField( proto.MESSAGE, number=1, message="AsyncAnnotateFileRequest", ) - - parent = proto.Field(proto.STRING, number=4) + parent = proto.Field(proto.STRING, number=4,) class AsyncBatchAnnotateFilesResponse(proto.Message): r"""Response to an async batch file annotation request. - Attributes: responses (Sequence[google.cloud.vision_v1.types.AsyncAnnotateFileResponse]): The list of file annotation responses, one @@ -1160,7 +1054,6 @@ class AsyncBatchAnnotateFilesResponse(proto.Message): class InputConfig(proto.Message): r"""The desired input location and metadata. - Attributes: gcs_source (google.cloud.vision_v1.types.GcsSource): The Google Cloud Storage location to read the @@ -1180,15 +1073,12 @@ class InputConfig(proto.Message): """ 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) + 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 (google.cloud.vision_v1.types.GcsDestination): The Google Cloud Storage location to write @@ -1208,8 +1098,7 @@ class OutputConfig(proto.Message): """ gcs_destination = proto.Field(proto.MESSAGE, number=1, message="GcsDestination",) - - batch_size = proto.Field(proto.INT32, number=2) + batch_size = proto.Field(proto.INT32, number=2,) class GcsSource(proto.Message): @@ -1223,7 +1112,7 @@ class GcsSource(proto.Message): Wildcards are not currently supported. """ - uri = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) class GcsDestination(proto.Message): @@ -1260,12 +1149,11 @@ class GcsDestination(proto.Message): overflows into multiple sharded files. """ - uri = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) class OperationMetadata(proto.Message): r"""Contains metadata for the BatchAnnotateImages operation. - Attributes: state (google.cloud.vision_v1.types.OperationMetadata.State): Current state of the batch operation. @@ -1285,10 +1173,8 @@ class State(proto.Enum): 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,) + create_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + update_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.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 index d28d3390..17364f24 100644 --- a/google/cloud/vision_v1/types/product_search.py +++ b/google/cloud/vision_v1/types/product_search.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # 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 +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -31,7 +28,6 @@ class ProductSearchParams(proto.Message): r"""Parameters for a product search request. - Attributes: bounding_poly (google.cloud.vision_v1.types.BoundingPoly): The bounding polygon around the area of @@ -71,17 +67,13 @@ class ProductSearchParams(proto.Message): """ 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) + 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 (google.protobuf.timestamp_pb2.Timestamp): Timestamp of the index which provided these @@ -101,7 +93,6 @@ class ProductSearchResults(proto.Message): class Result(proto.Message): r"""Information about a product. - Attributes: product (google.cloud.vision_v1.types.Product): The Product. @@ -116,14 +107,11 @@ class Result(proto.Message): 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) + 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 @@ -138,13 +126,10 @@ class ObjectAnnotation(proto.Message): 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) + 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 @@ -164,19 +149,15 @@ class GroupedResult(proto.Message): 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,) - + index_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) results = proto.RepeatedField(proto.MESSAGE, number=5, message=Result,) - product_grouped_results = proto.RepeatedField( proto.MESSAGE, number=6, message=GroupedResult, ) diff --git a/google/cloud/vision_v1/types/product_search_service.py b/google/cloud/vision_v1/types/product_search_service.py index 65cb5d7f..269230e9 100644 --- a/google/cloud/vision_v1/types/product_search_service.py +++ b/google/cloud/vision_v1/types/product_search_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # 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 +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -64,7 +61,6 @@ class Product(proto.Message): r"""A Product contains ReferenceImages. - Attributes: name (str): The resource name of the product. @@ -108,7 +104,6 @@ class Product(proto.Message): 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. @@ -119,18 +114,13 @@ class KeyValue(proto.Message): 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) + 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,) @@ -169,13 +159,10 @@ class ProductSet(proto.Message): 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,) + 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_pb2.Timestamp,) + index_error = proto.Field(proto.MESSAGE, number=4, message=status_pb2.Status,) class ReferenceImage(proto.Message): @@ -208,10 +195,8 @@ class ReferenceImage(proto.Message): 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) - + 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, ) @@ -219,7 +204,6 @@ class ReferenceImage(proto.Message): class CreateProductRequest(proto.Message): r"""Request message for the ``CreateProduct`` method. - Attributes: parent (str): Required. The project in which the Product should be @@ -236,16 +220,13 @@ class CreateProductRequest(proto.Message): cannot contain the character ``/``. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) product = proto.Field(proto.MESSAGE, number=2, message="Product",) - - product_id = proto.Field(proto.STRING, number=3) + 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 @@ -260,16 +241,13 @@ class ListProductsRequest(proto.Message): 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) + 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[google.cloud.vision_v1.types.Product]): List of products. @@ -284,13 +262,11 @@ def raw_page(self): return self products = proto.RepeatedField(proto.MESSAGE, number=1, message="Product",) - - next_page_token = proto.Field(proto.STRING, number=2) + 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. @@ -299,12 +275,11 @@ class GetProductRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateProductRequest(proto.Message): r"""Request message for the ``UpdateProduct`` method. - Attributes: product (google.cloud.vision_v1.types.Product): Required. The Product resource which replaces @@ -318,13 +293,13 @@ class UpdateProductRequest(proto.Message): """ product = proto.Field(proto.MESSAGE, number=1, message="Product",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteProductRequest(proto.Message): r"""Request message for the ``DeleteProduct`` method. - Attributes: name (str): Required. Resource name of product to delete. @@ -333,12 +308,11 @@ class DeleteProductRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field(proto.STRING, number=1) + 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 @@ -355,16 +329,13 @@ class CreateProductSetRequest(proto.Message): cannot contain the character ``/``. """ - parent = proto.Field(proto.STRING, number=1) - + 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) + 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 @@ -379,16 +350,13 @@ class ListProductSetsRequest(proto.Message): 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) + 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[google.cloud.vision_v1.types.ProductSet]): List of ProductSets. @@ -403,13 +371,11 @@ 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) + 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. @@ -418,12 +384,11 @@ class GetProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateProductSetRequest(proto.Message): r"""Request message for the ``UpdateProductSet`` method. - Attributes: product_set (google.cloud.vision_v1.types.ProductSet): Required. The ProductSet resource which @@ -436,13 +401,13 @@ class UpdateProductSetRequest(proto.Message): """ product_set = proto.Field(proto.MESSAGE, number=1, message="ProductSet",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteProductSetRequest(proto.Message): r"""Request message for the ``DeleteProductSet`` method. - Attributes: name (str): Required. Resource name of the ProductSet to delete. @@ -451,12 +416,11 @@ class DeleteProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` """ - name = proto.Field(proto.STRING, number=1) + 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 @@ -475,16 +439,13 @@ class CreateReferenceImageRequest(proto.Message): characters long. It cannot contain the character ``/``. """ - parent = proto.Field(proto.STRING, number=1) - + 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) + 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 @@ -503,16 +464,13 @@ class ListReferenceImagesRequest(proto.Message): 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) + 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[google.cloud.vision_v1.types.ReferenceImage]): The list of reference images. @@ -531,15 +489,12 @@ def raw_page(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) + 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. @@ -548,12 +503,11 @@ class GetReferenceImageRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. """ - name = proto.Field(proto.STRING, number=1) + 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 @@ -563,12 +517,11 @@ class DeleteReferenceImageRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` """ - name = proto.Field(proto.STRING, number=1) + 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. @@ -583,14 +536,12 @@ class AddProductToProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field(proto.STRING, number=1) - - product = proto.Field(proto.STRING, number=2) + 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. @@ -605,14 +556,12 @@ class RemoveProductFromProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field(proto.STRING, number=1) - - product = proto.Field(proto.STRING, number=2) + 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 @@ -628,16 +577,13 @@ class ListProductsInProductSetRequest(proto.Message): 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) + 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[google.cloud.vision_v1.types.Product]): The list of Products. @@ -652,8 +598,7 @@ def raw_page(self): return self products = proto.RepeatedField(proto.MESSAGE, number=1, message="Product",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class ImportProductSetsGcsSource(proto.Message): @@ -737,12 +682,11 @@ class ImportProductSetsGcsSource(proto.Message): too large to process (larger than 20MP). """ - csv_file_uri = proto.Field(proto.STRING, number=1) + csv_file_uri = proto.Field(proto.STRING, number=1,) class ImportProductSetsInputConfig(proto.Message): r"""The input content for the ``ImportProductSets`` method. - Attributes: gcs_source (google.cloud.vision_v1.types.ImportProductSetsGcsSource): The Google Cloud Storage location for a csv @@ -757,7 +701,6 @@ class ImportProductSetsInputConfig(proto.Message): class ImportProductSetsRequest(proto.Message): r"""Request message for the ``ImportProductSets`` method. - Attributes: parent (str): Required. The project in which the ProductSets should be @@ -769,8 +712,7 @@ class ImportProductSetsRequest(proto.Message): requests. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) input_config = proto.Field( proto.MESSAGE, number=2, message="ImportProductSetsInputConfig", ) @@ -801,8 +743,7 @@ class ImportProductSetsResponse(proto.Message): reference_images = proto.RepeatedField( proto.MESSAGE, number=1, message="ReferenceImage", ) - - statuses = proto.RepeatedField(proto.MESSAGE, number=2, message=status.Status,) + statuses = proto.RepeatedField(proto.MESSAGE, number=2, message=status_pb2.Status,) class BatchOperationMetadata(proto.Message): @@ -835,10 +776,8 @@ class State(proto.Enum): 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,) + submit_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) class ProductSetPurgeConfig(proto.Message): @@ -852,12 +791,11 @@ class ProductSetPurgeConfig(proto.Message): ProductSets, the Product will still be deleted. """ - product_set_id = proto.Field(proto.STRING, number=1) + 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 (google.cloud.vision_v1.types.ProductSetPurgeConfig): Specify which ProductSet contains the @@ -878,12 +816,9 @@ class PurgeProductsRequest(proto.Message): 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) + 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 index 3f8e73a8..224fe7c0 100644 --- a/google/cloud/vision_v1/types/text_annotation.py +++ b/google/cloud/vision_v1/types/text_annotation.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # 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 @@ -46,7 +43,6 @@ class TextAnnotation(proto.Message): 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 @@ -56,13 +52,11 @@ class DetectedLanguage(proto.Message): Confidence of detected language. Range [0, 1]. """ - language_code = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) + 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_ (google.cloud.vision_v1.types.TextAnnotation.DetectedBreak.BreakType): Detected break type. @@ -82,12 +76,10 @@ class BreakType(proto.Enum): type_ = proto.Field( proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", ) - - is_prefix = proto.Field(proto.BOOL, number=2) + is_prefix = proto.Field(proto.BOOL, number=2,) class TextProperty(proto.Message): r"""Additional information detected on the structural component. - Attributes: detected_languages (Sequence[google.cloud.vision_v1.types.TextAnnotation.DetectedLanguage]): A list of detected languages together with @@ -99,19 +91,16 @@ class TextProperty(proto.Message): 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) + text = proto.Field(proto.STRING, number=2,) class Page(proto.Message): r"""Detected page from OCR. - Attributes: property (google.cloud.vision_v1.types.TextAnnotation.TextProperty): Additional information detected on the page. @@ -131,19 +120,14 @@ class Page(proto.Message): property = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - - width = proto.Field(proto.INT32, number=2) - - height = proto.Field(proto.INT32, number=3) - + 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) + confidence = proto.Field(proto.FLOAT, number=5,) class Block(proto.Message): r"""Logical element on the page. - Attributes: property (google.cloud.vision_v1.types.TextAnnotation.TextProperty): Additional information detected for the @@ -195,14 +179,10 @@ class BlockType(proto.Enum): 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) + confidence = proto.Field(proto.FLOAT, number=5,) class Paragraph(proto.Message): @@ -235,17 +215,13 @@ class Paragraph(proto.Message): 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) + confidence = proto.Field(proto.FLOAT, number=4,) class Word(proto.Message): r"""A word representation. - Attributes: property (google.cloud.vision_v1.types.TextAnnotation.TextProperty): Additional information detected for the word. @@ -272,17 +248,13 @@ class Word(proto.Message): 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) + confidence = proto.Field(proto.FLOAT, number=4,) class Symbol(proto.Message): r"""A single symbol representation. - Attributes: property (google.cloud.vision_v1.types.TextAnnotation.TextProperty): Additional information detected for the @@ -309,12 +281,9 @@ class Symbol(proto.Message): 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) + 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 index 7aa82a25..c629b85a 100644 --- a/google/cloud/vision_v1/types/web_detection.py +++ b/google/cloud/vision_v1/types/web_detection.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -25,7 +23,6 @@ class WebDetection(proto.Message): r"""Relevant information for the image from the Internet. - Attributes: web_entities (Sequence[google.cloud.vision_v1.types.WebDetection.WebEntity]): Deduced entities from similar images on the @@ -52,7 +49,6 @@ class WebDetection(proto.Message): class WebEntity(proto.Message): r"""Entity deduced from similar images on the Internet. - Attributes: entity_id (str): Opaque entity ID. @@ -65,15 +61,12 @@ class WebEntity(proto.Message): English. """ - entity_id = proto.Field(proto.STRING, number=1) - - score = proto.Field(proto.FLOAT, number=2) - - description = proto.Field(proto.STRING, number=3) + 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. @@ -82,13 +75,11 @@ class WebImage(proto.Message): image. """ - url = proto.Field(proto.STRING, number=1) - - score = proto.Field(proto.FLOAT, number=2) + 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. @@ -109,23 +100,18 @@ class WebPage(proto.Message): crops. """ - url = proto.Field(proto.STRING, number=1) - - score = proto.Field(proto.FLOAT, number=2) - - page_title = proto.Field(proto.STRING, number=3) - + 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. @@ -135,28 +121,22 @@ class WebLabel(proto.Message): http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. """ - label = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + 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,) diff --git a/google/cloud/vision_v1p1beta1/__init__.py b/google/cloud/vision_v1p1beta1/__init__.py index 65a2aaac..84c64ab0 100644 --- a/google/cloud/vision_v1p1beta1/__init__.py +++ b/google/cloud/vision_v1p1beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -19,6 +18,8 @@ from google.cloud.vision_helpers import VisionHelpers from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient +from .services.image_annotator import ImageAnnotatorAsyncClient + from .types.geometry import BoundingPoly from .types.geometry import Position from .types.geometry import Vertex @@ -39,12 +40,12 @@ 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 TextDetectionParams from .types.image_annotator import WebDetectionParams +from .types.image_annotator import Likelihood from .types.text_annotation import Block from .types.text_annotation import Page from .types.text_annotation import Paragraph @@ -61,6 +62,7 @@ class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): __all__ = ( + "ImageAnnotatorAsyncClient", "AnnotateImageRequest", "AnnotateImageResponse", "BatchAnnotateImagesRequest", @@ -76,6 +78,7 @@ class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): "FaceAnnotation", "Feature", "Image", + "ImageAnnotatorClient", "ImageContext", "ImageProperties", "ImageSource", @@ -94,5 +97,4 @@ class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): "WebDetection", "WebDetectionParams", "Word", - "ImageAnnotatorClient", ) diff --git a/google/cloud/vision_v1p1beta1/proto/geometry.proto b/google/cloud/vision_v1p1beta1/proto/geometry.proto deleted file mode 100644 index 6d46d9c3..00000000 --- a/google/cloud/vision_v1p1beta1/proto/geometry.proto +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2017 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.v1p1beta1; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p1beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "GeometryProto"; -option java_package = "com.google.cloud.vision.v1p1beta1"; - -// A vertex represents a 2D point in the image. -// NOTE: the vertex coordinates are in the same scale as the original image. -message Vertex { - // X coordinate. - int32 x = 1; - - // Y coordinate. - int32 y = 2; -} - -// A bounding polygon for the detected image annotation. -message BoundingPoly { - // The bounding polygon vertices. - repeated Vertex vertices = 1; -} - -// 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. -message Position { - // X coordinate. - float x = 1; - - // Y coordinate. - float y = 2; - - // Z coordinate (or depth). - float z = 3; -} diff --git a/google/cloud/vision_v1p1beta1/proto/image_annotator.proto b/google/cloud/vision_v1p1beta1/proto/image_annotator.proto deleted file mode 100644 index daf6a2d2..00000000 --- a/google/cloud/vision_v1p1beta1/proto/image_annotator.proto +++ /dev/null @@ -1,614 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.vision.v1p1beta1; - -import "google/api/annotations.proto"; -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; -import "google/cloud/vision/v1p1beta1/geometry.proto"; -import "google/cloud/vision/v1p1beta1/text_annotation.proto"; -import "google/cloud/vision/v1p1beta1/web_detection.proto"; -import "google/rpc/status.proto"; -import "google/type/color.proto"; -import "google/type/latlng.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p1beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "ImageAnnotatorProto"; -option java_package = "com.google.cloud.vision.v1p1beta1"; - -// 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 ImageAnnotator { - option (google.api.default_host) = "vision.googleapis.com"; - option (google.api.oauth_scopes) = - "https://www.googleapis.com/auth/cloud-platform," - "https://www.googleapis.com/auth/cloud-vision"; - - // Run image detection and annotation for a batch of images. - rpc BatchAnnotateImages(BatchAnnotateImagesRequest) - returns (BatchAnnotateImagesResponse) { - option (google.api.http) = { - post: "/v1p1beta1/images:annotate" - body: "*" - }; - option (google.api.method_signature) = "requests"; - } -} - -// 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. -message Feature { - // Type of image feature. - enum Type { - // Unspecified feature type. - TYPE_UNSPECIFIED = 0; - - // Run face detection. - FACE_DETECTION = 1; - - // Run landmark detection. - LANDMARK_DETECTION = 2; - - // Run logo detection. - LOGO_DETECTION = 3; - - // Run label detection. - LABEL_DETECTION = 4; - - // Run OCR. - TEXT_DETECTION = 5; - - // Run dense text document OCR. Takes precedence when both - // DOCUMENT_TEXT_DETECTION and TEXT_DETECTION are present. - DOCUMENT_TEXT_DETECTION = 11; - - // Run computer vision models to compute image safe-search properties. - SAFE_SEARCH_DETECTION = 6; - - // Compute a set of image properties, such as the image's dominant colors. - IMAGE_PROPERTIES = 7; - - // Run crop hints. - CROP_HINTS = 9; - - // Run web detection. - WEB_DETECTION = 10; - } - - // The feature type. - Type type = 1; - - // Maximum number of results of this type. - int32 max_results = 2; - - // Model to use for the feature. - // Supported values: "builtin/stable" (the default if unset) and - // "builtin/latest". - string model = 3; -} - -// External image source (Google Cloud Storage image location). -message ImageSource { - // 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](https://cloud.google.com/storage/docs/reference-uris)). - // NOTE: Cloud Storage object versioning is not supported. - string gcs_image_uri = 1; - - // 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](https://cloud.google.com/storage/docs/reference-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. - string image_uri = 2; -} - -// Client image to perform Google Cloud Vision API tasks over. -message Image { - // 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. - bytes content = 1; - - // 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. - ImageSource source = 2; -} - -// A face annotation object contains the results of face detection. -message FaceAnnotation { - // A face-specific landmark (for example, a face feature). - message Landmark { - // 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. - enum Type { - // Unknown face landmark detected. Should not be filled. - UNKNOWN_LANDMARK = 0; - - // Left eye. - LEFT_EYE = 1; - - // Right eye. - RIGHT_EYE = 2; - - // Left of left eyebrow. - LEFT_OF_LEFT_EYEBROW = 3; - - // Right of left eyebrow. - RIGHT_OF_LEFT_EYEBROW = 4; - - // Left of right eyebrow. - LEFT_OF_RIGHT_EYEBROW = 5; - - // Right of right eyebrow. - RIGHT_OF_RIGHT_EYEBROW = 6; - - // Midpoint between eyes. - MIDPOINT_BETWEEN_EYES = 7; - - // Nose tip. - NOSE_TIP = 8; - - // Upper lip. - UPPER_LIP = 9; - - // Lower lip. - LOWER_LIP = 10; - - // Mouth left. - MOUTH_LEFT = 11; - - // Mouth right. - MOUTH_RIGHT = 12; - - // Mouth center. - MOUTH_CENTER = 13; - - // Nose, bottom right. - NOSE_BOTTOM_RIGHT = 14; - - // Nose, bottom left. - NOSE_BOTTOM_LEFT = 15; - - // Nose, bottom center. - NOSE_BOTTOM_CENTER = 16; - - // Left eye, top boundary. - LEFT_EYE_TOP_BOUNDARY = 17; - - // Left eye, right corner. - LEFT_EYE_RIGHT_CORNER = 18; - - // Left eye, bottom boundary. - LEFT_EYE_BOTTOM_BOUNDARY = 19; - - // Left eye, left corner. - LEFT_EYE_LEFT_CORNER = 20; - - // Right eye, top boundary. - RIGHT_EYE_TOP_BOUNDARY = 21; - - // Right eye, right corner. - RIGHT_EYE_RIGHT_CORNER = 22; - - // Right eye, bottom boundary. - RIGHT_EYE_BOTTOM_BOUNDARY = 23; - - // Right eye, left corner. - RIGHT_EYE_LEFT_CORNER = 24; - - // Left eyebrow, upper midpoint. - LEFT_EYEBROW_UPPER_MIDPOINT = 25; - - // Right eyebrow, upper midpoint. - RIGHT_EYEBROW_UPPER_MIDPOINT = 26; - - // Left ear tragion. - LEFT_EAR_TRAGION = 27; - - // Right ear tragion. - RIGHT_EAR_TRAGION = 28; - - // Left eye pupil. - LEFT_EYE_PUPIL = 29; - - // Right eye pupil. - RIGHT_EYE_PUPIL = 30; - - // Forehead glabella. - FOREHEAD_GLABELLA = 31; - - // Chin gnathion. - CHIN_GNATHION = 32; - - // Chin left gonion. - CHIN_LEFT_GONION = 33; - - // Chin right gonion. - CHIN_RIGHT_GONION = 34; - } - - // Face landmark type. - Type type = 3; - - // Face landmark position. - Position position = 4; - } - - // 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. - BoundingPoly bounding_poly = 1; - - // 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. - BoundingPoly fd_bounding_poly = 2; - - // Detected face landmarks. - repeated Landmark landmarks = 3; - - // 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]. - float roll_angle = 4; - - // 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]. - float pan_angle = 5; - - // Pitch angle, which indicates the upwards/downwards angle that the face is - // pointing relative to the image's horizontal plane. Range [-180,180]. - float tilt_angle = 6; - - // Detection confidence. Range [0, 1]. - float detection_confidence = 7; - - // Face landmarking confidence. Range [0, 1]. - float landmarking_confidence = 8; - - // Joy likelihood. - Likelihood joy_likelihood = 9; - - // Sorrow likelihood. - Likelihood sorrow_likelihood = 10; - - // Anger likelihood. - Likelihood anger_likelihood = 11; - - // Surprise likelihood. - Likelihood surprise_likelihood = 12; - - // Under-exposed likelihood. - Likelihood under_exposed_likelihood = 13; - - // Blurred likelihood. - Likelihood blurred_likelihood = 14; - - // Headwear likelihood. - Likelihood headwear_likelihood = 15; -} - -// Detected entity location information. -message LocationInfo { - // lat/long location coordinates. - google.type.LatLng lat_lng = 1; -} - -// A `Property` consists of a user-supplied name/value pair. -message Property { - // Name of the property. - string name = 1; - - // Value of the property. - string value = 2; - - // Value of numeric properties. - uint64 uint64_value = 3; -} - -// Set of detected entity features. -message EntityAnnotation { - // Opaque entity ID. Some IDs may be available in - // [Google Knowledge Graph Search - // API](https://developers.google.com/knowledge-graph/). - string mid = 1; - - // The language code for the locale in which the entity textual - // `description` is expressed. - string locale = 2; - - // Entity textual description, expressed in its `locale` language. - string description = 3; - - // Overall score of the result. Range [0, 1]. - float score = 4; - - // 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]. - float confidence = 5; - - // 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]. - float topicality = 6; - - // Image region to which this entity belongs. Not produced - // for `LABEL_DETECTION` features. - BoundingPoly bounding_poly = 7; - - // 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. - repeated LocationInfo locations = 8; - - // Some entities may have optional user-supplied `Property` (name/value) - // fields, such a score or string that qualifies the entity. - repeated Property properties = 9; -} - -// Set of features pertaining to the image, computed by computer vision -// methods over safe-search verticals (for example, adult, spoof, medical, -// violence). -message SafeSearchAnnotation { - // Represents the adult content likelihood for the image. Adult content may - // contain elements such as nudity, pornographic images or cartoons, or - // sexual activities. - Likelihood adult = 1; - - // Spoof likelihood. The likelihood that an modification - // was made to the image's canonical version to make it appear - // funny or offensive. - Likelihood spoof = 2; - - // Likelihood that this is a medical image. - Likelihood medical = 3; - - // Likelihood that this image contains violent content. - Likelihood violence = 4; - - // 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. - Likelihood racy = 9; -} - -// Rectangle determined by min and max `LatLng` pairs. -message LatLongRect { - // Min lat/long pair. - google.type.LatLng min_lat_lng = 1; - - // Max lat/long pair. - google.type.LatLng max_lat_lng = 2; -} - -// Color information consists of RGB channels, score, and the fraction of -// the image that the color occupies in the image. -message ColorInfo { - // RGB components of the color. - google.type.Color color = 1; - - // Image-specific score for this color. Value in range [0, 1]. - float score = 2; - - // The fraction of pixels the color occupies in the image. - // Value in range [0, 1]. - float pixel_fraction = 3; -} - -// Set of dominant colors and their corresponding scores. -message DominantColorsAnnotation { - // RGB color values with their score and pixel fraction. - repeated ColorInfo colors = 1; -} - -// Stores image properties, such as dominant colors. -message ImageProperties { - // If present, dominant colors completed successfully. - DominantColorsAnnotation dominant_colors = 1; -} - -// Single crop hint that is used to generate a new crop when serving an image. -message CropHint { - // The bounding polygon for the crop region. The coordinates of the bounding - // box are in the original image's scale, as returned in `ImageParams`. - BoundingPoly bounding_poly = 1; - - // Confidence of this being a salient region. Range [0, 1]. - float confidence = 2; - - // Fraction of importance of this salient region with respect to the original - // image. - float importance_fraction = 3; -} - -// Set of crop hints that are used to generate new crops when serving images. -message CropHintsAnnotation { - // Crop hint results. - repeated CropHint crop_hints = 1; -} - -// Parameters for crop hints annotation request. -message CropHintsParams { - // 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. - repeated float aspect_ratios = 1; -} - -// Parameters for web detection request. -message WebDetectionParams { - // Whether to include results derived from the geo information in the image. - bool include_geo_results = 2; -} - -// Parameters for text detections. This is used to control TEXT_DETECTION and -// DOCUMENT_TEXT_DETECTION features. -message TextDetectionParams { - - // By default, Cloud Vision API only includes confidence score for - // DOCUMENT_TEXT_DETECTION result. Set the flag to true to include confidence - // score for TEXT_DETECTION as well. - bool enable_text_detection_confidence_score = 9; -} - -// Image context and/or feature-specific parameters. -message ImageContext { - // lat/long rectangle that specifies the location of the image. - LatLongRect lat_long_rect = 1; - - // 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](https://cloud.google.com/vision/docs/languages). - repeated string language_hints = 2; - - // Parameters for crop hints annotation request. - CropHintsParams crop_hints_params = 4; - - // Parameters for web detection. - WebDetectionParams web_detection_params = 6; - - // Parameters for text detection and document text detection. - TextDetectionParams text_detection_params = 12; -} - -// Request for performing Google Cloud Vision API tasks over a user-provided -// image, with user-requested features. -message AnnotateImageRequest { - // The image to be processed. - Image image = 1; - - // Requested features. - repeated Feature features = 2; - - // Additional context that may accompany the image. - ImageContext image_context = 3; -} - -// Response to an image annotation request. -message AnnotateImageResponse { - // If present, face detection has completed successfully. - repeated FaceAnnotation face_annotations = 1; - - // If present, landmark detection has completed successfully. - repeated EntityAnnotation landmark_annotations = 2; - - // If present, logo detection has completed successfully. - repeated EntityAnnotation logo_annotations = 3; - - // If present, label detection has completed successfully. - repeated EntityAnnotation label_annotations = 4; - - // If present, text (OCR) detection has completed successfully. - repeated EntityAnnotation text_annotations = 5; - - // If present, text (OCR) detection or document (OCR) text detection has - // completed successfully. - // This annotation provides the structural hierarchy for the OCR detected - // text. - TextAnnotation full_text_annotation = 12; - - // If present, safe-search annotation has completed successfully. - SafeSearchAnnotation safe_search_annotation = 6; - - // If present, image properties were extracted successfully. - ImageProperties image_properties_annotation = 8; - - // If present, crop hints have completed successfully. - CropHintsAnnotation crop_hints_annotation = 11; - - // If present, web detection has completed successfully. - WebDetection web_detection = 13; - - // 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. - google.rpc.Status error = 9; -} - -// Multiple image annotation requests are batched into a single service call. -message BatchAnnotateImagesRequest { - // Required. Individual image annotation requests for this batch. - repeated AnnotateImageRequest requests = 1 [(google.api.field_behavior) = REQUIRED]; -} - -// Response to a batch image annotation request. -message BatchAnnotateImagesResponse { - // Individual responses to image annotation requests within the batch. - repeated AnnotateImageResponse responses = 1; -} - -// A bucketized representation of likelihood, which is intended to give clients -// highly stable results across model upgrades. -enum Likelihood { - // Unknown likelihood. - UNKNOWN = 0; - - // It is very unlikely that the image belongs to the specified vertical. - VERY_UNLIKELY = 1; - - // It is unlikely that the image belongs to the specified vertical. - UNLIKELY = 2; - - // It is possible that the image belongs to the specified vertical. - POSSIBLE = 3; - - // It is likely that the image belongs to the specified vertical. - LIKELY = 4; - - // It is very likely that the image belongs to the specified vertical. - VERY_LIKELY = 5; -} diff --git a/google/cloud/vision_v1p1beta1/proto/text_annotation.proto b/google/cloud/vision_v1p1beta1/proto/text_annotation.proto deleted file mode 100644 index 928e6e88..00000000 --- a/google/cloud/vision_v1p1beta1/proto/text_annotation.proto +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright 2017 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.v1p1beta1; - -import "google/api/annotations.proto"; -import "google/cloud/vision/v1p1beta1/geometry.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p1beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "TextAnnotationProto"; -option java_package = "com.google.cloud.vision.v1p1beta1"; - -// 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. -message TextAnnotation { - // Detected language for a structural component. - message DetectedLanguage { - // 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. - string language_code = 1; - - // Confidence of detected language. Range [0, 1]. - float confidence = 2; - } - - // Detected start or end of a structural component. - message DetectedBreak { - // Enum to denote the type of break found. New line, space etc. - enum BreakType { - // Unknown break label type. - UNKNOWN = 0; - - // Regular space. - SPACE = 1; - - // Sure space (very wide). - SURE_SPACE = 2; - - // Line-wrapping break. - EOL_SURE_SPACE = 3; - - // End-line hyphen that is not present in text; does not co-occur with - // `SPACE`, `LEADER_SPACE`, or `LINE_BREAK`. - HYPHEN = 4; - - // Line break that ends a paragraph. - LINE_BREAK = 5; - } - - // Detected break type. - BreakType type = 1; - - // True if break prepends the element. - bool is_prefix = 2; - } - - // Additional information detected on the structural component. - message TextProperty { - // A list of detected languages together with confidence. - repeated DetectedLanguage detected_languages = 1; - - // Detected start or end of a text segment. - DetectedBreak detected_break = 2; - } - - // List of pages detected by OCR. - repeated Page pages = 1; - - // UTF-8 text detected on the pages. - string text = 2; -} - -// Detected page from OCR. -message Page { - // Additional information detected on the page. - TextAnnotation.TextProperty property = 1; - - // Page width in pixels. - int32 width = 2; - - // Page height in pixels. - int32 height = 3; - - // List of blocks of text, images etc on this page. - repeated Block blocks = 4; - - // Confidence of the OCR results on the page. Range [0, 1]. - float confidence = 5; -} - -// Logical element on the page. -message Block { - // Type of a block (text, image etc) as identified by OCR. - enum BlockType { - // Unknown block type. - UNKNOWN = 0; - - // Regular text block. - TEXT = 1; - - // Table block. - TABLE = 2; - - // Image block. - PICTURE = 3; - - // Horizontal/vertical line box. - RULER = 4; - - // Barcode block. - BARCODE = 5; - } - - // Additional information detected for the block. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // List of paragraphs in this block (if this blocks is of type text). - repeated Paragraph paragraphs = 3; - - // Detected block type (text, image etc) for this block. - BlockType block_type = 4; - - // Confidence of the OCR results on the block. Range [0, 1]. - float confidence = 5; -} - -// Structural unit of text representing a number of words in certain order. -message Paragraph { - // Additional information detected for the paragraph. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // List of words in this paragraph. - repeated Word words = 3; - - // Confidence of the OCR results for the paragraph. Range [0, 1]. - float confidence = 4; -} - -// A word representation. -message Word { - // Additional information detected for the word. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // List of symbols in the word. - // The order of the symbols follows the natural reading order. - repeated Symbol symbols = 3; - - // Confidence of the OCR results for the word. Range [0, 1]. - float confidence = 4; -} - -// A single symbol representation. -message Symbol { - // Additional information detected for the symbol. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // The actual UTF-8 representation of the symbol. - string text = 3; - - // Confidence of the OCR results for the symbol. Range [0, 1]. - float confidence = 4; -} diff --git a/google/cloud/vision_v1p1beta1/proto/web_detection.proto b/google/cloud/vision_v1p1beta1/proto/web_detection.proto deleted file mode 100644 index 28249cbd..00000000 --- a/google/cloud/vision_v1p1beta1/proto/web_detection.proto +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2017 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.v1p1beta1; - -import "google/api/annotations.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p1beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "WebDetectionProto"; -option java_package = "com.google.cloud.vision.v1p1beta1"; - -// Relevant information for the image from the Internet. -message WebDetection { - // Entity deduced from similar images on the Internet. - message WebEntity { - // Opaque entity ID. - string entity_id = 1; - - // Overall relevancy score for the entity. - // Not normalized and not comparable across different image queries. - float score = 2; - - // Canonical description of the entity, in English. - string description = 3; - } - - // Metadata for online images. - message WebImage { - // The result image URL. - string url = 1; - - // (Deprecated) Overall relevancy score for the image. - float score = 2; - } - - // Metadata for web pages. - message WebPage { - // The result web page URL. - string url = 1; - - // (Deprecated) Overall relevancy score for the web page. - float score = 2; - - // Title for the web page, may contain HTML markups. - string page_title = 3; - - // Fully matching images on the page. - // Can include resized copies of the query image. - repeated WebImage full_matching_images = 4; - - // 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. - repeated WebImage partial_matching_images = 5; - } - - // Label to provide extra metadata for the web detection. - message WebLabel { - // Label for extra metadata. - string label = 1; - - // 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. - string language_code = 2; - } - - // Deduced entities from similar images on the Internet. - repeated WebEntity web_entities = 1; - - // Fully matching images from the Internet. - // Can include resized copies of the query image. - repeated WebImage full_matching_images = 2; - - // 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. - repeated WebImage partial_matching_images = 3; - - // Web pages containing the matching images from the Internet. - repeated WebPage pages_with_matching_images = 4; - - // The visually similar image results. - repeated WebImage visually_similar_images = 6; - - // Best guess text labels for the request image. - repeated WebLabel best_guess_labels = 8; -} diff --git a/google/cloud/vision_v1p1beta1/services/__init__.py b/google/cloud/vision_v1p1beta1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/vision_v1p1beta1/services/__init__.py +++ b/google/cloud/vision_v1p1beta1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/__init__.py b/google/cloud/vision_v1p1beta1/services/image_annotator/__init__.py index 2b601881..422732ba 100644 --- a/google/cloud/vision_v1p1beta1/services/image_annotator/__init__.py +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ImageAnnotatorClient from .async_client import 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 index ed07ee43..57a81899 100644 --- a/google/cloud/vision_v1p1beta1/services/image_annotator/async_client.py +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,14 +20,13 @@ 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 exceptions as core_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 import credentials as ga_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 @@ -53,24 +50,20 @@ class ImageAnnotatorAsyncClient: parse_common_billing_account_path = staticmethod( ImageAnnotatorClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ImageAnnotatorClient.common_folder_path) parse_common_folder_path = staticmethod( ImageAnnotatorClient.parse_common_folder_path ) - common_organization_path = staticmethod( ImageAnnotatorClient.common_organization_path ) parse_common_organization_path = staticmethod( ImageAnnotatorClient.parse_common_organization_path ) - common_project_path = staticmethod(ImageAnnotatorClient.common_project_path) parse_common_project_path = staticmethod( ImageAnnotatorClient.parse_common_project_path ) - common_location_path = staticmethod(ImageAnnotatorClient.common_location_path) parse_common_location_path = staticmethod( ImageAnnotatorClient.parse_common_location_path @@ -78,7 +71,8 @@ class ImageAnnotatorAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -93,7 +87,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -110,7 +104,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ImageAnnotatorTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ImageAnnotatorTransport: The transport used by the client instance. @@ -124,12 +118,12 @@ def transport(self) -> ImageAnnotatorTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_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. + """Instantiates the image annotator client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -161,7 +155,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ImageAnnotatorClient( credentials=credentials, transport=transport, @@ -192,7 +185,6 @@ async def batch_annotate_images( 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. @@ -219,7 +211,6 @@ async def batch_annotate_images( # If we have keyword arguments corresponding to fields on the # request, apply these. - if requests: request.requests.extend(requests) @@ -232,7 +223,8 @@ async def batch_annotate_images( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/client.py b/google/cloud/vision_v1p1beta1/services/image_annotator/client.py index 23d0dddd..585d691a 100644 --- a/google/cloud/vision_v1p1beta1/services/image_annotator/client.py +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,17 +21,16 @@ 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 exceptions as core_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 import credentials as ga_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 @@ -54,7 +51,7 @@ class ImageAnnotatorClientMeta(type): _transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ImageAnnotatorTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -81,7 +78,8 @@ class ImageAnnotatorClient(metaclass=ImageAnnotatorClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -115,7 +113,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -132,7 +131,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -151,16 +150,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ImageAnnotatorTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ImageAnnotatorTransport: The transport used by the client instance. + ImageAnnotatorTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -173,7 +173,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -184,7 +184,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -195,7 +195,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -206,7 +206,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -220,12 +220,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_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. + """Instantiates the image annotator client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -280,9 +280,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -294,12 +295,14 @@ def __init__( 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 - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -314,8 +317,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -353,7 +356,6 @@ def batch_annotate_images( 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. @@ -385,10 +387,8 @@ def batch_annotate_images( 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 diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/__init__.py b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/__init__.py index e2a0c3ea..419b4293 100644 --- a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/__init__.py +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py index 51ad8825..3b397199 100644 --- a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_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 import credentials as ga_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, @@ -35,6 +34,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ImageAnnotatorTransport(abc.ABC): """Abstract transport class for ImageAnnotator.""" @@ -44,21 +54,24 @@ class ImageAnnotatorTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-vision", ) + DEFAULT_HOST: str = "vision.googleapis.com" + 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, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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. + 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 @@ -67,7 +80,7 @@ def __init__( 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. + scopes (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): @@ -81,29 +94,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -114,7 +174,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -126,11 +187,11 @@ def _prep_wrapped_messages(self, client_info): @property def batch_annotate_images( self, - ) -> typing.Callable[ + ) -> Callable[ [image_annotator.BatchAnnotateImagesRequest], - typing.Union[ + Union[ image_annotator.BatchAnnotateImagesResponse, - typing.Awaitable[image_annotator.BatchAnnotateImagesResponse], + Awaitable[image_annotator.BatchAnnotateImagesResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py index ba4d21c0..b3a25a47 100644 --- a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,18 @@ # 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 typing import Callable, Dict, Optional, Sequence, Tuple, Union 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 +import google.auth # type: ignore +from google.auth import credentials as ga_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 @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -177,7 +175,7 @@ def __init__( def create_channel( cls, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -208,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) 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 index 5023707c..96f1472a 100644 --- a/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc_asyncio.py +++ b/google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union 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 import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version 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 @@ -56,7 +53,7 @@ class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): def create_channel( cls, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -169,7 +169,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/vision_v1p1beta1/types/__init__.py b/google/cloud/vision_v1p1beta1/types/__init__.py index 196e5262..1333bab5 100644 --- a/google/cloud/vision_v1p1beta1/types/__init__.py +++ b/google/cloud/vision_v1p1beta1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .geometry import ( BoundingPoly, Position, diff --git a/google/cloud/vision_v1p1beta1/types/geometry.py b/google/cloud/vision_v1p1beta1/types/geometry.py index f581bee0..bc33ea35 100644 --- a/google/cloud/vision_v1p1beta1/types/geometry.py +++ b/google/cloud/vision_v1p1beta1/types/geometry.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -36,14 +34,12 @@ class Vertex(proto.Message): Y coordinate. """ - x = proto.Field(proto.INT32, number=1) - - y = proto.Field(proto.INT32, number=2) + 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[google.cloud.vision_v1p1beta1.types.Vertex]): The bounding polygon vertices. @@ -67,11 +63,9 @@ class Position(proto.Message): 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) + 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 index 93f03cb8..b8196484 100644 --- a/google/cloud/vision_v1p1beta1/types/image_annotator.py +++ b/google/cloud/vision_v1p1beta1/types/image_annotator.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,16 +13,14 @@ # 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 +from google.rpc import status_pb2 # type: ignore +from google.type import color_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore __protobuf__ = proto.module( @@ -101,15 +98,12 @@ class Type(proto.Enum): 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) + 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 @@ -132,14 +126,12 @@ class ImageSource(proto.Message): ``image_uri`` takes precedence. """ - gcs_image_uri = proto.Field(proto.STRING, number=1) - - image_uri = proto.Field(proto.STRING, number=2) + 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 @@ -152,8 +144,7 @@ class Image(proto.Message): request. """ - content = proto.Field(proto.BYTES, number=1) - + content = proto.Field(proto.BYTES, number=1,) source = proto.Field(proto.MESSAGE, number=2, message="ImageSource",) @@ -216,7 +207,6 @@ class FaceAnnotation(proto.Message): class Landmark(proto.Message): r"""A face-specific landmark (for example, a face feature). - Attributes: type_ (google.cloud.vision_v1p1beta1.types.FaceAnnotation.Landmark.Type): Face landmark type. @@ -267,56 +257,39 @@ class Type(proto.Enum): 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) - + 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 (google.type.latlng_pb2.LatLng): lat/long location coordinates. """ - lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng.LatLng,) + lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng_pb2.LatLng,) class Property(proto.Message): r"""A ``Property`` consists of a user-supplied name/value pair. - Attributes: name (str): Name of the property. @@ -326,16 +299,13 @@ class Property(proto.Message): 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) + 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 @@ -377,22 +347,14 @@ class EntityAnnotation(proto.Message): 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) - + 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",) @@ -426,19 +388,14 @@ class SafeSearchAnnotation(proto.Message): """ 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 (google.type.latlng_pb2.LatLng): Min lat/long pair. @@ -446,9 +403,8 @@ class LatLongRect(proto.Message): 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,) + min_lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng_pb2.LatLng,) + max_lat_lng = proto.Field(proto.MESSAGE, number=2, message=latlng_pb2.LatLng,) class ColorInfo(proto.Message): @@ -465,16 +421,13 @@ class ColorInfo(proto.Message): 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) + color = proto.Field(proto.MESSAGE, number=1, message=color_pb2.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[google.cloud.vision_v1p1beta1.types.ColorInfo]): RGB color values with their score and pixel @@ -486,7 +439,6 @@ class DominantColorsAnnotation(proto.Message): class ImageProperties(proto.Message): r"""Stores image properties, such as dominant colors. - Attributes: dominant_colors (google.cloud.vision_v1p1beta1.types.DominantColorsAnnotation): If present, dominant colors completed @@ -515,10 +467,8 @@ class CropHint(proto.Message): """ 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) + confidence = proto.Field(proto.FLOAT, number=2,) + importance_fraction = proto.Field(proto.FLOAT, number=3,) class CropHintsAnnotation(proto.Message): @@ -535,7 +485,6 @@ class CropHintsAnnotation(proto.Message): class CropHintsParams(proto.Message): r"""Parameters for crop hints annotation request. - Attributes: aspect_ratios (Sequence[float]): Aspect ratios in floats, representing the @@ -548,19 +497,18 @@ class CropHintsParams(proto.Message): provided after the 16th are ignored. """ - aspect_ratios = proto.RepeatedField(proto.FLOAT, number=1) + 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) + include_geo_results = proto.Field(proto.BOOL, number=2,) class TextDetectionParams(proto.Message): @@ -574,12 +522,11 @@ class TextDetectionParams(proto.Message): include confidence score for TEXT_DETECTION as well. """ - enable_text_detection_confidence_score = proto.Field(proto.BOOL, number=9) + enable_text_detection_confidence_score = proto.Field(proto.BOOL, number=9,) class ImageContext(proto.Message): r"""Image context and/or feature-specific parameters. - Attributes: lat_long_rect (google.cloud.vision_v1p1beta1.types.LatLongRect): lat/long rectangle that specifies the @@ -605,15 +552,11 @@ class ImageContext(proto.Message): """ lat_long_rect = proto.Field(proto.MESSAGE, number=1, message="LatLongRect",) - - language_hints = proto.RepeatedField(proto.STRING, number=2) - + 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", ) - text_detection_params = proto.Field( proto.MESSAGE, number=12, message="TextDetectionParams", ) @@ -634,15 +577,12 @@ class AnnotateImageRequest(proto.Message): """ 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[google.cloud.vision_v1p1beta1.types.FaceAnnotation]): If present, face detection has completed @@ -685,44 +625,34 @@ class AnnotateImageResponse(proto.Message): 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,) + error = proto.Field(proto.MESSAGE, number=9, message=status_pb2.Status,) class BatchAnnotateImagesRequest(proto.Message): @@ -742,7 +672,6 @@ class BatchAnnotateImagesRequest(proto.Message): class BatchAnnotateImagesResponse(proto.Message): r"""Response to a batch image annotation request. - Attributes: responses (Sequence[google.cloud.vision_v1p1beta1.types.AnnotateImageResponse]): Individual responses to image annotation diff --git a/google/cloud/vision_v1p1beta1/types/text_annotation.py b/google/cloud/vision_v1p1beta1/types/text_annotation.py index 23b249fe..bc458aca 100644 --- a/google/cloud/vision_v1p1beta1/types/text_annotation.py +++ b/google/cloud/vision_v1p1beta1/types/text_annotation.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # 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 @@ -46,7 +43,6 @@ class TextAnnotation(proto.Message): 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 @@ -56,13 +52,11 @@ class DetectedLanguage(proto.Message): Confidence of detected language. Range [0, 1]. """ - language_code = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) + 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_ (google.cloud.vision_v1p1beta1.types.TextAnnotation.DetectedBreak.BreakType): Detected break type. @@ -82,12 +76,10 @@ class BreakType(proto.Enum): type_ = proto.Field( proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", ) - - is_prefix = proto.Field(proto.BOOL, number=2) + is_prefix = proto.Field(proto.BOOL, number=2,) class TextProperty(proto.Message): r"""Additional information detected on the structural component. - Attributes: detected_languages (Sequence[google.cloud.vision_v1p1beta1.types.TextAnnotation.DetectedLanguage]): A list of detected languages together with @@ -99,19 +91,16 @@ class TextProperty(proto.Message): 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) + text = proto.Field(proto.STRING, number=2,) class Page(proto.Message): r"""Detected page from OCR. - Attributes: property (google.cloud.vision_v1p1beta1.types.TextAnnotation.TextProperty): Additional information detected on the page. @@ -129,19 +118,14 @@ class Page(proto.Message): property = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - - width = proto.Field(proto.INT32, number=2) - - height = proto.Field(proto.INT32, number=3) - + 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) + confidence = proto.Field(proto.FLOAT, number=5,) class Block(proto.Message): r"""Logical element on the page. - Attributes: property (google.cloud.vision_v1p1beta1.types.TextAnnotation.TextProperty): Additional information detected for the @@ -180,14 +164,10 @@ class BlockType(proto.Enum): 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) + confidence = proto.Field(proto.FLOAT, number=5,) class Paragraph(proto.Message): @@ -220,17 +200,13 @@ class Paragraph(proto.Message): 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) + confidence = proto.Field(proto.FLOAT, number=4,) class Word(proto.Message): r"""A word representation. - Attributes: property (google.cloud.vision_v1p1beta1.types.TextAnnotation.TextProperty): Additional information detected for the word. @@ -257,17 +233,13 @@ class Word(proto.Message): 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) + confidence = proto.Field(proto.FLOAT, number=4,) class Symbol(proto.Message): r"""A single symbol representation. - Attributes: property (google.cloud.vision_v1p1beta1.types.TextAnnotation.TextProperty): Additional information detected for the @@ -294,12 +266,9 @@ class Symbol(proto.Message): 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) + 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 index 1e9586d6..664f49bd 100644 --- a/google/cloud/vision_v1p1beta1/types/web_detection.py +++ b/google/cloud/vision_v1p1beta1/types/web_detection.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -25,7 +23,6 @@ class WebDetection(proto.Message): r"""Relevant information for the image from the Internet. - Attributes: web_entities (Sequence[google.cloud.vision_v1p1beta1.types.WebDetection.WebEntity]): Deduced entities from similar images on the @@ -50,7 +47,6 @@ class WebDetection(proto.Message): class WebEntity(proto.Message): r"""Entity deduced from similar images on the Internet. - Attributes: entity_id (str): Opaque entity ID. @@ -63,15 +59,12 @@ class WebEntity(proto.Message): English. """ - entity_id = proto.Field(proto.STRING, number=1) - - score = proto.Field(proto.FLOAT, number=2) - - description = proto.Field(proto.STRING, number=3) + 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. @@ -80,13 +73,11 @@ class WebImage(proto.Message): image. """ - url = proto.Field(proto.STRING, number=1) - - score = proto.Field(proto.FLOAT, number=2) + 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. @@ -107,23 +98,18 @@ class WebPage(proto.Message): crops. """ - url = proto.Field(proto.STRING, number=1) - - score = proto.Field(proto.FLOAT, number=2) - - page_title = proto.Field(proto.STRING, number=3) - + 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. @@ -133,28 +119,22 @@ class WebLabel(proto.Message): http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. """ - label = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + 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,) diff --git a/google/cloud/vision_v1p2beta1/__init__.py b/google/cloud/vision_v1p2beta1/__init__.py index 98b5a243..9d65b538 100644 --- a/google/cloud/vision_v1p2beta1/__init__.py +++ b/google/cloud/vision_v1p2beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -19,6 +18,8 @@ from google.cloud.vision_helpers import VisionHelpers from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient +from .services.image_annotator import ImageAnnotatorAsyncClient + from .types.geometry import BoundingPoly from .types.geometry import NormalizedVertex from .types.geometry import Position @@ -49,7 +50,6 @@ 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 @@ -57,6 +57,7 @@ from .types.image_annotator import SafeSearchAnnotation from .types.image_annotator import TextDetectionParams from .types.image_annotator import WebDetectionParams +from .types.image_annotator import Likelihood from .types.text_annotation import Block from .types.text_annotation import Page from .types.text_annotation import Paragraph @@ -73,6 +74,7 @@ class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): __all__ = ( + "ImageAnnotatorAsyncClient", "AnnotateFileResponse", "AnnotateImageRequest", "AnnotateImageResponse", @@ -96,6 +98,7 @@ class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): "GcsSource", "Image", "ImageAnnotationContext", + "ImageAnnotatorClient", "ImageContext", "ImageProperties", "ImageSource", @@ -118,5 +121,4 @@ class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): "WebDetection", "WebDetectionParams", "Word", - "ImageAnnotatorClient", ) diff --git a/google/cloud/vision_v1p2beta1/proto/geometry.proto b/google/cloud/vision_v1p2beta1/proto/geometry.proto deleted file mode 100644 index e9fec20b..00000000 --- a/google/cloud/vision_v1p2beta1/proto/geometry.proto +++ /dev/null @@ -1,67 +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.v1p2beta1; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p2beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "GeometryProto"; -option java_package = "com.google.cloud.vision.v1p2beta1"; - -// A vertex represents a 2D point in the image. -// NOTE: the vertex coordinates are in the same scale as the original image. -message Vertex { - // X coordinate. - int32 x = 1; - - // Y coordinate. - int32 y = 2; -} - -// 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. -message NormalizedVertex { - // X coordinate. - float x = 1; - - // Y coordinate. - float y = 2; -} - -// A bounding polygon for the detected image annotation. -message BoundingPoly { - // The bounding polygon vertices. - repeated Vertex vertices = 1; - - // The bounding polygon normalized vertices. - repeated NormalizedVertex normalized_vertices = 2; -} - -// 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. -message Position { - // X coordinate. - float x = 1; - - // Y coordinate. - float y = 2; - - // Z coordinate (or depth). - float z = 3; -} diff --git a/google/cloud/vision_v1p2beta1/proto/image_annotator.proto b/google/cloud/vision_v1p2beta1/proto/image_annotator.proto deleted file mode 100644 index eaf5abf0..00000000 --- a/google/cloud/vision_v1p2beta1/proto/image_annotator.proto +++ /dev/null @@ -1,790 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.vision.v1p2beta1; - -import "google/api/annotations.proto"; -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; -import "google/cloud/vision/v1p2beta1/geometry.proto"; -import "google/cloud/vision/v1p2beta1/text_annotation.proto"; -import "google/cloud/vision/v1p2beta1/web_detection.proto"; -import "google/longrunning/operations.proto"; -import "google/protobuf/timestamp.proto"; -import "google/rpc/status.proto"; -import "google/type/color.proto"; -import "google/type/latlng.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p2beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "ImageAnnotatorProto"; -option java_package = "com.google.cloud.vision.v1p2beta1"; - -// 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 ImageAnnotator { - option (google.api.default_host) = "vision.googleapis.com"; - option (google.api.oauth_scopes) = - "https://www.googleapis.com/auth/cloud-platform," - "https://www.googleapis.com/auth/cloud-vision"; - - // Run image detection and annotation for a batch of images. - rpc BatchAnnotateImages(BatchAnnotateImagesRequest) returns (BatchAnnotateImagesResponse) { - option (google.api.http) = { - post: "/v1p2beta1/images:annotate" - body: "*" - }; - option (google.api.method_signature) = "requests"; - } - - // 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). - rpc AsyncBatchAnnotateFiles(AsyncBatchAnnotateFilesRequest) returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v1p2beta1/files:asyncBatchAnnotate" - body: "*" - }; - option (google.api.method_signature) = "requests"; - option (google.longrunning.operation_info) = { - response_type: "AsyncBatchAnnotateFilesResponse" - metadata_type: "OperationMetadata" - }; - } -} - -// 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. -message Feature { - // Type of Google Cloud Vision API feature to be extracted. - enum Type { - // Unspecified feature type. - TYPE_UNSPECIFIED = 0; - - // Run face detection. - FACE_DETECTION = 1; - - // Run landmark detection. - LANDMARK_DETECTION = 2; - - // Run logo detection. - LOGO_DETECTION = 3; - - // Run label detection. - LABEL_DETECTION = 4; - - // 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. - TEXT_DETECTION = 5; - - // Run dense text document OCR. Takes precedence when both - // `DOCUMENT_TEXT_DETECTION` and `TEXT_DETECTION` are present. - DOCUMENT_TEXT_DETECTION = 11; - - // Run Safe Search to detect potentially unsafe - // or undesirable content. - SAFE_SEARCH_DETECTION = 6; - - // Compute a set of image properties, such as the - // image's dominant colors. - IMAGE_PROPERTIES = 7; - - // Run crop hints. - CROP_HINTS = 9; - - // Run web detection. - WEB_DETECTION = 10; - } - - // The feature type. - Type type = 1; - - // Maximum number of results of this type. Does not apply to - // `TEXT_DETECTION`, `DOCUMENT_TEXT_DETECTION`, or `CROP_HINTS`. - int32 max_results = 2; - - // Model to use for the feature. - // Supported values: "builtin/stable" (the default if unset) and - // "builtin/latest". - string model = 3; -} - -// External image source (Google Cloud Storage or web URL image location). -message ImageSource { - // **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](https://cloud.google.com/storage/docs/reference-uris) for more info. - string gcs_image_uri = 1; - - // 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](https://cloud.google.com/storage/docs/reference-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. - string image_uri = 2; -} - -// Client image to perform Google Cloud Vision API tasks over. -message Image { - // 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. - bytes content = 1; - - // 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. - ImageSource source = 2; -} - -// A face annotation object contains the results of face detection. -message FaceAnnotation { - // A face-specific landmark (for example, a face feature). - message Landmark { - // 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. - enum Type { - // Unknown face landmark detected. Should not be filled. - UNKNOWN_LANDMARK = 0; - - // Left eye. - LEFT_EYE = 1; - - // Right eye. - RIGHT_EYE = 2; - - // Left of left eyebrow. - LEFT_OF_LEFT_EYEBROW = 3; - - // Right of left eyebrow. - RIGHT_OF_LEFT_EYEBROW = 4; - - // Left of right eyebrow. - LEFT_OF_RIGHT_EYEBROW = 5; - - // Right of right eyebrow. - RIGHT_OF_RIGHT_EYEBROW = 6; - - // Midpoint between eyes. - MIDPOINT_BETWEEN_EYES = 7; - - // Nose tip. - NOSE_TIP = 8; - - // Upper lip. - UPPER_LIP = 9; - - // Lower lip. - LOWER_LIP = 10; - - // Mouth left. - MOUTH_LEFT = 11; - - // Mouth right. - MOUTH_RIGHT = 12; - - // Mouth center. - MOUTH_CENTER = 13; - - // Nose, bottom right. - NOSE_BOTTOM_RIGHT = 14; - - // Nose, bottom left. - NOSE_BOTTOM_LEFT = 15; - - // Nose, bottom center. - NOSE_BOTTOM_CENTER = 16; - - // Left eye, top boundary. - LEFT_EYE_TOP_BOUNDARY = 17; - - // Left eye, right corner. - LEFT_EYE_RIGHT_CORNER = 18; - - // Left eye, bottom boundary. - LEFT_EYE_BOTTOM_BOUNDARY = 19; - - // Left eye, left corner. - LEFT_EYE_LEFT_CORNER = 20; - - // Right eye, top boundary. - RIGHT_EYE_TOP_BOUNDARY = 21; - - // Right eye, right corner. - RIGHT_EYE_RIGHT_CORNER = 22; - - // Right eye, bottom boundary. - RIGHT_EYE_BOTTOM_BOUNDARY = 23; - - // Right eye, left corner. - RIGHT_EYE_LEFT_CORNER = 24; - - // Left eyebrow, upper midpoint. - LEFT_EYEBROW_UPPER_MIDPOINT = 25; - - // Right eyebrow, upper midpoint. - RIGHT_EYEBROW_UPPER_MIDPOINT = 26; - - // Left ear tragion. - LEFT_EAR_TRAGION = 27; - - // Right ear tragion. - RIGHT_EAR_TRAGION = 28; - - // Left eye pupil. - LEFT_EYE_PUPIL = 29; - - // Right eye pupil. - RIGHT_EYE_PUPIL = 30; - - // Forehead glabella. - FOREHEAD_GLABELLA = 31; - - // Chin gnathion. - CHIN_GNATHION = 32; - - // Chin left gonion. - CHIN_LEFT_GONION = 33; - - // Chin right gonion. - CHIN_RIGHT_GONION = 34; - } - - // Face landmark type. - Type type = 3; - - // Face landmark position. - Position position = 4; - } - - // 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. - BoundingPoly bounding_poly = 1; - - // 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. - BoundingPoly fd_bounding_poly = 2; - - // Detected face landmarks. - repeated Landmark landmarks = 3; - - // 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]. - float roll_angle = 4; - - // 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]. - float pan_angle = 5; - - // Pitch angle, which indicates the upwards/downwards angle that the face is - // pointing relative to the image's horizontal plane. Range [-180,180]. - float tilt_angle = 6; - - // Detection confidence. Range [0, 1]. - float detection_confidence = 7; - - // Face landmarking confidence. Range [0, 1]. - float landmarking_confidence = 8; - - // Joy likelihood. - Likelihood joy_likelihood = 9; - - // Sorrow likelihood. - Likelihood sorrow_likelihood = 10; - - // Anger likelihood. - Likelihood anger_likelihood = 11; - - // Surprise likelihood. - Likelihood surprise_likelihood = 12; - - // Under-exposed likelihood. - Likelihood under_exposed_likelihood = 13; - - // Blurred likelihood. - Likelihood blurred_likelihood = 14; - - // Headwear likelihood. - Likelihood headwear_likelihood = 15; -} - -// Detected entity location information. -message LocationInfo { - // lat/long location coordinates. - google.type.LatLng lat_lng = 1; -} - -// A `Property` consists of a user-supplied name/value pair. -message Property { - // Name of the property. - string name = 1; - - // Value of the property. - string value = 2; - - // Value of numeric properties. - uint64 uint64_value = 3; -} - -// Set of detected entity features. -message EntityAnnotation { - // Opaque entity ID. Some IDs may be available in - // [Google Knowledge Graph Search - // API](https://developers.google.com/knowledge-graph/). - string mid = 1; - - // The language code for the locale in which the entity textual - // `description` is expressed. - string locale = 2; - - // Entity textual description, expressed in its `locale` language. - string description = 3; - - // Overall score of the result. Range [0, 1]. - float score = 4; - - // **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]. - float confidence = 5; - - // 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]. - float topicality = 6; - - // Image region to which this entity belongs. Not produced - // for `LABEL_DETECTION` features. - BoundingPoly bounding_poly = 7; - - // 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. - repeated LocationInfo locations = 8; - - // Some entities may have optional user-supplied `Property` (name/value) - // fields, such a score or string that qualifies the entity. - repeated Property properties = 9; -} - -// Set of features pertaining to the image, computed by computer vision -// methods over safe-search verticals (for example, adult, spoof, medical, -// violence). -message SafeSearchAnnotation { - // Represents the adult content likelihood for the image. Adult content may - // contain elements such as nudity, pornographic images or cartoons, or - // sexual activities. - Likelihood adult = 1; - - // Spoof likelihood. The likelihood that an modification - // was made to the image's canonical version to make it appear - // funny or offensive. - Likelihood spoof = 2; - - // Likelihood that this is a medical image. - Likelihood medical = 3; - - // Likelihood that this image contains violent content. - Likelihood violence = 4; - - // 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. - Likelihood racy = 9; -} - -// Rectangle determined by min and max `LatLng` pairs. -message LatLongRect { - // Min lat/long pair. - google.type.LatLng min_lat_lng = 1; - - // Max lat/long pair. - google.type.LatLng max_lat_lng = 2; -} - -// Color information consists of RGB channels, score, and the fraction of -// the image that the color occupies in the image. -message ColorInfo { - // RGB components of the color. - google.type.Color color = 1; - - // Image-specific score for this color. Value in range [0, 1]. - float score = 2; - - // The fraction of pixels the color occupies in the image. - // Value in range [0, 1]. - float pixel_fraction = 3; -} - -// Set of dominant colors and their corresponding scores. -message DominantColorsAnnotation { - // RGB color values with their score and pixel fraction. - repeated ColorInfo colors = 1; -} - -// Stores image properties, such as dominant colors. -message ImageProperties { - // If present, dominant colors completed successfully. - DominantColorsAnnotation dominant_colors = 1; -} - -// Single crop hint that is used to generate a new crop when serving an image. -message CropHint { - // The bounding polygon for the crop region. The coordinates of the bounding - // box are in the original image's scale, as returned in `ImageParams`. - BoundingPoly bounding_poly = 1; - - // Confidence of this being a salient region. Range [0, 1]. - float confidence = 2; - - // Fraction of importance of this salient region with respect to the original - // image. - float importance_fraction = 3; -} - -// Set of crop hints that are used to generate new crops when serving images. -message CropHintsAnnotation { - // Crop hint results. - repeated CropHint crop_hints = 1; -} - -// Parameters for crop hints annotation request. -message CropHintsParams { - // 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. - repeated float aspect_ratios = 1; -} - -// Parameters for web detection request. -message WebDetectionParams { - // Whether to include results derived from the geo information in the image. - bool include_geo_results = 2; -} - -// Parameters for text detections. This is used to control TEXT_DETECTION and -// DOCUMENT_TEXT_DETECTION features. -message TextDetectionParams { - - // By default, Cloud Vision API only includes confidence score for - // DOCUMENT_TEXT_DETECTION result. Set the flag to true to include confidence - // score for TEXT_DETECTION as well. - bool enable_text_detection_confidence_score = 9; -} - -// Image context and/or feature-specific parameters. -message ImageContext { - // Not used. - LatLongRect lat_long_rect = 1; - - // 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](https://cloud.google.com/vision/docs/languages). - repeated string language_hints = 2; - - // Parameters for crop hints annotation request. - CropHintsParams crop_hints_params = 4; - - // Parameters for web detection. - WebDetectionParams web_detection_params = 6; - - // Parameters for text detection and document text detection. - TextDetectionParams text_detection_params = 12; -} - -// Request for performing Google Cloud Vision API tasks over a user-provided -// image, with user-requested features. -message AnnotateImageRequest { - // The image to be processed. - Image image = 1; - - // Requested features. - repeated Feature features = 2; - - // Additional context that may accompany the image. - ImageContext image_context = 3; -} - -// If an image was produced from a file (e.g. a PDF), this message gives -// information about the source of that image. -message ImageAnnotationContext { - // The URI of the file used to produce the image. - string uri = 1; - - // If the file was a PDF or TIFF, this field gives the page number within - // the file used to produce the image. - int32 page_number = 2; -} - -// Response to an image annotation request. -message AnnotateImageResponse { - // If present, face detection has completed successfully. - repeated FaceAnnotation face_annotations = 1; - - // If present, landmark detection has completed successfully. - repeated EntityAnnotation landmark_annotations = 2; - - // If present, logo detection has completed successfully. - repeated EntityAnnotation logo_annotations = 3; - - // If present, label detection has completed successfully. - repeated EntityAnnotation label_annotations = 4; - - // If present, text (OCR) detection has completed successfully. - repeated EntityAnnotation text_annotations = 5; - - // If present, text (OCR) detection or document (OCR) text detection has - // completed successfully. - // This annotation provides the structural hierarchy for the OCR detected - // text. - TextAnnotation full_text_annotation = 12; - - // If present, safe-search annotation has completed successfully. - SafeSearchAnnotation safe_search_annotation = 6; - - // If present, image properties were extracted successfully. - ImageProperties image_properties_annotation = 8; - - // If present, crop hints have completed successfully. - CropHintsAnnotation crop_hints_annotation = 11; - - // If present, web detection has completed successfully. - WebDetection web_detection = 13; - - // 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. - google.rpc.Status error = 9; - - // If present, contextual information is needed to understand where this image - // comes from. - ImageAnnotationContext context = 21; -} - -// Response to a single file annotation request. A file may contain one or more -// images, which individually have their own responses. -message AnnotateFileResponse { - // Information about the file for which this response is generated. - InputConfig input_config = 1; - - // Individual responses to images found within the file. - repeated AnnotateImageResponse responses = 2; -} - -// Multiple image annotation requests are batched into a single service call. -message BatchAnnotateImagesRequest { - // Required. Individual image annotation requests for this batch. - repeated AnnotateImageRequest requests = 1 [(google.api.field_behavior) = REQUIRED]; -} - -// Response to a batch image annotation request. -message BatchAnnotateImagesResponse { - // Individual responses to image annotation requests within the batch. - repeated AnnotateImageResponse responses = 1; -} - -// An offline file annotation request. -message AsyncAnnotateFileRequest { - // Required. Information about the input file. - InputConfig input_config = 1; - - // Required. Requested features. - repeated Feature features = 2; - - // Additional context that may accompany the image(s) in the file. - ImageContext image_context = 3; - - // Required. The desired output location and metadata (e.g. format). - OutputConfig output_config = 4; -} - -// The response for a single offline file annotation request. -message AsyncAnnotateFileResponse { - // The output location and metadata from AsyncAnnotateFileRequest. - OutputConfig output_config = 1; -} - -// Multiple async file annotation requests are batched into a single service -// call. -message AsyncBatchAnnotateFilesRequest { - // Required. Individual async file annotation requests for this batch. - repeated AsyncAnnotateFileRequest requests = 1 [(google.api.field_behavior) = REQUIRED]; -} - -// Response to an async batch file annotation request. -message AsyncBatchAnnotateFilesResponse { - // The list of file annotation responses, one for each request in - // AsyncBatchAnnotateFilesRequest. - repeated AsyncAnnotateFileResponse responses = 1; -} - -// The desired input location and metadata. -message InputConfig { - // The Google Cloud Storage location to read the input from. - GcsSource gcs_source = 1; - - // The type of the file. Currently only "application/pdf" and "image/tiff" - // are supported. Wildcards are not supported. - string mime_type = 2; -} - -// The desired output location and metadata. -message OutputConfig { - // The Google Cloud Storage location to write the output(s) to. - GcsDestination gcs_destination = 1; - - // 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. - int32 batch_size = 2; -} - -// The Google Cloud Storage location where the input will be read from. -message GcsSource { - // Google Cloud Storage URI for the input file. This must only be a GCS - // object. Wildcards are not currently supported. - string uri = 1; -} - -// The Google Cloud Storage location where the output will be written to. -message GcsDestination { - // 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. - string uri = 1; -} - -// Contains metadata for the BatchAnnotateImages operation. -message OperationMetadata { - // Batch operation states. - enum State { - // Invalid. - STATE_UNSPECIFIED = 0; - - // Request is received. - CREATED = 1; - - // Request is actively being processed. - RUNNING = 2; - - // The batch processing is done. - DONE = 3; - - // The batch processing was cancelled. - CANCELLED = 4; - } - - // Current state of the batch operation. - State state = 1; - - // The time when the batch request was received. - google.protobuf.Timestamp create_time = 5; - - // The time when the operation result was last updated. - google.protobuf.Timestamp update_time = 6; -} - -// A bucketized representation of likelihood, which is intended to give clients -// highly stable results across model upgrades. -enum Likelihood { - // Unknown likelihood. - UNKNOWN = 0; - - // It is very unlikely that the image belongs to the specified vertical. - VERY_UNLIKELY = 1; - - // It is unlikely that the image belongs to the specified vertical. - UNLIKELY = 2; - - // It is possible that the image belongs to the specified vertical. - POSSIBLE = 3; - - // It is likely that the image belongs to the specified vertical. - LIKELY = 4; - - // It is very likely that the image belongs to the specified vertical. - VERY_LIKELY = 5; -} diff --git a/google/cloud/vision_v1p2beta1/proto/text_annotation.proto b/google/cloud/vision_v1p2beta1/proto/text_annotation.proto deleted file mode 100644 index b35eb47e..00000000 --- a/google/cloud/vision_v1p2beta1/proto/text_annotation.proto +++ /dev/null @@ -1,259 +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.v1p2beta1; - -import "google/api/annotations.proto"; -import "google/cloud/vision/v1p2beta1/geometry.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p2beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "TextAnnotationProto"; -option java_package = "com.google.cloud.vision.v1p2beta1"; - -// 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. -message TextAnnotation { - // Detected language for a structural component. - message DetectedLanguage { - // 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. - string language_code = 1; - - // Confidence of detected language. Range [0, 1]. - float confidence = 2; - } - - // Detected start or end of a structural component. - message DetectedBreak { - // Enum to denote the type of break found. New line, space etc. - enum BreakType { - // Unknown break label type. - UNKNOWN = 0; - - // Regular space. - SPACE = 1; - - // Sure space (very wide). - SURE_SPACE = 2; - - // Line-wrapping break. - EOL_SURE_SPACE = 3; - - // End-line hyphen that is not present in text; does not co-occur with - // `SPACE`, `LEADER_SPACE`, or `LINE_BREAK`. - HYPHEN = 4; - - // Line break that ends a paragraph. - LINE_BREAK = 5; - } - - // Detected break type. - BreakType type = 1; - - // True if break prepends the element. - bool is_prefix = 2; - } - - // Additional information detected on the structural component. - message TextProperty { - // A list of detected languages together with confidence. - repeated DetectedLanguage detected_languages = 1; - - // Detected start or end of a text segment. - DetectedBreak detected_break = 2; - } - - // List of pages detected by OCR. - repeated Page pages = 1; - - // UTF-8 text detected on the pages. - string text = 2; -} - -// Detected page from OCR. -message Page { - // Additional information detected on the page. - TextAnnotation.TextProperty property = 1; - - // Page width. For PDFs the unit is points. For images (including - // TIFFs) the unit is pixels. - int32 width = 2; - - // Page height. For PDFs the unit is points. For images (including - // TIFFs) the unit is pixels. - int32 height = 3; - - // List of blocks of text, images etc on this page. - repeated Block blocks = 4; - - // Confidence of the OCR results on the page. Range [0, 1]. - float confidence = 5; -} - -// Logical element on the page. -message Block { - // Type of a block (text, image etc) as identified by OCR. - enum BlockType { - // Unknown block type. - UNKNOWN = 0; - - // Regular text block. - TEXT = 1; - - // Table block. - TABLE = 2; - - // Image block. - PICTURE = 3; - - // Horizontal/vertical line box. - RULER = 4; - - // Barcode block. - BARCODE = 5; - } - - // Additional information detected for the block. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // List of paragraphs in this block (if this blocks is of type text). - repeated Paragraph paragraphs = 3; - - // Detected block type (text, image etc) for this block. - BlockType block_type = 4; - - // Confidence of the OCR results on the block. Range [0, 1]. - float confidence = 5; -} - -// Structural unit of text representing a number of words in certain order. -message Paragraph { - // Additional information detected for the paragraph. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // List of words in this paragraph. - repeated Word words = 3; - - // Confidence of the OCR results for the paragraph. Range [0, 1]. - float confidence = 4; -} - -// A word representation. -message Word { - // Additional information detected for the word. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // List of symbols in the word. - // The order of the symbols follows the natural reading order. - repeated Symbol symbols = 3; - - // Confidence of the OCR results for the word. Range [0, 1]. - float confidence = 4; -} - -// A single symbol representation. -message Symbol { - // Additional information detected for the symbol. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // The actual UTF-8 representation of the symbol. - string text = 3; - - // Confidence of the OCR results for the symbol. Range [0, 1]. - float confidence = 4; -} diff --git a/google/cloud/vision_v1p2beta1/proto/web_detection.proto b/google/cloud/vision_v1p2beta1/proto/web_detection.proto deleted file mode 100644 index f2b9dfef..00000000 --- a/google/cloud/vision_v1p2beta1/proto/web_detection.proto +++ /dev/null @@ -1,104 +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.v1p2beta1; - -import "google/api/annotations.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p2beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "WebDetectionProto"; -option java_package = "com.google.cloud.vision.v1p2beta1"; - -// Relevant information for the image from the Internet. -message WebDetection { - // Entity deduced from similar images on the Internet. - message WebEntity { - // Opaque entity ID. - string entity_id = 1; - - // Overall relevancy score for the entity. - // Not normalized and not comparable across different image queries. - float score = 2; - - // Canonical description of the entity, in English. - string description = 3; - } - - // Metadata for online images. - message WebImage { - // The result image URL. - string url = 1; - - // (Deprecated) Overall relevancy score for the image. - float score = 2; - } - - // Metadata for web pages. - message WebPage { - // The result web page URL. - string url = 1; - - // (Deprecated) Overall relevancy score for the web page. - float score = 2; - - // Title for the web page, may contain HTML markups. - string page_title = 3; - - // Fully matching images on the page. - // Can include resized copies of the query image. - repeated WebImage full_matching_images = 4; - - // 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. - repeated WebImage partial_matching_images = 5; - } - - // Label to provide extra metadata for the web detection. - message WebLabel { - // Label for extra metadata. - string label = 1; - - // 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. - string language_code = 2; - } - - // Deduced entities from similar images on the Internet. - repeated WebEntity web_entities = 1; - - // Fully matching images from the Internet. - // Can include resized copies of the query image. - repeated WebImage full_matching_images = 2; - - // 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. - repeated WebImage partial_matching_images = 3; - - // Web pages containing the matching images from the Internet. - repeated WebPage pages_with_matching_images = 4; - - // The visually similar image results. - repeated WebImage visually_similar_images = 6; - - // Best guess text labels for the request image. - repeated WebLabel best_guess_labels = 8; -} diff --git a/google/cloud/vision_v1p2beta1/services/__init__.py b/google/cloud/vision_v1p2beta1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/vision_v1p2beta1/services/__init__.py +++ b/google/cloud/vision_v1p2beta1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/__init__.py b/google/cloud/vision_v1p2beta1/services/image_annotator/__init__.py index 2b601881..422732ba 100644 --- a/google/cloud/vision_v1p2beta1/services/image_annotator/__init__.py +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ImageAnnotatorClient from .async_client import 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 index 07e33837..d05d66fd 100644 --- a/google/cloud/vision_v1p2beta1/services/image_annotator/async_client.py +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,16 +20,15 @@ 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 exceptions as core_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 import credentials as ga_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 @@ -55,24 +52,20 @@ class ImageAnnotatorAsyncClient: parse_common_billing_account_path = staticmethod( ImageAnnotatorClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ImageAnnotatorClient.common_folder_path) parse_common_folder_path = staticmethod( ImageAnnotatorClient.parse_common_folder_path ) - common_organization_path = staticmethod( ImageAnnotatorClient.common_organization_path ) parse_common_organization_path = staticmethod( ImageAnnotatorClient.parse_common_organization_path ) - common_project_path = staticmethod(ImageAnnotatorClient.common_project_path) parse_common_project_path = staticmethod( ImageAnnotatorClient.parse_common_project_path ) - common_location_path = staticmethod(ImageAnnotatorClient.common_location_path) parse_common_location_path = staticmethod( ImageAnnotatorClient.parse_common_location_path @@ -80,7 +73,8 @@ class ImageAnnotatorAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -95,7 +89,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -112,7 +106,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ImageAnnotatorTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ImageAnnotatorTransport: The transport used by the client instance. @@ -126,12 +120,12 @@ def transport(self) -> ImageAnnotatorTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_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. + """Instantiates the image annotator client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -163,7 +157,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ImageAnnotatorClient( credentials=credentials, transport=transport, @@ -194,7 +187,6 @@ async def batch_annotate_images( 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. @@ -221,7 +213,6 @@ async def batch_annotate_images( # If we have keyword arguments corresponding to fields on the # request, apply these. - if requests: request.requests.extend(requests) @@ -234,7 +225,8 @@ async def batch_annotate_images( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -276,7 +268,6 @@ async def async_batch_annotate_files( 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. @@ -306,7 +297,6 @@ async def async_batch_annotate_files( # If we have keyword arguments corresponding to fields on the # request, apply these. - if requests: request.requests.extend(requests) @@ -319,7 +309,8 @@ async def async_batch_annotate_files( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/client.py b/google/cloud/vision_v1p2beta1/services/image_annotator/client.py index 25d7616a..d813808c 100644 --- a/google/cloud/vision_v1p2beta1/services/image_annotator/client.py +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ 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 exceptions as core_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 import credentials as ga_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 @@ -35,7 +33,6 @@ 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 @@ -56,7 +53,7 @@ class ImageAnnotatorClientMeta(type): _transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ImageAnnotatorTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -83,7 +80,8 @@ class ImageAnnotatorClient(metaclass=ImageAnnotatorClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -117,7 +115,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -134,7 +133,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -153,16 +152,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ImageAnnotatorTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ImageAnnotatorTransport: The transport used by the client instance. + ImageAnnotatorTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -175,7 +175,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -186,7 +186,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -197,7 +197,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -208,7 +208,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -222,12 +222,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_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. + """Instantiates the image annotator client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -282,9 +282,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -296,12 +297,14 @@ def __init__( 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 - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -316,8 +319,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -355,7 +358,6 @@ def batch_annotate_images( 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. @@ -387,10 +389,8 @@ def batch_annotate_images( 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 @@ -432,7 +432,6 @@ def async_batch_annotate_files( 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. @@ -467,10 +466,8 @@ def async_batch_annotate_files( 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 diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/__init__.py b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/__init__.py index e2a0c3ea..419b4293 100644 --- a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/__init__.py +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py index 6cd152c0..b2eb955e 100644 --- a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_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.auth import credentials as ga_credentials # type: ignore from google.cloud.vision_v1p2beta1.types import image_annotator -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -37,6 +36,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ImageAnnotatorTransport(abc.ABC): """Abstract transport class for ImageAnnotator.""" @@ -46,21 +56,24 @@ class ImageAnnotatorTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-vision", ) + DEFAULT_HOST: str = "vision.googleapis.com" + 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, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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. + 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 @@ -69,7 +82,7 @@ def __init__( 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. + scopes (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): @@ -83,29 +96,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -116,7 +176,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -130,7 +191,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -147,11 +209,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def batch_annotate_images( self, - ) -> typing.Callable[ + ) -> Callable[ [image_annotator.BatchAnnotateImagesRequest], - typing.Union[ + Union[ image_annotator.BatchAnnotateImagesResponse, - typing.Awaitable[image_annotator.BatchAnnotateImagesResponse], + Awaitable[image_annotator.BatchAnnotateImagesResponse], ], ]: raise NotImplementedError() @@ -159,9 +221,9 @@ def batch_annotate_images( @property def async_batch_annotate_files( self, - ) -> typing.Callable[ + ) -> Callable[ [image_annotator.AsyncBatchAnnotateFilesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py index b0b2f324..c5cd75b4 100644 --- a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # 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 typing import Callable, Dict, Optional, Sequence, Tuple, Union 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 +import google.auth # type: ignore +from google.auth import credentials as ga_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 google.longrunning import operations_pb2 # type: ignore from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -180,7 +178,7 @@ def __init__( def create_channel( cls, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -211,13 +209,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -275,7 +275,7 @@ def batch_annotate_images( def async_batch_annotate_files( self, ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], operations.Operation + [image_annotator.AsyncBatchAnnotateFilesRequest], operations_pb2.Operation ]: r"""Return a callable for the async batch annotate files method over gRPC. @@ -301,7 +301,7 @@ def async_batch_annotate_files( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["async_batch_annotate_files"] 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 index 21fa5d3a..ed019dfa 100644 --- a/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc_asyncio.py +++ b/google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union 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 import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version 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 google.longrunning import operations_pb2 # type: ignore from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .grpc import ImageAnnotatorGrpcTransport @@ -58,7 +55,7 @@ class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): def create_channel( cls, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -172,7 +172,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -282,7 +281,7 @@ def async_batch_annotate_files( self, ) -> Callable[ [image_annotator.AsyncBatchAnnotateFilesRequest], - Awaitable[operations.Operation], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the async batch annotate files method over gRPC. @@ -308,7 +307,7 @@ def async_batch_annotate_files( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["async_batch_annotate_files"] diff --git a/google/cloud/vision_v1p2beta1/types/__init__.py b/google/cloud/vision_v1p2beta1/types/__init__.py index 6ad8d27d..e95c0f53 100644 --- a/google/cloud/vision_v1p2beta1/types/__init__.py +++ b/google/cloud/vision_v1p2beta1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .geometry import ( BoundingPoly, NormalizedVertex, diff --git a/google/cloud/vision_v1p2beta1/types/geometry.py b/google/cloud/vision_v1p2beta1/types/geometry.py index 42fb6ec0..c10c04b2 100644 --- a/google/cloud/vision_v1p2beta1/types/geometry.py +++ b/google/cloud/vision_v1p2beta1/types/geometry.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -36,9 +34,8 @@ class Vertex(proto.Message): Y coordinate. """ - x = proto.Field(proto.INT32, number=1) - - y = proto.Field(proto.INT32, number=2) + x = proto.Field(proto.INT32, number=1,) + y = proto.Field(proto.INT32, number=2,) class NormalizedVertex(proto.Message): @@ -53,14 +50,12 @@ class NormalizedVertex(proto.Message): Y coordinate. """ - x = proto.Field(proto.FLOAT, number=1) - - y = proto.Field(proto.FLOAT, number=2) + 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[google.cloud.vision_v1p2beta1.types.Vertex]): The bounding polygon vertices. @@ -69,7 +64,6 @@ class BoundingPoly(proto.Message): """ vertices = proto.RepeatedField(proto.MESSAGE, number=1, message="Vertex",) - normalized_vertices = proto.RepeatedField( proto.MESSAGE, number=2, message="NormalizedVertex", ) @@ -90,11 +84,9 @@ class Position(proto.Message): 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) + 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 index 5480edb6..935b40af 100644 --- a/google/cloud/vision_v1p2beta1/types/image_annotator.py +++ b/google/cloud/vision_v1p2beta1/types/image_annotator.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,17 +13,15 @@ # 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 +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import color_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore __protobuf__ = proto.module( @@ -113,10 +110,8 @@ class Type(proto.Enum): 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) + max_results = proto.Field(proto.INT32, number=2,) + model = proto.Field(proto.STRING, number=3,) class ImageSource(proto.Message): @@ -154,14 +149,12 @@ class ImageSource(proto.Message): ``image_uri`` takes precedence. """ - gcs_image_uri = proto.Field(proto.STRING, number=1) - - image_uri = proto.Field(proto.STRING, number=2) + 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 @@ -174,8 +167,7 @@ class Image(proto.Message): perform the image annotation request. """ - content = proto.Field(proto.BYTES, number=1) - + content = proto.Field(proto.BYTES, number=1,) source = proto.Field(proto.MESSAGE, number=2, message="ImageSource",) @@ -238,7 +230,6 @@ class FaceAnnotation(proto.Message): class Landmark(proto.Message): r"""A face-specific landmark (for example, a face feature). - Attributes: type_ (google.cloud.vision_v1p2beta1.types.FaceAnnotation.Landmark.Type): Face landmark type. @@ -289,56 +280,39 @@ class Type(proto.Enum): 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) - + 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 (google.type.latlng_pb2.LatLng): lat/long location coordinates. """ - lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng.LatLng,) + lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng_pb2.LatLng,) class Property(proto.Message): r"""A ``Property`` consists of a user-supplied name/value pair. - Attributes: name (str): Name of the property. @@ -348,16 +322,13 @@ class Property(proto.Message): 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) + 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 @@ -400,22 +371,14 @@ class EntityAnnotation(proto.Message): 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) - + 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",) @@ -449,19 +412,14 @@ class SafeSearchAnnotation(proto.Message): """ 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 (google.type.latlng_pb2.LatLng): Min lat/long pair. @@ -469,9 +427,8 @@ class LatLongRect(proto.Message): 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,) + min_lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng_pb2.LatLng,) + max_lat_lng = proto.Field(proto.MESSAGE, number=2, message=latlng_pb2.LatLng,) class ColorInfo(proto.Message): @@ -488,16 +445,13 @@ class ColorInfo(proto.Message): 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) + color = proto.Field(proto.MESSAGE, number=1, message=color_pb2.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[google.cloud.vision_v1p2beta1.types.ColorInfo]): RGB color values with their score and pixel @@ -509,7 +463,6 @@ class DominantColorsAnnotation(proto.Message): class ImageProperties(proto.Message): r"""Stores image properties, such as dominant colors. - Attributes: dominant_colors (google.cloud.vision_v1p2beta1.types.DominantColorsAnnotation): If present, dominant colors completed @@ -538,10 +491,8 @@ class CropHint(proto.Message): """ 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) + confidence = proto.Field(proto.FLOAT, number=2,) + importance_fraction = proto.Field(proto.FLOAT, number=3,) class CropHintsAnnotation(proto.Message): @@ -558,7 +509,6 @@ class CropHintsAnnotation(proto.Message): class CropHintsParams(proto.Message): r"""Parameters for crop hints annotation request. - Attributes: aspect_ratios (Sequence[float]): Aspect ratios in floats, representing the @@ -571,19 +521,18 @@ class CropHintsParams(proto.Message): provided after the 16th are ignored. """ - aspect_ratios = proto.RepeatedField(proto.FLOAT, number=1) + 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) + include_geo_results = proto.Field(proto.BOOL, number=2,) class TextDetectionParams(proto.Message): @@ -597,12 +546,11 @@ class TextDetectionParams(proto.Message): include confidence score for TEXT_DETECTION as well. """ - enable_text_detection_confidence_score = proto.Field(proto.BOOL, number=9) + enable_text_detection_confidence_score = proto.Field(proto.BOOL, number=9,) class ImageContext(proto.Message): r"""Image context and/or feature-specific parameters. - Attributes: lat_long_rect (google.cloud.vision_v1p2beta1.types.LatLongRect): Not used. @@ -627,15 +575,11 @@ class ImageContext(proto.Message): """ lat_long_rect = proto.Field(proto.MESSAGE, number=1, message="LatLongRect",) - - language_hints = proto.RepeatedField(proto.STRING, number=2) - + 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", ) - text_detection_params = proto.Field( proto.MESSAGE, number=12, message="TextDetectionParams", ) @@ -656,9 +600,7 @@ class AnnotateImageRequest(proto.Message): """ 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",) @@ -676,14 +618,12 @@ class ImageAnnotationContext(proto.Message): produce the image. """ - uri = proto.Field(proto.STRING, number=1) - - page_number = proto.Field(proto.INT32, number=2) + 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[google.cloud.vision_v1p2beta1.types.FaceAnnotation]): If present, face detection has completed @@ -729,45 +669,34 @@ class AnnotateImageResponse(proto.Message): 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,) - + error = proto.Field(proto.MESSAGE, number=9, message=status_pb2.Status,) context = proto.Field(proto.MESSAGE, number=21, message="ImageAnnotationContext",) @@ -786,7 +715,6 @@ class AnnotateFileResponse(proto.Message): """ input_config = proto.Field(proto.MESSAGE, number=1, message="InputConfig",) - responses = proto.RepeatedField( proto.MESSAGE, number=2, message="AnnotateImageResponse", ) @@ -809,7 +737,6 @@ class BatchAnnotateImagesRequest(proto.Message): class BatchAnnotateImagesResponse(proto.Message): r"""Response to a batch image annotation request. - Attributes: responses (Sequence[google.cloud.vision_v1p2beta1.types.AnnotateImageResponse]): Individual responses to image annotation @@ -823,7 +750,6 @@ class BatchAnnotateImagesResponse(proto.Message): class AsyncAnnotateFileRequest(proto.Message): r"""An offline file annotation request. - Attributes: input_config (google.cloud.vision_v1p2beta1.types.InputConfig): Required. Information about the input file. @@ -838,17 +764,13 @@ class AsyncAnnotateFileRequest(proto.Message): """ 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 (google.cloud.vision_v1p2beta1.types.OutputConfig): The output location and metadata from @@ -875,7 +797,6 @@ class AsyncBatchAnnotateFilesRequest(proto.Message): class AsyncBatchAnnotateFilesResponse(proto.Message): r"""Response to an async batch file annotation request. - Attributes: responses (Sequence[google.cloud.vision_v1p2beta1.types.AsyncAnnotateFileResponse]): The list of file annotation responses, one @@ -890,7 +811,6 @@ class AsyncBatchAnnotateFilesResponse(proto.Message): class InputConfig(proto.Message): r"""The desired input location and metadata. - Attributes: gcs_source (google.cloud.vision_v1p2beta1.types.GcsSource): The Google Cloud Storage location to read the @@ -902,13 +822,11 @@ class InputConfig(proto.Message): """ gcs_source = proto.Field(proto.MESSAGE, number=1, message="GcsSource",) - - mime_type = proto.Field(proto.STRING, number=2) + mime_type = proto.Field(proto.STRING, number=2,) class OutputConfig(proto.Message): r"""The desired output location and metadata. - Attributes: gcs_destination (google.cloud.vision_v1p2beta1.types.GcsDestination): The Google Cloud Storage location to write @@ -928,8 +846,7 @@ class OutputConfig(proto.Message): """ gcs_destination = proto.Field(proto.MESSAGE, number=1, message="GcsDestination",) - - batch_size = proto.Field(proto.INT32, number=2) + batch_size = proto.Field(proto.INT32, number=2,) class GcsSource(proto.Message): @@ -943,7 +860,7 @@ class GcsSource(proto.Message): not currently supported. """ - uri = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) class GcsDestination(proto.Message): @@ -971,12 +888,11 @@ class GcsDestination(proto.Message): overflows into multiple sharded files. """ - uri = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) class OperationMetadata(proto.Message): r"""Contains metadata for the BatchAnnotateImages operation. - Attributes: state (google.cloud.vision_v1p2beta1.types.OperationMetadata.State): Current state of the batch operation. @@ -996,10 +912,8 @@ class State(proto.Enum): 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,) + create_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + update_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.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 index e2366e17..c8e457f3 100644 --- a/google/cloud/vision_v1p2beta1/types/text_annotation.py +++ b/google/cloud/vision_v1p2beta1/types/text_annotation.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # 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 @@ -46,7 +43,6 @@ class TextAnnotation(proto.Message): 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 @@ -56,13 +52,11 @@ class DetectedLanguage(proto.Message): Confidence of detected language. Range [0, 1]. """ - language_code = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) + 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_ (google.cloud.vision_v1p2beta1.types.TextAnnotation.DetectedBreak.BreakType): Detected break type. @@ -82,12 +76,10 @@ class BreakType(proto.Enum): type_ = proto.Field( proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", ) - - is_prefix = proto.Field(proto.BOOL, number=2) + is_prefix = proto.Field(proto.BOOL, number=2,) class TextProperty(proto.Message): r"""Additional information detected on the structural component. - Attributes: detected_languages (Sequence[google.cloud.vision_v1p2beta1.types.TextAnnotation.DetectedLanguage]): A list of detected languages together with @@ -99,19 +91,16 @@ class TextProperty(proto.Message): 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) + text = proto.Field(proto.STRING, number=2,) class Page(proto.Message): r"""Detected page from OCR. - Attributes: property (google.cloud.vision_v1p2beta1.types.TextAnnotation.TextProperty): Additional information detected on the page. @@ -131,19 +120,14 @@ class Page(proto.Message): property = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - - width = proto.Field(proto.INT32, number=2) - - height = proto.Field(proto.INT32, number=3) - + 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) + confidence = proto.Field(proto.FLOAT, number=5,) class Block(proto.Message): r"""Logical element on the page. - Attributes: property (google.cloud.vision_v1p2beta1.types.TextAnnotation.TextProperty): Additional information detected for the @@ -195,14 +179,10 @@ class BlockType(proto.Enum): 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) + confidence = proto.Field(proto.FLOAT, number=5,) class Paragraph(proto.Message): @@ -235,17 +215,13 @@ class Paragraph(proto.Message): 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) + confidence = proto.Field(proto.FLOAT, number=4,) class Word(proto.Message): r"""A word representation. - Attributes: property (google.cloud.vision_v1p2beta1.types.TextAnnotation.TextProperty): Additional information detected for the word. @@ -272,17 +248,13 @@ class Word(proto.Message): 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) + confidence = proto.Field(proto.FLOAT, number=4,) class Symbol(proto.Message): r"""A single symbol representation. - Attributes: property (google.cloud.vision_v1p2beta1.types.TextAnnotation.TextProperty): Additional information detected for the @@ -309,12 +281,9 @@ class Symbol(proto.Message): 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) + 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 index d3a7ffee..45f796f7 100644 --- a/google/cloud/vision_v1p2beta1/types/web_detection.py +++ b/google/cloud/vision_v1p2beta1/types/web_detection.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -25,7 +23,6 @@ class WebDetection(proto.Message): r"""Relevant information for the image from the Internet. - Attributes: web_entities (Sequence[google.cloud.vision_v1p2beta1.types.WebDetection.WebEntity]): Deduced entities from similar images on the @@ -50,7 +47,6 @@ class WebDetection(proto.Message): class WebEntity(proto.Message): r"""Entity deduced from similar images on the Internet. - Attributes: entity_id (str): Opaque entity ID. @@ -63,15 +59,12 @@ class WebEntity(proto.Message): English. """ - entity_id = proto.Field(proto.STRING, number=1) - - score = proto.Field(proto.FLOAT, number=2) - - description = proto.Field(proto.STRING, number=3) + 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. @@ -80,13 +73,11 @@ class WebImage(proto.Message): image. """ - url = proto.Field(proto.STRING, number=1) - - score = proto.Field(proto.FLOAT, number=2) + 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. @@ -107,23 +98,18 @@ class WebPage(proto.Message): crops. """ - url = proto.Field(proto.STRING, number=1) - - score = proto.Field(proto.FLOAT, number=2) - - page_title = proto.Field(proto.STRING, number=3) - + 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. @@ -133,28 +119,22 @@ class WebLabel(proto.Message): http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. """ - label = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + 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,) diff --git a/google/cloud/vision_v1p3beta1/__init__.py b/google/cloud/vision_v1p3beta1/__init__.py index b38431b4..df1779cb 100644 --- a/google/cloud/vision_v1p3beta1/__init__.py +++ b/google/cloud/vision_v1p3beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -19,7 +18,10 @@ from google.cloud.vision_helpers import VisionHelpers from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient +from .services.image_annotator import ImageAnnotatorAsyncClient from .services.product_search import ProductSearchClient +from .services.product_search import ProductSearchAsyncClient + from .types.geometry import BoundingPoly from .types.geometry import NormalizedBoundingPoly from .types.geometry import NormalizedVertex @@ -51,7 +53,6 @@ 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 @@ -60,9 +61,10 @@ from .types.image_annotator import SafeSearchAnnotation from .types.image_annotator import TextDetectionParams from .types.image_annotator import WebDetectionParams -from .types.product_search import ProductSearchCategory +from .types.image_annotator import Likelihood from .types.product_search import ProductSearchParams from .types.product_search import ProductSearchResults +from .types.product_search import ProductSearchCategory from .types.product_search import ProductSearchResultsView from .types.product_search_service import AddProductToProductSetRequest from .types.product_search_service import BatchOperationMetadata @@ -109,6 +111,8 @@ class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): __all__ = ( + "ImageAnnotatorAsyncClient", + "ProductSearchAsyncClient", "AddProductToProductSetRequest", "AnnotateFileResponse", "AnnotateImageRequest", @@ -143,6 +147,7 @@ class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): "GetReferenceImageRequest", "Image", "ImageAnnotationContext", + "ImageAnnotatorClient", "ImageContext", "ImageProperties", "ImageSource", @@ -190,5 +195,4 @@ class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): "WebDetection", "WebDetectionParams", "Word", - "ImageAnnotatorClient", ) diff --git a/google/cloud/vision_v1p3beta1/proto/geometry.proto b/google/cloud/vision_v1p3beta1/proto/geometry.proto deleted file mode 100644 index 28b768ea..00000000 --- a/google/cloud/vision_v1p3beta1/proto/geometry.proto +++ /dev/null @@ -1,75 +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"; - -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 = "GeometryProto"; -option java_package = "com.google.cloud.vision.v1p3beta1"; - -// A vertex represents a 2D point in the image. -// NOTE: the vertex coordinates are in the same scale as the original image. -message Vertex { - // X coordinate. - int32 x = 1; - - // Y coordinate. - int32 y = 2; -} - -// 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. -message NormalizedVertex { - // X coordinate. - float x = 1; - - // Y coordinate. - float y = 2; -} - -// A bounding polygon for the detected image annotation. -message BoundingPoly { - // The bounding polygon vertices. - repeated Vertex vertices = 1; - - // The bounding polygon normalized vertices. - repeated NormalizedVertex normalized_vertices = 2; -} - -// A normalized bounding polygon around a portion of an image. -message NormalizedBoundingPoly { - // Normalized vertices of the bounding polygon. - repeated NormalizedVertex vertices = 1; -} - -// 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. -message Position { - // X coordinate. - float x = 1; - - // Y coordinate. - float y = 2; - - // Z coordinate (or depth). - float z = 3; -} diff --git a/google/cloud/vision_v1p3beta1/proto/image_annotator.proto b/google/cloud/vision_v1p3beta1/proto/image_annotator.proto deleted file mode 100644 index c865ff53..00000000 --- a/google/cloud/vision_v1p3beta1/proto/image_annotator.proto +++ /dev/null @@ -1,829 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.vision.v1p3beta1; - -import "google/api/annotations.proto"; -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; -import "google/cloud/vision/v1p3beta1/geometry.proto"; -import "google/cloud/vision/v1p3beta1/product_search.proto"; -import "google/cloud/vision/v1p3beta1/text_annotation.proto"; -import "google/cloud/vision/v1p3beta1/web_detection.proto"; -import "google/longrunning/operations.proto"; -import "google/protobuf/timestamp.proto"; -import "google/rpc/status.proto"; -import "google/type/color.proto"; -import "google/type/latlng.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 = "ImageAnnotatorProto"; -option java_package = "com.google.cloud.vision.v1p3beta1"; - -// 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 ImageAnnotator { - option (google.api.default_host) = "vision.googleapis.com"; - option (google.api.oauth_scopes) = - "https://www.googleapis.com/auth/cloud-platform," - "https://www.googleapis.com/auth/cloud-vision"; - - // Run image detection and annotation for a batch of images. - rpc BatchAnnotateImages(BatchAnnotateImagesRequest) returns (BatchAnnotateImagesResponse) { - option (google.api.http) = { - post: "/v1p3beta1/images:annotate" - body: "*" - }; - option (google.api.method_signature) = "requests"; - } - - // 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). - rpc AsyncBatchAnnotateFiles(AsyncBatchAnnotateFilesRequest) - returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v1p3beta1/files:asyncBatchAnnotate" - body: "*" - }; - option (google.api.method_signature) = "requests"; - option (google.longrunning.operation_info) = { - response_type: "AsyncBatchAnnotateFilesResponse" - metadata_type: "OperationMetadata" - }; - } -} - -// 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. -message Feature { - // Type of Google Cloud Vision API feature to be extracted. - enum Type { - // Unspecified feature type. - TYPE_UNSPECIFIED = 0; - - // Run face detection. - FACE_DETECTION = 1; - - // Run landmark detection. - LANDMARK_DETECTION = 2; - - // Run logo detection. - LOGO_DETECTION = 3; - - // Run label detection. - LABEL_DETECTION = 4; - - // 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. - TEXT_DETECTION = 5; - - // Run dense text document OCR. Takes precedence when both - // `DOCUMENT_TEXT_DETECTION` and `TEXT_DETECTION` are present. - DOCUMENT_TEXT_DETECTION = 11; - - // Run Safe Search to detect potentially unsafe - // or undesirable content. - SAFE_SEARCH_DETECTION = 6; - - // Compute a set of image properties, such as the - // image's dominant colors. - IMAGE_PROPERTIES = 7; - - // Run crop hints. - CROP_HINTS = 9; - - // Run web detection. - WEB_DETECTION = 10; - - // Run Product Search. - PRODUCT_SEARCH = 12; - - // Run localizer for object detection. - OBJECT_LOCALIZATION = 19; - } - - // The feature type. - Type type = 1; - - // Maximum number of results of this type. Does not apply to - // `TEXT_DETECTION`, `DOCUMENT_TEXT_DETECTION`, or `CROP_HINTS`. - int32 max_results = 2; - - // Model to use for the feature. - // Supported values: "builtin/stable" (the default if unset) and - // "builtin/latest". - string model = 3; -} - -// External image source (Google Cloud Storage or web URL image location). -message ImageSource { - // **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](https://cloud.google.com/storage/docs/reference-uris) for more info. - string gcs_image_uri = 1; - - // 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](https://cloud.google.com/storage/docs/reference-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. - string image_uri = 2; -} - -// Client image to perform Google Cloud Vision API tasks over. -message Image { - // 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. - bytes content = 1; - - // 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. - ImageSource source = 2; -} - -// A face annotation object contains the results of face detection. -message FaceAnnotation { - // A face-specific landmark (for example, a face feature). - message Landmark { - // 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. - enum Type { - // Unknown face landmark detected. Should not be filled. - UNKNOWN_LANDMARK = 0; - - // Left eye. - LEFT_EYE = 1; - - // Right eye. - RIGHT_EYE = 2; - - // Left of left eyebrow. - LEFT_OF_LEFT_EYEBROW = 3; - - // Right of left eyebrow. - RIGHT_OF_LEFT_EYEBROW = 4; - - // Left of right eyebrow. - LEFT_OF_RIGHT_EYEBROW = 5; - - // Right of right eyebrow. - RIGHT_OF_RIGHT_EYEBROW = 6; - - // Midpoint between eyes. - MIDPOINT_BETWEEN_EYES = 7; - - // Nose tip. - NOSE_TIP = 8; - - // Upper lip. - UPPER_LIP = 9; - - // Lower lip. - LOWER_LIP = 10; - - // Mouth left. - MOUTH_LEFT = 11; - - // Mouth right. - MOUTH_RIGHT = 12; - - // Mouth center. - MOUTH_CENTER = 13; - - // Nose, bottom right. - NOSE_BOTTOM_RIGHT = 14; - - // Nose, bottom left. - NOSE_BOTTOM_LEFT = 15; - - // Nose, bottom center. - NOSE_BOTTOM_CENTER = 16; - - // Left eye, top boundary. - LEFT_EYE_TOP_BOUNDARY = 17; - - // Left eye, right corner. - LEFT_EYE_RIGHT_CORNER = 18; - - // Left eye, bottom boundary. - LEFT_EYE_BOTTOM_BOUNDARY = 19; - - // Left eye, left corner. - LEFT_EYE_LEFT_CORNER = 20; - - // Right eye, top boundary. - RIGHT_EYE_TOP_BOUNDARY = 21; - - // Right eye, right corner. - RIGHT_EYE_RIGHT_CORNER = 22; - - // Right eye, bottom boundary. - RIGHT_EYE_BOTTOM_BOUNDARY = 23; - - // Right eye, left corner. - RIGHT_EYE_LEFT_CORNER = 24; - - // Left eyebrow, upper midpoint. - LEFT_EYEBROW_UPPER_MIDPOINT = 25; - - // Right eyebrow, upper midpoint. - RIGHT_EYEBROW_UPPER_MIDPOINT = 26; - - // Left ear tragion. - LEFT_EAR_TRAGION = 27; - - // Right ear tragion. - RIGHT_EAR_TRAGION = 28; - - // Left eye pupil. - LEFT_EYE_PUPIL = 29; - - // Right eye pupil. - RIGHT_EYE_PUPIL = 30; - - // Forehead glabella. - FOREHEAD_GLABELLA = 31; - - // Chin gnathion. - CHIN_GNATHION = 32; - - // Chin left gonion. - CHIN_LEFT_GONION = 33; - - // Chin right gonion. - CHIN_RIGHT_GONION = 34; - } - - // Face landmark type. - Type type = 3; - - // Face landmark position. - Position position = 4; - } - - // 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. - BoundingPoly bounding_poly = 1; - - // 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. - BoundingPoly fd_bounding_poly = 2; - - // Detected face landmarks. - repeated Landmark landmarks = 3; - - // 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]. - float roll_angle = 4; - - // 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]. - float pan_angle = 5; - - // Pitch angle, which indicates the upwards/downwards angle that the face is - // pointing relative to the image's horizontal plane. Range [-180,180]. - float tilt_angle = 6; - - // Detection confidence. Range [0, 1]. - float detection_confidence = 7; - - // Face landmarking confidence. Range [0, 1]. - float landmarking_confidence = 8; - - // Joy likelihood. - Likelihood joy_likelihood = 9; - - // Sorrow likelihood. - Likelihood sorrow_likelihood = 10; - - // Anger likelihood. - Likelihood anger_likelihood = 11; - - // Surprise likelihood. - Likelihood surprise_likelihood = 12; - - // Under-exposed likelihood. - Likelihood under_exposed_likelihood = 13; - - // Blurred likelihood. - Likelihood blurred_likelihood = 14; - - // Headwear likelihood. - Likelihood headwear_likelihood = 15; -} - -// Detected entity location information. -message LocationInfo { - // lat/long location coordinates. - google.type.LatLng lat_lng = 1; -} - -// A `Property` consists of a user-supplied name/value pair. -message Property { - // Name of the property. - string name = 1; - - // Value of the property. - string value = 2; - - // Value of numeric properties. - uint64 uint64_value = 3; -} - -// Set of detected entity features. -message EntityAnnotation { - // Opaque entity ID. Some IDs may be available in - // [Google Knowledge Graph Search - // API](https://developers.google.com/knowledge-graph/). - string mid = 1; - - // The language code for the locale in which the entity textual - // `description` is expressed. - string locale = 2; - - // Entity textual description, expressed in its `locale` language. - string description = 3; - - // Overall score of the result. Range [0, 1]. - float score = 4; - - // **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]. - float confidence = 5; - - // 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]. - float topicality = 6; - - // Image region to which this entity belongs. Not produced - // for `LABEL_DETECTION` features. - BoundingPoly bounding_poly = 7; - - // 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. - repeated LocationInfo locations = 8; - - // Some entities may have optional user-supplied `Property` (name/value) - // fields, such a score or string that qualifies the entity. - repeated Property properties = 9; -} - -// Set of detected objects with bounding boxes. -message LocalizedObjectAnnotation { - // Object ID that should align with EntityAnnotation mid. - string mid = 1; - - // 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. - string language_code = 2; - - // Object name, expressed in its `language_code` language. - string name = 3; - - // Score of the result. Range [0, 1]. - float score = 4; - - // Image region to which this object belongs. This must be populated. - BoundingPoly bounding_poly = 5; -} - -// Set of features pertaining to the image, computed by computer vision -// methods over safe-search verticals (for example, adult, spoof, medical, -// violence). -message SafeSearchAnnotation { - // Represents the adult content likelihood for the image. Adult content may - // contain elements such as nudity, pornographic images or cartoons, or - // sexual activities. - Likelihood adult = 1; - - // Spoof likelihood. The likelihood that an modification - // was made to the image's canonical version to make it appear - // funny or offensive. - Likelihood spoof = 2; - - // Likelihood that this is a medical image. - Likelihood medical = 3; - - // Likelihood that this image contains violent content. - Likelihood violence = 4; - - // 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. - Likelihood racy = 9; -} - -// Rectangle determined by min and max `LatLng` pairs. -message LatLongRect { - // Min lat/long pair. - google.type.LatLng min_lat_lng = 1; - - // Max lat/long pair. - google.type.LatLng max_lat_lng = 2; -} - -// Color information consists of RGB channels, score, and the fraction of -// the image that the color occupies in the image. -message ColorInfo { - // RGB components of the color. - google.type.Color color = 1; - - // Image-specific score for this color. Value in range [0, 1]. - float score = 2; - - // The fraction of pixels the color occupies in the image. - // Value in range [0, 1]. - float pixel_fraction = 3; -} - -// Set of dominant colors and their corresponding scores. -message DominantColorsAnnotation { - // RGB color values with their score and pixel fraction. - repeated ColorInfo colors = 1; -} - -// Stores image properties, such as dominant colors. -message ImageProperties { - // If present, dominant colors completed successfully. - DominantColorsAnnotation dominant_colors = 1; -} - -// Single crop hint that is used to generate a new crop when serving an image. -message CropHint { - // The bounding polygon for the crop region. The coordinates of the bounding - // box are in the original image's scale, as returned in `ImageParams`. - BoundingPoly bounding_poly = 1; - - // Confidence of this being a salient region. Range [0, 1]. - float confidence = 2; - - // Fraction of importance of this salient region with respect to the original - // image. - float importance_fraction = 3; -} - -// Set of crop hints that are used to generate new crops when serving images. -message CropHintsAnnotation { - // Crop hint results. - repeated CropHint crop_hints = 1; -} - -// Parameters for crop hints annotation request. -message CropHintsParams { - // 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. - repeated float aspect_ratios = 1; -} - -// Parameters for web detection request. -message WebDetectionParams { - // Whether to include results derived from the geo information in the image. - bool include_geo_results = 2; -} - -// Parameters for text detections. This is used to control TEXT_DETECTION and -// DOCUMENT_TEXT_DETECTION features. -message TextDetectionParams { - - // By default, Cloud Vision API only includes confidence score for - // DOCUMENT_TEXT_DETECTION result. Set the flag to true to include confidence - // score for TEXT_DETECTION as well. - bool enable_text_detection_confidence_score = 9; -} - -// Image context and/or feature-specific parameters. -message ImageContext { - // Not used. - LatLongRect lat_long_rect = 1; - - // 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](https://cloud.google.com/vision/docs/languages). - repeated string language_hints = 2; - - // Parameters for crop hints annotation request. - CropHintsParams crop_hints_params = 4; - - // Parameters for product search. - google.cloud.vision.v1p3beta1.ProductSearchParams product_search_params = 5; - - // Parameters for web detection. - WebDetectionParams web_detection_params = 6; - - // Parameters for text detection and document text detection. - TextDetectionParams text_detection_params = 12; -} - -// Request for performing Google Cloud Vision API tasks over a user-provided -// image, with user-requested features. -message AnnotateImageRequest { - // The image to be processed. - Image image = 1; - - // Requested features. - repeated Feature features = 2; - - // Additional context that may accompany the image. - ImageContext image_context = 3; -} - -// If an image was produced from a file (e.g. a PDF), this message gives -// information about the source of that image. -message ImageAnnotationContext { - // The URI of the file used to produce the image. - string uri = 1; - - // If the file was a PDF or TIFF, this field gives the page number within - // the file used to produce the image. - int32 page_number = 2; -} - -// Response to an image annotation request. -message AnnotateImageResponse { - // If present, face detection has completed successfully. - repeated FaceAnnotation face_annotations = 1; - - // If present, landmark detection has completed successfully. - repeated EntityAnnotation landmark_annotations = 2; - - // If present, logo detection has completed successfully. - repeated EntityAnnotation logo_annotations = 3; - - // If present, label detection has completed successfully. - repeated EntityAnnotation label_annotations = 4; - - // If present, localized object detection has completed successfully. - // This will be sorted descending by confidence score. - repeated LocalizedObjectAnnotation localized_object_annotations = 22; - - // If present, text (OCR) detection has completed successfully. - repeated EntityAnnotation text_annotations = 5; - - // If present, text (OCR) detection or document (OCR) text detection has - // completed successfully. - // This annotation provides the structural hierarchy for the OCR detected - // text. - TextAnnotation full_text_annotation = 12; - - // If present, safe-search annotation has completed successfully. - SafeSearchAnnotation safe_search_annotation = 6; - - // If present, image properties were extracted successfully. - ImageProperties image_properties_annotation = 8; - - // If present, crop hints have completed successfully. - CropHintsAnnotation crop_hints_annotation = 11; - - // If present, web detection has completed successfully. - WebDetection web_detection = 13; - - // If present, product search has completed successfully. - google.cloud.vision.v1p3beta1.ProductSearchResults product_search_results = - 14; - - // 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. - google.rpc.Status error = 9; - - // If present, contextual information is needed to understand where this image - // comes from. - ImageAnnotationContext context = 21; -} - -// Response to a single file annotation request. A file may contain one or more -// images, which individually have their own responses. -message AnnotateFileResponse { - // Information about the file for which this response is generated. - InputConfig input_config = 1; - - // Individual responses to images found within the file. - repeated AnnotateImageResponse responses = 2; -} - -// Multiple image annotation requests are batched into a single service call. -message BatchAnnotateImagesRequest { - // Individual image annotation requests for this batch. - repeated AnnotateImageRequest requests = 1; -} - -// Response to a batch image annotation request. -message BatchAnnotateImagesResponse { - // Individual responses to image annotation requests within the batch. - repeated AnnotateImageResponse responses = 1; -} - -// An offline file annotation request. -message AsyncAnnotateFileRequest { - // Required. Information about the input file. - InputConfig input_config = 1; - - // Required. Requested features. - repeated Feature features = 2; - - // Additional context that may accompany the image(s) in the file. - ImageContext image_context = 3; - - // Required. The desired output location and metadata (e.g. format). - OutputConfig output_config = 4; -} - -// The response for a single offline file annotation request. -message AsyncAnnotateFileResponse { - // The output location and metadata from AsyncAnnotateFileRequest. - OutputConfig output_config = 1; -} - -// Multiple async file annotation requests are batched into a single service -// call. -message AsyncBatchAnnotateFilesRequest { - // Required. Individual async file annotation requests for this batch. - repeated AsyncAnnotateFileRequest requests = 1 [(google.api.field_behavior) = REQUIRED]; -} - -// Response to an async batch file annotation request. -message AsyncBatchAnnotateFilesResponse { - // The list of file annotation responses, one for each request in - // AsyncBatchAnnotateFilesRequest. - repeated AsyncAnnotateFileResponse responses = 1; -} - -// The desired input location and metadata. -message InputConfig { - // The Google Cloud Storage location to read the input from. - GcsSource gcs_source = 1; - - // The type of the file. Currently only "application/pdf" and "image/tiff" - // are supported. Wildcards are not supported. - string mime_type = 2; -} - -// The desired output location and metadata. -message OutputConfig { - // The Google Cloud Storage location to write the output(s) to. - GcsDestination gcs_destination = 1; - - // 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. - int32 batch_size = 2; -} - -// The Google Cloud Storage location where the input will be read from. -message GcsSource { - // Google Cloud Storage URI for the input file. This must only be a - // Google Cloud Storage object. Wildcards are not currently supported. - string uri = 1; -} - -// The Google Cloud Storage location where the output will be written to. -message GcsDestination { - // 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. - string uri = 1; -} - -// A bucketized representation of likelihood, which is intended to give clients -// highly stable results across model upgrades. -enum Likelihood { - // Unknown likelihood. - UNKNOWN = 0; - - // It is very unlikely that the image belongs to the specified vertical. - VERY_UNLIKELY = 1; - - // It is unlikely that the image belongs to the specified vertical. - UNLIKELY = 2; - - // It is possible that the image belongs to the specified vertical. - POSSIBLE = 3; - - // It is likely that the image belongs to the specified vertical. - LIKELY = 4; - - // It is very likely that the image belongs to the specified vertical. - VERY_LIKELY = 5; -} - -// Contains metadata for the BatchAnnotateImages operation. -message OperationMetadata { - // Batch operation states. - enum State { - // Invalid. - STATE_UNSPECIFIED = 0; - - // Request is received. - CREATED = 1; - - // Request is actively being processed. - RUNNING = 2; - - // The batch processing is done. - DONE = 3; - - // The batch processing was cancelled. - CANCELLED = 4; - } - // Current state of the batch operation. - State state = 1; - - // The time when the batch request was received. - google.protobuf.Timestamp create_time = 5; - - // The time when the operation result was last updated. - google.protobuf.Timestamp update_time = 6; -} diff --git a/google/cloud/vision_v1p3beta1/proto/product_search.proto b/google/cloud/vision_v1p3beta1/proto/product_search.proto deleted file mode 100644 index 6dde477c..00000000 --- a/google/cloud/vision_v1p3beta1/proto/product_search.proto +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.vision.v1p3beta1; - -import "google/api/annotations.proto"; -import "google/api/resource.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 [(google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - }]; - - // 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_v1p3beta1/proto/product_search_service.proto b/google/cloud/vision_v1p3beta1/proto/product_search_service.proto deleted file mode 100644 index daf1d0dd..00000000 --- a/google/cloud/vision_v1p3beta1/proto/product_search_service.proto +++ /dev/null @@ -1,971 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.vision.v1p3beta1; - -import "google/api/annotations.proto"; -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; -import "google/api/resource.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 { - option (google.api.default_host) = "vision.googleapis.com"; - option (google.api.oauth_scopes) = - "https://www.googleapis.com/auth/cloud-platform," - "https://www.googleapis.com/auth/cloud-vision"; - - // 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" - }; - option (google.api.method_signature) = "parent,product_set,product_set_id"; - } - - // 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" - }; - option (google.api.method_signature) = "parent"; - } - - // 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/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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" - }; - option (google.api.method_signature) = "product_set,update_mask"; - } - - // 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/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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" - }; - option (google.api.method_signature) = "parent,product,product_id"; - } - - // 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" - }; - option (google.api.method_signature) = "parent"; - } - - // 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/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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" - }; - option (google.api.method_signature) = "product,update_mask"; - } - - // 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/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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" - }; - option (google.api.method_signature) = "parent,reference_image,reference_image_id"; - } - - // 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/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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" - }; - option (google.api.method_signature) = "parent"; - } - - // 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/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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: "*" - }; - option (google.api.method_signature) = "name,product"; - } - - // 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: "*" - }; - option (google.api.method_signature) = "name,product"; - } - - // 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" - }; - option (google.api.method_signature) = "name"; - } - - // 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: "*" - }; - option (google.api.method_signature) = "parent,input_config"; - option (google.longrunning.operation_info) = { - response_type: "ImportProductSetsResponse" - metadata_type: "BatchOperationMetadata" - }; - } -} - -// A Product contains ReferenceImages. -message Product { - option (google.api.resource) = { - type: "vision.googleapis.com/Product" - pattern: "projects/{project}/locations/{location}/products/{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; - - // 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. - string product_category = 4 [(google.api.field_behavior) = IMMUTABLE]; - - // 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 { - option (google.api.resource) = { - type: "vision.googleapis.com/ProductSet" - pattern: "projects/{project}/locations/{location}/productSets/{product_set}" - }; - - // 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 [(google.api.field_behavior) = OUTPUT_ONLY]; - - // 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 [(google.api.field_behavior) = OUTPUT_ONLY]; -} - -// A `ReferenceImage` represents a product image and its associated metadata, -// such as bounding boxes. -message ReferenceImage { - option (google.api.resource) = { - type: "vision.googleapis.com/ReferenceImage" - pattern: "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}" - }; - - // 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; - - // Required. The Google Cloud Storage URI of the reference image. - // - // The URI must start with `gs://`. - string uri = 2 [(google.api.field_behavior) = REQUIRED]; - - // 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). - repeated BoundingPoly bounding_polys = 3 [(google.api.field_behavior) = OPTIONAL]; -} - -// Request message for the `CreateProduct` method. -message CreateProductRequest { - // Required. The project in which the Product should be created. - // - // Format is - // `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Required. The product to create. - Product product = 2 [(google.api.field_behavior) = REQUIRED]; - - // 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 { - // Required. The project OR ProductSet from which Products should be listed. - // - // Format: - // `projects/PROJECT_ID/locations/LOC_ID` - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // 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 { - // Required. Resource name of the Product to get. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/Product" - } - ]; -} - -// Request message for the `UpdateProduct` method. -message UpdateProductRequest { - // Required. The Product resource which replaces the one on the server. - // product.name is immutable. - Product product = 1 [(google.api.field_behavior) = REQUIRED]; - - // 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 { - // Required. Resource name of product to delete. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/Product" - } - ]; -} - -// Request message for the `CreateProductSet` method. -message CreateProductSetRequest { - // Required. The project in which the ProductSet should be created. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Required. The ProductSet to create. - ProductSet product_set = 2 [(google.api.field_behavior) = REQUIRED]; - - // 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 { - // Required. The project from which ProductSets should be listed. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // 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 { - // Required. Resource name of the ProductSet to get. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - } - ]; -} - -// Request message for the `UpdateProductSet` method. -message UpdateProductSetRequest { - // Required. The ProductSet resource which replaces the one on the server. - ProductSet product_set = 1 [(google.api.field_behavior) = REQUIRED]; - - // 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 { - // Required. Resource name of the ProductSet to delete. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - } - ]; -} - -// Request message for the `CreateReferenceImage` method. -message CreateReferenceImageRequest { - // Required. 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 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/Product" - } - ]; - - // Required. The reference image to create. - // If an image ID is specified, it is ignored. - ReferenceImage reference_image = 2 [(google.api.field_behavior) = REQUIRED]; - - // 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 { - // Required. Resource name of the product containing the reference images. - // - // Format is - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/Product" - } - ]; - - // 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 { - // Required. 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 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ReferenceImage" - } - ]; -} - -// Request message for the `DeleteReferenceImage` method. -message DeleteReferenceImageRequest { - // Required. 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 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ReferenceImage" - } - ]; -} - -// Request message for the `AddProductToProductSet` method. -message AddProductToProductSetRequest { - // Required. The resource name for the ProductSet to modify. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - } - ]; - - // Required. 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 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/Product" - } - ]; -} - -// Request message for the `RemoveProductFromProductSet` method. -message RemoveProductFromProductSetRequest { - // Required. The resource name for the ProductSet to modify. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - } - ]; - - // Required. 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 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/Product" - } - ]; -} - -// Request message for the `ListProductsInProductSet` method. -message ListProductsInProductSetRequest { - // Required. The ProductSet resource for which to retrieve Products. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - } - ]; - - // 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 { - // Required. The project in which the ProductSets should be imported. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Required. The input content for the list of requests. - ImportProductSetsInputConfig input_config = 2 [(google.api.field_behavior) = REQUIRED]; -} - -// 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_v1p3beta1/proto/text_annotation.proto b/google/cloud/vision_v1p3beta1/proto/text_annotation.proto deleted file mode 100644 index 3c256c57..00000000 --- a/google/cloud/vision_v1p3beta1/proto/text_annotation.proto +++ /dev/null @@ -1,259 +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"; - -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 = "TextAnnotationProto"; -option java_package = "com.google.cloud.vision.v1p3beta1"; - -// 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. -message TextAnnotation { - // Detected language for a structural component. - message DetectedLanguage { - // 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. - string language_code = 1; - - // Confidence of detected language. Range [0, 1]. - float confidence = 2; - } - - // Detected start or end of a structural component. - message DetectedBreak { - // Enum to denote the type of break found. New line, space etc. - enum BreakType { - // Unknown break label type. - UNKNOWN = 0; - - // Regular space. - SPACE = 1; - - // Sure space (very wide). - SURE_SPACE = 2; - - // Line-wrapping break. - EOL_SURE_SPACE = 3; - - // End-line hyphen that is not present in text; does not co-occur with - // `SPACE`, `LEADER_SPACE`, or `LINE_BREAK`. - HYPHEN = 4; - - // Line break that ends a paragraph. - LINE_BREAK = 5; - } - - // Detected break type. - BreakType type = 1; - - // True if break prepends the element. - bool is_prefix = 2; - } - - // Additional information detected on the structural component. - message TextProperty { - // A list of detected languages together with confidence. - repeated DetectedLanguage detected_languages = 1; - - // Detected start or end of a text segment. - DetectedBreak detected_break = 2; - } - - // List of pages detected by OCR. - repeated Page pages = 1; - - // UTF-8 text detected on the pages. - string text = 2; -} - -// Detected page from OCR. -message Page { - // Additional information detected on the page. - TextAnnotation.TextProperty property = 1; - - // Page width. For PDFs the unit is points. For images (including - // TIFFs) the unit is pixels. - int32 width = 2; - - // Page height. For PDFs the unit is points. For images (including - // TIFFs) the unit is pixels. - int32 height = 3; - - // List of blocks of text, images etc on this page. - repeated Block blocks = 4; - - // Confidence of the OCR results on the page. Range [0, 1]. - float confidence = 5; -} - -// Logical element on the page. -message Block { - // Type of a block (text, image etc) as identified by OCR. - enum BlockType { - // Unknown block type. - UNKNOWN = 0; - - // Regular text block. - TEXT = 1; - - // Table block. - TABLE = 2; - - // Image block. - PICTURE = 3; - - // Horizontal/vertical line box. - RULER = 4; - - // Barcode block. - BARCODE = 5; - } - - // Additional information detected for the block. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // List of paragraphs in this block (if this blocks is of type text). - repeated Paragraph paragraphs = 3; - - // Detected block type (text, image etc) for this block. - BlockType block_type = 4; - - // Confidence of the OCR results on the block. Range [0, 1]. - float confidence = 5; -} - -// Structural unit of text representing a number of words in certain order. -message Paragraph { - // Additional information detected for the paragraph. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // List of words in this paragraph. - repeated Word words = 3; - - // Confidence of the OCR results for the paragraph. Range [0, 1]. - float confidence = 4; -} - -// A word representation. -message Word { - // Additional information detected for the word. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // List of symbols in the word. - // The order of the symbols follows the natural reading order. - repeated Symbol symbols = 3; - - // Confidence of the OCR results for the word. Range [0, 1]. - float confidence = 4; -} - -// A single symbol representation. -message Symbol { - // Additional information detected for the symbol. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // The actual UTF-8 representation of the symbol. - string text = 3; - - // Confidence of the OCR results for the symbol. Range [0, 1]. - float confidence = 4; -} diff --git a/google/cloud/vision_v1p3beta1/proto/web_detection.proto b/google/cloud/vision_v1p3beta1/proto/web_detection.proto deleted file mode 100644 index cf9a2261..00000000 --- a/google/cloud/vision_v1p3beta1/proto/web_detection.proto +++ /dev/null @@ -1,104 +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"; - -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 = "WebDetectionProto"; -option java_package = "com.google.cloud.vision.v1p3beta1"; - -// Relevant information for the image from the Internet. -message WebDetection { - // Entity deduced from similar images on the Internet. - message WebEntity { - // Opaque entity ID. - string entity_id = 1; - - // Overall relevancy score for the entity. - // Not normalized and not comparable across different image queries. - float score = 2; - - // Canonical description of the entity, in English. - string description = 3; - } - - // Metadata for online images. - message WebImage { - // The result image URL. - string url = 1; - - // (Deprecated) Overall relevancy score for the image. - float score = 2; - } - - // Metadata for web pages. - message WebPage { - // The result web page URL. - string url = 1; - - // (Deprecated) Overall relevancy score for the web page. - float score = 2; - - // Title for the web page, may contain HTML markups. - string page_title = 3; - - // Fully matching images on the page. - // Can include resized copies of the query image. - repeated WebImage full_matching_images = 4; - - // 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. - repeated WebImage partial_matching_images = 5; - } - - // Label to provide extra metadata for the web detection. - message WebLabel { - // Label for extra metadata. - string label = 1; - - // 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. - string language_code = 2; - } - - // Deduced entities from similar images on the Internet. - repeated WebEntity web_entities = 1; - - // Fully matching images from the Internet. - // Can include resized copies of the query image. - repeated WebImage full_matching_images = 2; - - // 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. - repeated WebImage partial_matching_images = 3; - - // Web pages containing the matching images from the Internet. - repeated WebPage pages_with_matching_images = 4; - - // The visually similar image results. - repeated WebImage visually_similar_images = 6; - - // Best guess text labels for the request image. - repeated WebLabel best_guess_labels = 8; -} diff --git a/google/cloud/vision_v1p3beta1/services/__init__.py b/google/cloud/vision_v1p3beta1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/vision_v1p3beta1/services/__init__.py +++ b/google/cloud/vision_v1p3beta1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/__init__.py b/google/cloud/vision_v1p3beta1/services/image_annotator/__init__.py index 2b601881..422732ba 100644 --- a/google/cloud/vision_v1p3beta1/services/image_annotator/__init__.py +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ImageAnnotatorClient from .async_client import 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 index 59137286..8c460024 100644 --- a/google/cloud/vision_v1p3beta1/services/image_annotator/async_client.py +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,16 +20,15 @@ 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 exceptions as core_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 import credentials as ga_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 @@ -53,31 +50,26 @@ class ImageAnnotatorAsyncClient: parse_product_path = staticmethod(ImageAnnotatorClient.parse_product_path) product_set_path = staticmethod(ImageAnnotatorClient.product_set_path) parse_product_set_path = staticmethod(ImageAnnotatorClient.parse_product_set_path) - common_billing_account_path = staticmethod( ImageAnnotatorClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ImageAnnotatorClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ImageAnnotatorClient.common_folder_path) parse_common_folder_path = staticmethod( ImageAnnotatorClient.parse_common_folder_path ) - common_organization_path = staticmethod( ImageAnnotatorClient.common_organization_path ) parse_common_organization_path = staticmethod( ImageAnnotatorClient.parse_common_organization_path ) - common_project_path = staticmethod(ImageAnnotatorClient.common_project_path) parse_common_project_path = staticmethod( ImageAnnotatorClient.parse_common_project_path ) - common_location_path = staticmethod(ImageAnnotatorClient.common_location_path) parse_common_location_path = staticmethod( ImageAnnotatorClient.parse_common_location_path @@ -85,7 +77,8 @@ class ImageAnnotatorAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -100,7 +93,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -117,7 +110,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ImageAnnotatorTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ImageAnnotatorTransport: The transport used by the client instance. @@ -131,12 +124,12 @@ def transport(self) -> ImageAnnotatorTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_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. + """Instantiates the image annotator client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -168,7 +161,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ImageAnnotatorClient( credentials=credentials, transport=transport, @@ -199,7 +191,6 @@ async def batch_annotate_images( 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. @@ -226,7 +217,6 @@ async def batch_annotate_images( # If we have keyword arguments corresponding to fields on the # request, apply these. - if requests: request.requests.extend(requests) @@ -239,7 +229,8 @@ async def batch_annotate_images( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -281,7 +272,6 @@ async def async_batch_annotate_files( 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. @@ -311,7 +301,6 @@ async def async_batch_annotate_files( # If we have keyword arguments corresponding to fields on the # request, apply these. - if requests: request.requests.extend(requests) diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/client.py b/google/cloud/vision_v1p3beta1/services/image_annotator/client.py index eb5a0cf9..d9f989e4 100644 --- a/google/cloud/vision_v1p3beta1/services/image_annotator/client.py +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ 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 exceptions as core_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 import credentials as ga_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 @@ -35,7 +33,6 @@ 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 @@ -56,7 +53,7 @@ class ImageAnnotatorClientMeta(type): _transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ImageAnnotatorTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -83,7 +80,8 @@ class ImageAnnotatorClient(metaclass=ImageAnnotatorClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -117,7 +115,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -134,7 +133,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -153,23 +152,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ImageAnnotatorTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ImageAnnotatorTransport: The transport used by the client instance. + ImageAnnotatorTransport: The transport used by the client + instance. """ return self._transport @staticmethod def product_path(project: str, location: str, product: str,) -> str: - """Return a fully-qualified product string.""" + """Returns 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.""" + """Parses a product path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", path, @@ -178,14 +178,14 @@ def parse_product_path(path: str) -> Dict[str, str]: @staticmethod def product_set_path(project: str, location: str, product_set: str,) -> str: - """Return a fully-qualified product_set string.""" + """Returns 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.""" + """Parses a product_set path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", path, @@ -194,7 +194,7 @@ def parse_product_set_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -207,7 +207,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -218,7 +218,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -229,7 +229,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -240,7 +240,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -254,12 +254,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_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. + """Instantiates the image annotator client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -314,9 +314,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -328,12 +329,14 @@ def __init__( 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 - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -348,8 +351,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -387,7 +390,6 @@ def batch_annotate_images( 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. @@ -419,10 +421,8 @@ def batch_annotate_images( 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 @@ -464,7 +464,6 @@ def async_batch_annotate_files( 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. @@ -499,10 +498,8 @@ def async_batch_annotate_files( 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 diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/__init__.py b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/__init__.py index e2a0c3ea..419b4293 100644 --- a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/__init__.py +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py index 10e41bcc..381e427d 100644 --- a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_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.auth import credentials as ga_credentials # type: ignore from google.cloud.vision_v1p3beta1.types import image_annotator -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -37,6 +36,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ImageAnnotatorTransport(abc.ABC): """Abstract transport class for ImageAnnotator.""" @@ -46,21 +56,24 @@ class ImageAnnotatorTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-vision", ) + DEFAULT_HOST: str = "vision.googleapis.com" + 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, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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. + 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 @@ -69,7 +82,7 @@ def __init__( 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. + scopes (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): @@ -83,29 +96,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -116,7 +176,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -145,11 +206,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def batch_annotate_images( self, - ) -> typing.Callable[ + ) -> Callable[ [image_annotator.BatchAnnotateImagesRequest], - typing.Union[ + Union[ image_annotator.BatchAnnotateImagesResponse, - typing.Awaitable[image_annotator.BatchAnnotateImagesResponse], + Awaitable[image_annotator.BatchAnnotateImagesResponse], ], ]: raise NotImplementedError() @@ -157,9 +218,9 @@ def batch_annotate_images( @property def async_batch_annotate_files( self, - ) -> typing.Callable[ + ) -> Callable[ [image_annotator.AsyncBatchAnnotateFilesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py index a4913ae6..eb7daf7a 100644 --- a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # 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 typing import Callable, Dict, Optional, Sequence, Tuple, Union 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 +import google.auth # type: ignore +from google.auth import credentials as ga_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 google.longrunning import operations_pb2 # type: ignore from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -180,7 +178,7 @@ def __init__( def create_channel( cls, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -211,13 +209,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -275,7 +275,7 @@ def batch_annotate_images( def async_batch_annotate_files( self, ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], operations.Operation + [image_annotator.AsyncBatchAnnotateFilesRequest], operations_pb2.Operation ]: r"""Return a callable for the async batch annotate files method over gRPC. @@ -301,7 +301,7 @@ def async_batch_annotate_files( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["async_batch_annotate_files"] 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 index 97a40b99..ebc81645 100644 --- a/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc_asyncio.py +++ b/google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union 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 import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version 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 google.longrunning import operations_pb2 # type: ignore from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .grpc import ImageAnnotatorGrpcTransport @@ -58,7 +55,7 @@ class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): def create_channel( cls, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -172,7 +172,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -282,7 +281,7 @@ def async_batch_annotate_files( self, ) -> Callable[ [image_annotator.AsyncBatchAnnotateFilesRequest], - Awaitable[operations.Operation], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the async batch annotate files method over gRPC. @@ -308,7 +307,7 @@ def async_batch_annotate_files( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["async_batch_annotate_files"] diff --git a/google/cloud/vision_v1p3beta1/services/product_search/__init__.py b/google/cloud/vision_v1p3beta1/services/product_search/__init__.py index e82b5909..f357996e 100644 --- a/google/cloud/vision_v1p3beta1/services/product_search/__init__.py +++ b/google/cloud/vision_v1p3beta1/services/product_search/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ProductSearchClient from .async_client import 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 index f644391c..3ac90b29 100644 --- a/google/cloud/vision_v1p3beta1/services/product_search/async_client.py +++ b/google/cloud/vision_v1p3beta1/services/product_search/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ 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 exceptions as core_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 import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -33,10 +31,9 @@ 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 google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport from .client import ProductSearchClient @@ -78,31 +75,26 @@ class ProductSearchAsyncClient: parse_reference_image_path = staticmethod( ProductSearchClient.parse_reference_image_path ) - common_billing_account_path = staticmethod( ProductSearchClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ProductSearchClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ProductSearchClient.common_folder_path) parse_common_folder_path = staticmethod( ProductSearchClient.parse_common_folder_path ) - common_organization_path = staticmethod( ProductSearchClient.common_organization_path ) parse_common_organization_path = staticmethod( ProductSearchClient.parse_common_organization_path ) - common_project_path = staticmethod(ProductSearchClient.common_project_path) parse_common_project_path = staticmethod( ProductSearchClient.parse_common_project_path ) - common_location_path = staticmethod(ProductSearchClient.common_location_path) parse_common_location_path = staticmethod( ProductSearchClient.parse_common_location_path @@ -110,7 +102,8 @@ class ProductSearchAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -125,7 +118,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -142,7 +135,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ProductSearchTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ProductSearchTransport: The transport used by the client instance. @@ -156,12 +149,12 @@ def transport(self) -> ProductSearchTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_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. + """Instantiates the product search client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -193,7 +186,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ProductSearchClient( credentials=credentials, transport=transport, @@ -247,7 +239,6 @@ async def create_product_set( 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. @@ -277,7 +268,6 @@ async def create_product_set( # 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: @@ -341,7 +331,6 @@ async def list_product_sets( 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. @@ -370,7 +359,6 @@ async def list_product_sets( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -383,7 +371,8 @@ async def list_product_sets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -437,7 +426,6 @@ async def get_product_set( 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. @@ -467,7 +455,6 @@ async def get_product_set( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -480,7 +467,8 @@ async def get_product_set( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -505,7 +493,7 @@ async def update_product_set( request: product_search_service.UpdateProductSetRequest = None, *, product_set: product_search_service.ProductSet = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -540,7 +528,6 @@ async def update_product_set( 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. @@ -570,7 +557,6 @@ async def update_product_set( # 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: @@ -637,7 +623,6 @@ async def delete_product_set( 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. @@ -658,7 +643,6 @@ async def delete_product_set( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -671,7 +655,8 @@ async def delete_product_set( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -740,7 +725,6 @@ async def create_product( 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. @@ -765,7 +749,6 @@ async def create_product( # 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: @@ -829,7 +812,6 @@ async def list_products( 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. @@ -858,7 +840,6 @@ async def list_products( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -871,7 +852,8 @@ async def list_products( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -925,7 +907,6 @@ async def get_product( 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. @@ -950,7 +931,6 @@ async def get_product( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -963,7 +943,8 @@ async def get_product( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -988,7 +969,7 @@ async def update_product( request: product_search_service.UpdateProductRequest = None, *, product: product_search_service.Product = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1032,7 +1013,6 @@ async def update_product( 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. @@ -1057,7 +1037,6 @@ async def update_product( # 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: @@ -1124,7 +1103,6 @@ async def delete_product( 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. @@ -1145,7 +1123,6 @@ async def delete_product( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1158,7 +1135,8 @@ async def delete_product( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1243,7 +1221,6 @@ async def create_reference_image( 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. @@ -1270,7 +1247,6 @@ async def create_reference_image( # 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: @@ -1342,7 +1318,6 @@ async def delete_reference_image( 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. @@ -1363,7 +1338,6 @@ async def delete_reference_image( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1376,7 +1350,8 @@ async def delete_reference_image( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1426,7 +1401,6 @@ async def list_reference_images( 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. @@ -1455,7 +1429,6 @@ async def list_reference_images( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1468,7 +1441,8 @@ async def list_reference_images( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1524,7 +1498,6 @@ async def get_reference_image( 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. @@ -1551,7 +1524,6 @@ async def get_reference_image( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1564,7 +1536,8 @@ async def get_reference_image( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1628,7 +1601,6 @@ async def add_product_to_product_set( 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. @@ -1649,7 +1621,6 @@ async def add_product_to_product_set( # 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: @@ -1722,7 +1693,6 @@ async def remove_product_from_product_set( 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. @@ -1743,7 +1713,6 @@ async def remove_product_from_product_set( # 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: @@ -1807,7 +1776,6 @@ async def list_products_in_product_set( 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. @@ -1837,7 +1805,6 @@ async def list_products_in_product_set( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1850,7 +1817,8 @@ async def list_products_in_product_set( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1919,7 +1887,6 @@ async def import_product_sets( 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. @@ -1955,7 +1922,6 @@ async def import_product_sets( # 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: diff --git a/google/cloud/vision_v1p3beta1/services/product_search/client.py b/google/cloud/vision_v1p3beta1/services/product_search/client.py index 729476be..6dd45e09 100644 --- a/google/cloud/vision_v1p3beta1/services/product_search/client.py +++ b/google/cloud/vision_v1p3beta1/services/product_search/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ 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 exceptions as core_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 import credentials as ga_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 @@ -37,10 +35,9 @@ 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 google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ProductSearchGrpcTransport from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport @@ -59,7 +56,7 @@ class ProductSearchClientMeta(type): _transport_registry["grpc_asyncio"] = ProductSearchGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ProductSearchTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -102,7 +99,8 @@ class ProductSearchClient(metaclass=ProductSearchClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -136,7 +134,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -153,7 +152,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -172,23 +171,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ProductSearchTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ProductSearchTransport: The transport used by the client instance. + ProductSearchTransport: The transport used by the client + instance. """ return self._transport @staticmethod def product_path(project: str, location: str, product: str,) -> str: - """Return a fully-qualified product string.""" + """Returns 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.""" + """Parses a product path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", path, @@ -197,14 +197,14 @@ def parse_product_path(path: str) -> Dict[str, str]: @staticmethod def product_set_path(project: str, location: str, product_set: str,) -> str: - """Return a fully-qualified product_set string.""" + """Returns 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.""" + """Parses a product_set path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", path, @@ -215,7 +215,7 @@ def parse_product_set_path(path: str) -> Dict[str, str]: def reference_image_path( project: str, location: str, product: str, reference_image: str, ) -> str: - """Return a fully-qualified reference_image string.""" + """Returns a fully-qualified reference_image string.""" return "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( project=project, location=location, @@ -225,7 +225,7 @@ def reference_image_path( @staticmethod def parse_reference_image_path(path: str) -> Dict[str, str]: - """Parse a reference_image path into its component segments.""" + """Parses a reference_image path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)/referenceImages/(?P.+?)$", path, @@ -234,7 +234,7 @@ def parse_reference_image_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -247,7 +247,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -258,7 +258,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -269,7 +269,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -280,7 +280,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -294,12 +294,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_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. + """Instantiates the product search client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -354,9 +354,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -368,12 +369,14 @@ def __init__( 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 - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -388,8 +391,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -450,7 +453,6 @@ def create_product_set( 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. @@ -482,10 +484,8 @@ def create_product_set( # 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: @@ -538,7 +538,6 @@ def list_product_sets( 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. @@ -569,10 +568,8 @@ def list_product_sets( # 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 @@ -626,7 +623,6 @@ def get_product_set( 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. @@ -658,10 +654,8 @@ def get_product_set( # 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 @@ -686,7 +680,7 @@ def update_product_set( request: product_search_service.UpdateProductSetRequest = None, *, product_set: product_search_service.ProductSet = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -721,7 +715,6 @@ def update_product_set( 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. @@ -753,10 +746,8 @@ def update_product_set( # 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: @@ -812,7 +803,6 @@ def delete_product_set( 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. @@ -835,10 +825,8 @@ def delete_product_set( # 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 @@ -907,7 +895,6 @@ def create_product( 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. @@ -934,10 +921,8 @@ def create_product( # 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: @@ -990,7 +975,6 @@ def list_products( 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. @@ -1021,10 +1005,8 @@ def list_products( # 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 @@ -1078,7 +1060,6 @@ def get_product( 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. @@ -1105,10 +1086,8 @@ def get_product( # 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 @@ -1133,7 +1112,7 @@ def update_product( request: product_search_service.UpdateProductRequest = None, *, product: product_search_service.Product = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1177,7 +1156,6 @@ def update_product( 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. @@ -1204,10 +1182,8 @@ def update_product( # 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: @@ -1263,7 +1239,6 @@ def delete_product( 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. @@ -1286,10 +1261,8 @@ def delete_product( # 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 @@ -1374,7 +1347,6 @@ def create_reference_image( 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. @@ -1403,10 +1375,8 @@ def create_reference_image( # 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: @@ -1467,7 +1437,6 @@ def delete_reference_image( 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. @@ -1490,10 +1459,8 @@ def delete_reference_image( # 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 @@ -1543,7 +1510,6 @@ def list_reference_images( 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. @@ -1574,10 +1540,8 @@ def list_reference_images( # 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 @@ -1633,7 +1597,6 @@ def get_reference_image( 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. @@ -1662,10 +1625,8 @@ def get_reference_image( # 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 @@ -1729,7 +1690,6 @@ def add_product_to_product_set( 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. @@ -1754,10 +1714,8 @@ def add_product_to_product_set( 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: @@ -1821,7 +1779,6 @@ def remove_product_from_product_set( 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. @@ -1846,10 +1803,8 @@ def remove_product_from_product_set( 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: @@ -1904,7 +1859,6 @@ def list_products_in_product_set( 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. @@ -1938,10 +1892,8 @@ def list_products_in_product_set( 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 @@ -2012,7 +1964,6 @@ def import_product_sets( 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. @@ -2050,10 +2001,8 @@ def import_product_sets( # 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: diff --git a/google/cloud/vision_v1p3beta1/services/product_search/pagers.py b/google/cloud/vision_v1p3beta1/services/product_search/pagers.py index 49f585a6..e6b70676 100644 --- a/google/cloud/vision_v1p3beta1/services/product_search/pagers.py +++ b/google/cloud/vision_v1p3beta1/services/product_search/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -249,7 +247,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -379,7 +377,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -513,7 +511,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/vision_v1p3beta1/services/product_search/transports/__init__.py b/google/cloud/vision_v1p3beta1/services/product_search/transports/__init__.py index 8295a6de..f38d3aef 100644 --- a/google/cloud/vision_v1p3beta1/services/product_search/transports/__init__.py +++ b/google/cloud/vision_v1p3beta1/services/product_search/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/vision_v1p3beta1/services/product_search/transports/base.py b/google/cloud/vision_v1p3beta1/services/product_search/transports/base.py index f9ba4746..5fe11de3 100644 --- a/google/cloud/vision_v1p3beta1/services/product_search/transports/base.py +++ b/google/cloud/vision_v1p3beta1/services/product_search/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_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.auth import credentials as ga_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 - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -38,6 +37,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ProductSearchTransport(abc.ABC): """Abstract transport class for ProductSearch.""" @@ -47,21 +57,24 @@ class ProductSearchTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-vision", ) + DEFAULT_HOST: str = "vision.googleapis.com" + 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, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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. + 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 @@ -70,7 +83,7 @@ def __init__( 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. + scopes (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): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -129,7 +189,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -143,7 +204,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -169,7 +231,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -195,7 +258,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -209,7 +273,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -235,7 +300,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -261,7 +327,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -275,7 +342,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -289,7 +357,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -327,7 +396,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -356,11 +426,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def create_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.CreateProductSetRequest], - typing.Union[ + Union[ product_search_service.ProductSet, - typing.Awaitable[product_search_service.ProductSet], + Awaitable[product_search_service.ProductSet], ], ]: raise NotImplementedError() @@ -368,11 +438,11 @@ def create_product_set( @property def list_product_sets( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.ListProductSetsRequest], - typing.Union[ + Union[ product_search_service.ListProductSetsResponse, - typing.Awaitable[product_search_service.ListProductSetsResponse], + Awaitable[product_search_service.ListProductSetsResponse], ], ]: raise NotImplementedError() @@ -380,11 +450,11 @@ def list_product_sets( @property def get_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.GetProductSetRequest], - typing.Union[ + Union[ product_search_service.ProductSet, - typing.Awaitable[product_search_service.ProductSet], + Awaitable[product_search_service.ProductSet], ], ]: raise NotImplementedError() @@ -392,11 +462,11 @@ def get_product_set( @property def update_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.UpdateProductSetRequest], - typing.Union[ + Union[ product_search_service.ProductSet, - typing.Awaitable[product_search_service.ProductSet], + Awaitable[product_search_service.ProductSet], ], ]: raise NotImplementedError() @@ -404,20 +474,19 @@ def update_product_set( @property def delete_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.DeleteProductSetRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def create_product( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.CreateProductRequest], - typing.Union[ - product_search_service.Product, - typing.Awaitable[product_search_service.Product], + Union[ + product_search_service.Product, Awaitable[product_search_service.Product] ], ]: raise NotImplementedError() @@ -425,11 +494,11 @@ def create_product( @property def list_products( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.ListProductsRequest], - typing.Union[ + Union[ product_search_service.ListProductsResponse, - typing.Awaitable[product_search_service.ListProductsResponse], + Awaitable[product_search_service.ListProductsResponse], ], ]: raise NotImplementedError() @@ -437,11 +506,10 @@ def list_products( @property def get_product( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.GetProductRequest], - typing.Union[ - product_search_service.Product, - typing.Awaitable[product_search_service.Product], + Union[ + product_search_service.Product, Awaitable[product_search_service.Product] ], ]: raise NotImplementedError() @@ -449,11 +517,10 @@ def get_product( @property def update_product( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.UpdateProductRequest], - typing.Union[ - product_search_service.Product, - typing.Awaitable[product_search_service.Product], + Union[ + product_search_service.Product, Awaitable[product_search_service.Product] ], ]: raise NotImplementedError() @@ -461,20 +528,20 @@ def update_product( @property def delete_product( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.DeleteProductRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def create_reference_image( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.CreateReferenceImageRequest], - typing.Union[ + Union[ product_search_service.ReferenceImage, - typing.Awaitable[product_search_service.ReferenceImage], + Awaitable[product_search_service.ReferenceImage], ], ]: raise NotImplementedError() @@ -482,20 +549,20 @@ def create_reference_image( @property def delete_reference_image( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.DeleteReferenceImageRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def list_reference_images( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.ListReferenceImagesRequest], - typing.Union[ + Union[ product_search_service.ListReferenceImagesResponse, - typing.Awaitable[product_search_service.ListReferenceImagesResponse], + Awaitable[product_search_service.ListReferenceImagesResponse], ], ]: raise NotImplementedError() @@ -503,11 +570,11 @@ def list_reference_images( @property def get_reference_image( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.GetReferenceImageRequest], - typing.Union[ + Union[ product_search_service.ReferenceImage, - typing.Awaitable[product_search_service.ReferenceImage], + Awaitable[product_search_service.ReferenceImage], ], ]: raise NotImplementedError() @@ -515,29 +582,29 @@ def get_reference_image( @property def add_product_to_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.AddProductToProductSetRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def remove_product_from_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.RemoveProductFromProductSetRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def list_products_in_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.ListProductsInProductSetRequest], - typing.Union[ + Union[ product_search_service.ListProductsInProductSetResponse, - typing.Awaitable[product_search_service.ListProductsInProductSetResponse], + Awaitable[product_search_service.ListProductsInProductSetResponse], ], ]: raise NotImplementedError() @@ -545,9 +612,9 @@ def list_products_in_product_set( @property def import_product_sets( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.ImportProductSetsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py b/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py index 5844bad9..a3a0ebdd 100644 --- a/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py +++ b/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # 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 typing import Callable, Dict, Optional, Sequence, Tuple, Union 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 +import google.auth # type: ignore +from google.auth import credentials as ga_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 google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO @@ -72,7 +69,7 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -86,7 +83,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -197,7 +195,7 @@ def __init__( def create_channel( cls, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -228,13 +226,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -398,7 +398,7 @@ def update_product_set( @property def delete_product_set( self, - ) -> Callable[[product_search_service.DeleteProductSetRequest], empty.Empty]: + ) -> Callable[[product_search_service.DeleteProductSetRequest], empty_pb2.Empty]: r"""Return a callable for the delete product set method over gRPC. Permanently deletes a ProductSet. All Products and @@ -425,7 +425,7 @@ def delete_product_set( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_product_set"] @@ -578,7 +578,7 @@ def update_product( @property def delete_product( self, - ) -> Callable[[product_search_service.DeleteProductRequest], empty.Empty]: + ) -> Callable[[product_search_service.DeleteProductRequest], empty_pb2.Empty]: r"""Return a callable for the delete product method over gRPC. Permanently deletes a product and its reference images. @@ -605,7 +605,7 @@ def delete_product( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_product"] @@ -662,7 +662,9 @@ def create_reference_image( @property def delete_reference_image( self, - ) -> Callable[[product_search_service.DeleteReferenceImageRequest], empty.Empty]: + ) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], empty_pb2.Empty + ]: r"""Return a callable for the delete reference image method over gRPC. Permanently deletes a reference image. @@ -692,7 +694,7 @@ def delete_reference_image( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_reference_image"] @@ -767,7 +769,9 @@ def get_reference_image( @property def add_product_to_product_set( self, - ) -> Callable[[product_search_service.AddProductToProductSetRequest], empty.Empty]: + ) -> Callable[ + [product_search_service.AddProductToProductSetRequest], empty_pb2.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 @@ -794,7 +798,7 @@ def add_product_to_product_set( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["add_product_to_product_set"] @@ -802,7 +806,7 @@ def add_product_to_product_set( def remove_product_from_product_set( self, ) -> Callable[ - [product_search_service.RemoveProductFromProductSetRequest], empty.Empty + [product_search_service.RemoveProductFromProductSetRequest], empty_pb2.Empty ]: r"""Return a callable for the remove product from product set method over gRPC. @@ -830,7 +834,7 @@ def 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["remove_product_from_product_set"] @@ -874,7 +878,7 @@ def list_products_in_product_set( def import_product_sets( self, ) -> Callable[ - [product_search_service.ImportProductSetsRequest], operations.Operation + [product_search_service.ImportProductSetsRequest], operations_pb2.Operation ]: r"""Return a callable for the import product sets method over gRPC. @@ -905,7 +909,7 @@ def import_product_sets( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_product_sets"] 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 index 326e71c7..89edcf5d 100644 --- a/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc_asyncio.py +++ b/google/cloud/vision_v1p3beta1/services/product_search/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union 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 import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version 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 google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .grpc import ProductSearchGrpcTransport @@ -75,7 +72,7 @@ class ProductSearchGrpcAsyncIOTransport(ProductSearchTransport): def create_channel( cls, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -102,13 +99,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -116,7 +115,7 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -130,7 +129,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -189,7 +189,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -406,7 +405,7 @@ def update_product_set( def delete_product_set( self, ) -> Callable[ - [product_search_service.DeleteProductSetRequest], Awaitable[empty.Empty] + [product_search_service.DeleteProductSetRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete product set method over gRPC. @@ -434,7 +433,7 @@ def delete_product_set( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_product_set"] @@ -591,7 +590,7 @@ def update_product( def delete_product( self, ) -> Callable[ - [product_search_service.DeleteProductRequest], Awaitable[empty.Empty] + [product_search_service.DeleteProductRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete product method over gRPC. @@ -619,7 +618,7 @@ def delete_product( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_product"] @@ -677,7 +676,7 @@ def create_reference_image( def delete_reference_image( self, ) -> Callable[ - [product_search_service.DeleteReferenceImageRequest], Awaitable[empty.Empty] + [product_search_service.DeleteReferenceImageRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete reference image method over gRPC. @@ -708,7 +707,7 @@ def delete_reference_image( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_reference_image"] @@ -784,7 +783,8 @@ def get_reference_image( def add_product_to_product_set( self, ) -> Callable[ - [product_search_service.AddProductToProductSetRequest], Awaitable[empty.Empty] + [product_search_service.AddProductToProductSetRequest], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the add product to product set method over gRPC. @@ -812,7 +812,7 @@ def add_product_to_product_set( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["add_product_to_product_set"] @@ -821,7 +821,7 @@ def remove_product_from_product_set( self, ) -> Callable[ [product_search_service.RemoveProductFromProductSetRequest], - Awaitable[empty.Empty], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the remove product from product set method over gRPC. @@ -849,7 +849,7 @@ def 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["remove_product_from_product_set"] @@ -894,7 +894,7 @@ def import_product_sets( self, ) -> Callable[ [product_search_service.ImportProductSetsRequest], - Awaitable[operations.Operation], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the import product sets method over gRPC. @@ -925,7 +925,7 @@ def import_product_sets( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_product_sets"] diff --git a/google/cloud/vision_v1p3beta1/types/__init__.py b/google/cloud/vision_v1p3beta1/types/__init__.py index 927cc5e0..8db76dfa 100644 --- a/google/cloud/vision_v1p3beta1/types/__init__.py +++ b/google/cloud/vision_v1p3beta1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .geometry import ( BoundingPoly, NormalizedBoundingPoly, diff --git a/google/cloud/vision_v1p3beta1/types/geometry.py b/google/cloud/vision_v1p3beta1/types/geometry.py index c1b1fd91..04c7a90b 100644 --- a/google/cloud/vision_v1p3beta1/types/geometry.py +++ b/google/cloud/vision_v1p3beta1/types/geometry.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -42,9 +40,8 @@ class Vertex(proto.Message): Y coordinate. """ - x = proto.Field(proto.INT32, number=1) - - y = proto.Field(proto.INT32, number=2) + x = proto.Field(proto.INT32, number=1,) + y = proto.Field(proto.INT32, number=2,) class NormalizedVertex(proto.Message): @@ -59,14 +56,12 @@ class NormalizedVertex(proto.Message): Y coordinate. """ - x = proto.Field(proto.FLOAT, number=1) - - y = proto.Field(proto.FLOAT, number=2) + 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[google.cloud.vision_v1p3beta1.types.Vertex]): The bounding polygon vertices. @@ -75,7 +70,6 @@ class BoundingPoly(proto.Message): """ vertices = proto.RepeatedField(proto.MESSAGE, number=1, message="Vertex",) - normalized_vertices = proto.RepeatedField( proto.MESSAGE, number=2, message="NormalizedVertex", ) @@ -83,7 +77,6 @@ class BoundingPoly(proto.Message): class NormalizedBoundingPoly(proto.Message): r"""A normalized bounding polygon around a portion of an image. - Attributes: vertices (Sequence[google.cloud.vision_v1p3beta1.types.NormalizedVertex]): Normalized vertices of the bounding polygon. @@ -107,11 +100,9 @@ class Position(proto.Message): 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) + 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 index 0af98b5a..a0fa0b7c 100644 --- a/google/cloud/vision_v1p3beta1/types/image_annotator.py +++ b/google/cloud/vision_v1p3beta1/types/image_annotator.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,18 +13,16 @@ # 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 +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import color_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore __protobuf__ = proto.module( @@ -117,10 +114,8 @@ class Type(proto.Enum): 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) + max_results = proto.Field(proto.INT32, number=2,) + model = proto.Field(proto.STRING, number=3,) class ImageSource(proto.Message): @@ -158,14 +153,12 @@ class ImageSource(proto.Message): ``image_uri`` takes precedence. """ - gcs_image_uri = proto.Field(proto.STRING, number=1) - - image_uri = proto.Field(proto.STRING, number=2) + 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 @@ -178,8 +171,7 @@ class Image(proto.Message): perform the image annotation request. """ - content = proto.Field(proto.BYTES, number=1) - + content = proto.Field(proto.BYTES, number=1,) source = proto.Field(proto.MESSAGE, number=2, message="ImageSource",) @@ -242,7 +234,6 @@ class FaceAnnotation(proto.Message): class Landmark(proto.Message): r"""A face-specific landmark (for example, a face feature). - Attributes: type_ (google.cloud.vision_v1p3beta1.types.FaceAnnotation.Landmark.Type): Face landmark type. @@ -293,56 +284,39 @@ class Type(proto.Enum): 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) - + 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 (google.type.latlng_pb2.LatLng): lat/long location coordinates. """ - lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng.LatLng,) + lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng_pb2.LatLng,) class Property(proto.Message): r"""A ``Property`` consists of a user-supplied name/value pair. - Attributes: name (str): Name of the property. @@ -352,16 +326,13 @@ class Property(proto.Message): 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) + 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 @@ -404,28 +375,19 @@ class EntityAnnotation(proto.Message): 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) - + 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 @@ -443,14 +405,10 @@ class LocalizedObjectAnnotation(proto.Message): 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) - + 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,) @@ -484,19 +442,14 @@ class SafeSearchAnnotation(proto.Message): """ 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 (google.type.latlng_pb2.LatLng): Min lat/long pair. @@ -504,9 +457,8 @@ class LatLongRect(proto.Message): 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,) + min_lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng_pb2.LatLng,) + max_lat_lng = proto.Field(proto.MESSAGE, number=2, message=latlng_pb2.LatLng,) class ColorInfo(proto.Message): @@ -523,16 +475,13 @@ class ColorInfo(proto.Message): 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) + color = proto.Field(proto.MESSAGE, number=1, message=color_pb2.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[google.cloud.vision_v1p3beta1.types.ColorInfo]): RGB color values with their score and pixel @@ -544,7 +493,6 @@ class DominantColorsAnnotation(proto.Message): class ImageProperties(proto.Message): r"""Stores image properties, such as dominant colors. - Attributes: dominant_colors (google.cloud.vision_v1p3beta1.types.DominantColorsAnnotation): If present, dominant colors completed @@ -573,10 +521,8 @@ class CropHint(proto.Message): """ 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) + confidence = proto.Field(proto.FLOAT, number=2,) + importance_fraction = proto.Field(proto.FLOAT, number=3,) class CropHintsAnnotation(proto.Message): @@ -593,7 +539,6 @@ class CropHintsAnnotation(proto.Message): class CropHintsParams(proto.Message): r"""Parameters for crop hints annotation request. - Attributes: aspect_ratios (Sequence[float]): Aspect ratios in floats, representing the @@ -606,19 +551,18 @@ class CropHintsParams(proto.Message): provided after the 16th are ignored. """ - aspect_ratios = proto.RepeatedField(proto.FLOAT, number=1) + 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) + include_geo_results = proto.Field(proto.BOOL, number=2,) class TextDetectionParams(proto.Message): @@ -632,12 +576,11 @@ class TextDetectionParams(proto.Message): include confidence score for TEXT_DETECTION as well. """ - enable_text_detection_confidence_score = proto.Field(proto.BOOL, number=9) + enable_text_detection_confidence_score = proto.Field(proto.BOOL, number=9,) class ImageContext(proto.Message): r"""Image context and/or feature-specific parameters. - Attributes: lat_long_rect (google.cloud.vision_v1p3beta1.types.LatLongRect): Not used. @@ -664,19 +607,14 @@ class ImageContext(proto.Message): """ lat_long_rect = proto.Field(proto.MESSAGE, number=1, message="LatLongRect",) - - language_hints = proto.RepeatedField(proto.STRING, number=2) - + 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", ) - text_detection_params = proto.Field( proto.MESSAGE, number=12, message="TextDetectionParams", ) @@ -697,9 +635,7 @@ class AnnotateImageRequest(proto.Message): """ 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",) @@ -717,14 +653,12 @@ class ImageAnnotationContext(proto.Message): produce the image. """ - uri = proto.Field(proto.STRING, number=1) - - page_number = proto.Field(proto.INT32, number=2) + 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[google.cloud.vision_v1p3beta1.types.FaceAnnotation]): If present, face detection has completed @@ -777,53 +711,40 @@ class AnnotateImageResponse(proto.Message): 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,) - + error = proto.Field(proto.MESSAGE, number=9, message=status_pb2.Status,) context = proto.Field(proto.MESSAGE, number=21, message="ImageAnnotationContext",) @@ -842,7 +763,6 @@ class AnnotateFileResponse(proto.Message): """ input_config = proto.Field(proto.MESSAGE, number=1, message="InputConfig",) - responses = proto.RepeatedField( proto.MESSAGE, number=2, message="AnnotateImageResponse", ) @@ -865,7 +785,6 @@ class BatchAnnotateImagesRequest(proto.Message): class BatchAnnotateImagesResponse(proto.Message): r"""Response to a batch image annotation request. - Attributes: responses (Sequence[google.cloud.vision_v1p3beta1.types.AnnotateImageResponse]): Individual responses to image annotation @@ -879,7 +798,6 @@ class BatchAnnotateImagesResponse(proto.Message): class AsyncAnnotateFileRequest(proto.Message): r"""An offline file annotation request. - Attributes: input_config (google.cloud.vision_v1p3beta1.types.InputConfig): Required. Information about the input file. @@ -894,17 +812,13 @@ class AsyncAnnotateFileRequest(proto.Message): """ 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 (google.cloud.vision_v1p3beta1.types.OutputConfig): The output location and metadata from @@ -931,7 +845,6 @@ class AsyncBatchAnnotateFilesRequest(proto.Message): class AsyncBatchAnnotateFilesResponse(proto.Message): r"""Response to an async batch file annotation request. - Attributes: responses (Sequence[google.cloud.vision_v1p3beta1.types.AsyncAnnotateFileResponse]): The list of file annotation responses, one @@ -946,7 +859,6 @@ class AsyncBatchAnnotateFilesResponse(proto.Message): class InputConfig(proto.Message): r"""The desired input location and metadata. - Attributes: gcs_source (google.cloud.vision_v1p3beta1.types.GcsSource): The Google Cloud Storage location to read the @@ -958,13 +870,11 @@ class InputConfig(proto.Message): """ gcs_source = proto.Field(proto.MESSAGE, number=1, message="GcsSource",) - - mime_type = proto.Field(proto.STRING, number=2) + mime_type = proto.Field(proto.STRING, number=2,) class OutputConfig(proto.Message): r"""The desired output location and metadata. - Attributes: gcs_destination (google.cloud.vision_v1p3beta1.types.GcsDestination): The Google Cloud Storage location to write @@ -984,8 +894,7 @@ class OutputConfig(proto.Message): """ gcs_destination = proto.Field(proto.MESSAGE, number=1, message="GcsDestination",) - - batch_size = proto.Field(proto.INT32, number=2) + batch_size = proto.Field(proto.INT32, number=2,) class GcsSource(proto.Message): @@ -999,7 +908,7 @@ class GcsSource(proto.Message): Wildcards are not currently supported. """ - uri = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) class GcsDestination(proto.Message): @@ -1027,12 +936,11 @@ class GcsDestination(proto.Message): overflows into multiple sharded files. """ - uri = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) class OperationMetadata(proto.Message): r"""Contains metadata for the BatchAnnotateImages operation. - Attributes: state (google.cloud.vision_v1p3beta1.types.OperationMetadata.State): Current state of the batch operation. @@ -1052,10 +960,8 @@ class State(proto.Enum): 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,) + create_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + update_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.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 index 43cb9f3a..f96c5a38 100644 --- a/google/cloud/vision_v1p3beta1/types/product_search.py +++ b/google/cloud/vision_v1p3beta1/types/product_search.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # 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 +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -49,7 +46,6 @@ class ProductSearchResultsView(proto.Enum): class ProductSearchParams(proto.Message): r"""Parameters for a product search request. - Attributes: catalog_name (str): The resource name of the catalog to search. @@ -98,30 +94,21 @@ class ProductSearchParams(proto.Message): red OR brand = Google)" or "color: red". """ - catalog_name = proto.Field(proto.STRING, number=1) - + 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) - + 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) + 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 (google.cloud.vision_v1p3beta1.types.ProductSearchCategory): Product category. [Deprecated] Use ``product_category``. @@ -141,7 +128,6 @@ class ProductSearchResults(proto.Message): class ProductInfo(proto.Message): r"""Information about a product. - Attributes: product_id (str): Product ID. @@ -158,15 +144,12 @@ class ProductInfo(proto.Message): 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) + 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 (google.cloud.vision_v1p3beta1.types.Product): The Product. @@ -184,19 +167,13 @@ class Result(proto.Message): 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) + 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,) - + product_category = proto.Field(proto.STRING, number=4,) + index_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) products = proto.RepeatedField(proto.MESSAGE, number=3, message=ProductInfo,) - results = proto.RepeatedField(proto.MESSAGE, number=5, message=Result,) diff --git a/google/cloud/vision_v1p3beta1/types/product_search_service.py b/google/cloud/vision_v1p3beta1/types/product_search_service.py index aef592b7..c42c3bf1 100644 --- a/google/cloud/vision_v1p3beta1/types/product_search_service.py +++ b/google/cloud/vision_v1p3beta1/types/product_search_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # 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 +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -62,7 +59,6 @@ class Product(proto.Message): r"""A Product contains ReferenceImages. - Attributes: name (str): The resource name of the product. @@ -100,7 +96,6 @@ class Product(proto.Message): 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. @@ -111,18 +106,13 @@ class KeyValue(proto.Message): 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) + 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,) @@ -160,13 +150,10 @@ class ProductSet(proto.Message): 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,) + 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_pb2.Timestamp,) + index_error = proto.Field(proto.MESSAGE, number=4, message=status_pb2.Status,) class ReferenceImage(proto.Message): @@ -200,10 +187,8 @@ class ReferenceImage(proto.Message): 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) - + 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, ) @@ -211,7 +196,6 @@ class ReferenceImage(proto.Message): class CreateProductRequest(proto.Message): r"""Request message for the ``CreateProduct`` method. - Attributes: parent (str): Required. The project in which the Product should be @@ -228,16 +212,13 @@ class CreateProductRequest(proto.Message): cannot contain the character ``/``. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) product = proto.Field(proto.MESSAGE, number=2, message="Product",) - - product_id = proto.Field(proto.STRING, number=3) + 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 @@ -252,16 +233,13 @@ class ListProductsRequest(proto.Message): 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) + 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[google.cloud.vision_v1p3beta1.types.Product]): List of products. @@ -276,13 +254,11 @@ def raw_page(self): return self products = proto.RepeatedField(proto.MESSAGE, number=1, message="Product",) - - next_page_token = proto.Field(proto.STRING, number=2) + 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. @@ -291,12 +267,11 @@ class GetProductRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateProductRequest(proto.Message): r"""Request message for the ``UpdateProduct`` method. - Attributes: product (google.cloud.vision_v1p3beta1.types.Product): Required. The Product resource which replaces @@ -310,13 +285,13 @@ class UpdateProductRequest(proto.Message): """ product = proto.Field(proto.MESSAGE, number=1, message="Product",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteProductRequest(proto.Message): r"""Request message for the ``DeleteProduct`` method. - Attributes: name (str): Required. Resource name of product to delete. @@ -325,12 +300,11 @@ class DeleteProductRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field(proto.STRING, number=1) + 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 @@ -347,16 +321,13 @@ class CreateProductSetRequest(proto.Message): cannot contain the character ``/``. """ - parent = proto.Field(proto.STRING, number=1) - + 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) + 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 @@ -371,16 +342,13 @@ class ListProductSetsRequest(proto.Message): 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) + 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[google.cloud.vision_v1p3beta1.types.ProductSet]): List of ProductSets. @@ -395,13 +363,11 @@ 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) + 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. @@ -410,12 +376,11 @@ class GetProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateProductSetRequest(proto.Message): r"""Request message for the ``UpdateProductSet`` method. - Attributes: product_set (google.cloud.vision_v1p3beta1.types.ProductSet): Required. The ProductSet resource which @@ -428,13 +393,13 @@ class UpdateProductSetRequest(proto.Message): """ product_set = proto.Field(proto.MESSAGE, number=1, message="ProductSet",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteProductSetRequest(proto.Message): r"""Request message for the ``DeleteProductSet`` method. - Attributes: name (str): Required. Resource name of the ProductSet to delete. @@ -443,12 +408,11 @@ class DeleteProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` """ - name = proto.Field(proto.STRING, number=1) + 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 @@ -467,16 +431,13 @@ class CreateReferenceImageRequest(proto.Message): characters long. It cannot contain the character ``/``. """ - parent = proto.Field(proto.STRING, number=1) - + 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) + 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 @@ -495,16 +456,13 @@ class ListReferenceImagesRequest(proto.Message): 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) + 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[google.cloud.vision_v1p3beta1.types.ReferenceImage]): The list of reference images. @@ -523,15 +481,12 @@ def raw_page(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) + 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. @@ -541,12 +496,11 @@ class GetReferenceImageRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. """ - name = proto.Field(proto.STRING, number=1) + 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 @@ -557,12 +511,11 @@ class DeleteReferenceImageRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` """ - name = proto.Field(proto.STRING, number=1) + 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. @@ -577,14 +530,12 @@ class AddProductToProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field(proto.STRING, number=1) - - product = proto.Field(proto.STRING, number=2) + 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. @@ -599,14 +550,12 @@ class RemoveProductFromProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field(proto.STRING, number=1) - - product = proto.Field(proto.STRING, number=2) + 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 @@ -622,16 +571,13 @@ class ListProductsInProductSetRequest(proto.Message): 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) + 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[google.cloud.vision_v1p3beta1.types.Product]): The list of Products. @@ -646,8 +592,7 @@ def raw_page(self): return self products = proto.RepeatedField(proto.MESSAGE, number=1, message="Product",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class ImportProductSetsGcsSource(proto.Message): @@ -718,12 +663,11 @@ class ImportProductSetsGcsSource(proto.Message): polygons. """ - csv_file_uri = proto.Field(proto.STRING, number=1) + csv_file_uri = proto.Field(proto.STRING, number=1,) class ImportProductSetsInputConfig(proto.Message): r"""The input content for the ``ImportProductSets`` method. - Attributes: gcs_source (google.cloud.vision_v1p3beta1.types.ImportProductSetsGcsSource): The Google Cloud Storage location for a csv @@ -738,7 +682,6 @@ class ImportProductSetsInputConfig(proto.Message): class ImportProductSetsRequest(proto.Message): r"""Request message for the ``ImportProductSets`` method. - Attributes: parent (str): Required. The project in which the ProductSets should be @@ -750,8 +693,7 @@ class ImportProductSetsRequest(proto.Message): requests. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) input_config = proto.Field( proto.MESSAGE, number=2, message="ImportProductSetsInputConfig", ) @@ -782,8 +724,7 @@ class ImportProductSetsResponse(proto.Message): reference_images = proto.RepeatedField( proto.MESSAGE, number=1, message="ReferenceImage", ) - - statuses = proto.RepeatedField(proto.MESSAGE, number=2, message=status.Status,) + statuses = proto.RepeatedField(proto.MESSAGE, number=2, message=status_pb2.Status,) class BatchOperationMetadata(proto.Message): @@ -816,10 +757,8 @@ class State(proto.Enum): 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,) + submit_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.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 index 47423028..8c64ea1f 100644 --- a/google/cloud/vision_v1p3beta1/types/text_annotation.py +++ b/google/cloud/vision_v1p3beta1/types/text_annotation.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # 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 @@ -46,7 +43,6 @@ class TextAnnotation(proto.Message): 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 @@ -56,13 +52,11 @@ class DetectedLanguage(proto.Message): Confidence of detected language. Range [0, 1]. """ - language_code = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) + 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_ (google.cloud.vision_v1p3beta1.types.TextAnnotation.DetectedBreak.BreakType): Detected break type. @@ -82,12 +76,10 @@ class BreakType(proto.Enum): type_ = proto.Field( proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", ) - - is_prefix = proto.Field(proto.BOOL, number=2) + is_prefix = proto.Field(proto.BOOL, number=2,) class TextProperty(proto.Message): r"""Additional information detected on the structural component. - Attributes: detected_languages (Sequence[google.cloud.vision_v1p3beta1.types.TextAnnotation.DetectedLanguage]): A list of detected languages together with @@ -99,19 +91,16 @@ class TextProperty(proto.Message): 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) + text = proto.Field(proto.STRING, number=2,) class Page(proto.Message): r"""Detected page from OCR. - Attributes: property (google.cloud.vision_v1p3beta1.types.TextAnnotation.TextProperty): Additional information detected on the page. @@ -131,19 +120,14 @@ class Page(proto.Message): property = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - - width = proto.Field(proto.INT32, number=2) - - height = proto.Field(proto.INT32, number=3) - + 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) + confidence = proto.Field(proto.FLOAT, number=5,) class Block(proto.Message): r"""Logical element on the page. - Attributes: property (google.cloud.vision_v1p3beta1.types.TextAnnotation.TextProperty): Additional information detected for the @@ -195,14 +179,10 @@ class BlockType(proto.Enum): 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) + confidence = proto.Field(proto.FLOAT, number=5,) class Paragraph(proto.Message): @@ -235,17 +215,13 @@ class Paragraph(proto.Message): 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) + confidence = proto.Field(proto.FLOAT, number=4,) class Word(proto.Message): r"""A word representation. - Attributes: property (google.cloud.vision_v1p3beta1.types.TextAnnotation.TextProperty): Additional information detected for the word. @@ -272,17 +248,13 @@ class Word(proto.Message): 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) + confidence = proto.Field(proto.FLOAT, number=4,) class Symbol(proto.Message): r"""A single symbol representation. - Attributes: property (google.cloud.vision_v1p3beta1.types.TextAnnotation.TextProperty): Additional information detected for the @@ -309,12 +281,9 @@ class Symbol(proto.Message): 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) + 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 index 66587d99..608f78aa 100644 --- a/google/cloud/vision_v1p3beta1/types/web_detection.py +++ b/google/cloud/vision_v1p3beta1/types/web_detection.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -25,7 +23,6 @@ class WebDetection(proto.Message): r"""Relevant information for the image from the Internet. - Attributes: web_entities (Sequence[google.cloud.vision_v1p3beta1.types.WebDetection.WebEntity]): Deduced entities from similar images on the @@ -50,7 +47,6 @@ class WebDetection(proto.Message): class WebEntity(proto.Message): r"""Entity deduced from similar images on the Internet. - Attributes: entity_id (str): Opaque entity ID. @@ -63,15 +59,12 @@ class WebEntity(proto.Message): English. """ - entity_id = proto.Field(proto.STRING, number=1) - - score = proto.Field(proto.FLOAT, number=2) - - description = proto.Field(proto.STRING, number=3) + 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. @@ -80,13 +73,11 @@ class WebImage(proto.Message): image. """ - url = proto.Field(proto.STRING, number=1) - - score = proto.Field(proto.FLOAT, number=2) + 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. @@ -107,23 +98,18 @@ class WebPage(proto.Message): crops. """ - url = proto.Field(proto.STRING, number=1) - - score = proto.Field(proto.FLOAT, number=2) - - page_title = proto.Field(proto.STRING, number=3) - + 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. @@ -133,28 +119,22 @@ class WebLabel(proto.Message): http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. """ - label = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + 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,) diff --git a/google/cloud/vision_v1p4beta1/__init__.py b/google/cloud/vision_v1p4beta1/__init__.py index c2b932ed..11d87ea8 100644 --- a/google/cloud/vision_v1p4beta1/__init__.py +++ b/google/cloud/vision_v1p4beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -19,7 +18,10 @@ from google.cloud.vision_helpers import VisionHelpers from .services.image_annotator import ImageAnnotatorClient as IacImageAnnotatorClient +from .services.image_annotator import ImageAnnotatorAsyncClient from .services.product_search import ProductSearchClient +from .services.product_search import ProductSearchAsyncClient + from .types.face import Celebrity from .types.face import FaceRecognitionParams from .types.face import FaceRecognitionResult @@ -58,7 +60,6 @@ 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 @@ -67,6 +68,7 @@ from .types.image_annotator import SafeSearchAnnotation from .types.image_annotator import TextDetectionParams from .types.image_annotator import WebDetectionParams +from .types.image_annotator import Likelihood from .types.product_search import ProductSearchParams from .types.product_search import ProductSearchResults from .types.product_search_service import AddProductToProductSetRequest @@ -116,6 +118,8 @@ class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): __all__ = ( + "ImageAnnotatorAsyncClient", + "ProductSearchAsyncClient", "AddProductToProductSetRequest", "AnnotateFileRequest", "AnnotateFileResponse", @@ -158,6 +162,7 @@ class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): "GetReferenceImageRequest", "Image", "ImageAnnotationContext", + "ImageAnnotatorClient", "ImageContext", "ImageProperties", "ImageSource", @@ -204,5 +209,4 @@ class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient): "WebDetection", "WebDetectionParams", "Word", - "ImageAnnotatorClient", ) diff --git a/google/cloud/vision_v1p4beta1/proto/face.proto b/google/cloud/vision_v1p4beta1/proto/face.proto deleted file mode 100644 index 1786f26f..00000000 --- a/google/cloud/vision_v1p4beta1/proto/face.proto +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.vision.v1p4beta1; - -import "google/api/annotations.proto"; -import "google/cloud/vision/v1p4beta1/geometry.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "CelebrityProto"; -option java_package = "com.google.cloud.vision.v1p4beta1"; -option objc_class_prefix = "GCVN"; - -// Parameters for a celebrity recognition request. -message FaceRecognitionParams { - // 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. - repeated string celebrity_set = 1; -} - -// A Celebrity is a group of Faces with an identity. -message Celebrity { - // The resource name of the preloaded Celebrity. Has the format - // `builtin/{mid}`. - string name = 1; - - // The Celebrity's display name. - string display_name = 2; - - // The Celebrity's description. - string description = 3; -} - -// Information about a face's identity. -message FaceRecognitionResult { - // The [Celebrity][google.cloud.vision.v1p4beta1.Celebrity] that this face was - // matched to. - Celebrity celebrity = 1; - - // Recognition confidence. Range [0, 1]. - float confidence = 2; -} diff --git a/google/cloud/vision_v1p4beta1/proto/geometry.proto b/google/cloud/vision_v1p4beta1/proto/geometry.proto deleted file mode 100644 index 18877188..00000000 --- a/google/cloud/vision_v1p4beta1/proto/geometry.proto +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.vision.v1p4beta1; - -import "google/api/annotations.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "GeometryProto"; -option java_package = "com.google.cloud.vision.v1p4beta1"; -option objc_class_prefix = "GCVN"; - -// A vertex represents a 2D point in the image. -// NOTE: the vertex coordinates are in the same scale as the original image. -message Vertex { - // X coordinate. - int32 x = 1; - - // Y coordinate. - int32 y = 2; -} - -// 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. -message NormalizedVertex { - // X coordinate. - float x = 1; - - // Y coordinate. - float y = 2; -} - -// A bounding polygon for the detected image annotation. -message BoundingPoly { - // The bounding polygon vertices. - repeated Vertex vertices = 1; - - // The bounding polygon normalized vertices. - repeated NormalizedVertex normalized_vertices = 2; -} - -// 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. -message Position { - // X coordinate. - float x = 1; - - // Y coordinate. - float y = 2; - - // Z coordinate (or depth). - float z = 3; -} diff --git a/google/cloud/vision_v1p4beta1/proto/image_annotator.proto b/google/cloud/vision_v1p4beta1/proto/image_annotator.proto deleted file mode 100644 index 07217f39..00000000 --- a/google/cloud/vision_v1p4beta1/proto/image_annotator.proto +++ /dev/null @@ -1,964 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.vision.v1p4beta1; - -import "google/api/annotations.proto"; -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; -import "google/cloud/vision/v1p4beta1/face.proto"; -import "google/cloud/vision/v1p4beta1/geometry.proto"; -import "google/cloud/vision/v1p4beta1/product_search.proto"; -import "google/cloud/vision/v1p4beta1/text_annotation.proto"; -import "google/cloud/vision/v1p4beta1/web_detection.proto"; -import "google/longrunning/operations.proto"; -import "google/protobuf/field_mask.proto"; -import "google/protobuf/timestamp.proto"; -import "google/rpc/status.proto"; -import "google/type/color.proto"; -import "google/type/latlng.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "ImageAnnotatorProto"; -option java_package = "com.google.cloud.vision.v1p4beta1"; -option objc_class_prefix = "GCVN"; - -// 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 ImageAnnotator { - option (google.api.default_host) = "vision.googleapis.com"; - option (google.api.oauth_scopes) = - "https://www.googleapis.com/auth/cloud-platform," - "https://www.googleapis.com/auth/cloud-vision"; - - // Run image detection and annotation for a batch of images. - rpc BatchAnnotateImages(BatchAnnotateImagesRequest) - returns (BatchAnnotateImagesResponse) { - option (google.api.http) = { - post: "/v1p4beta1/images:annotate" - body: "*" - }; - option (google.api.method_signature) = "requests"; - } - - // 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. - rpc BatchAnnotateFiles(BatchAnnotateFilesRequest) - returns (BatchAnnotateFilesResponse) { - option (google.api.http) = { - post: "/v1p4beta1/files:annotate" - body: "*" - }; - option (google.api.method_signature) = "requests"; - } - - // 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. - rpc AsyncBatchAnnotateImages(AsyncBatchAnnotateImagesRequest) - returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v1p4beta1/images:asyncBatchAnnotate" - body: "*" - }; - option (google.api.method_signature) = "requests,output_config"; - option (google.longrunning.operation_info) = { - response_type: "AsyncBatchAnnotateImagesResponse" - metadata_type: "OperationMetadata" - }; - } - - // 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). - rpc AsyncBatchAnnotateFiles(AsyncBatchAnnotateFilesRequest) - returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v1p4beta1/files:asyncBatchAnnotate" - body: "*" - }; - option (google.api.method_signature) = "requests"; - option (google.longrunning.operation_info) = { - response_type: "AsyncBatchAnnotateFilesResponse" - metadata_type: "OperationMetadata" - }; - } -} - -// 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. -message Feature { - // Type of Google Cloud Vision API feature to be extracted. - enum Type { - // Unspecified feature type. - TYPE_UNSPECIFIED = 0; - - // Run face detection. - FACE_DETECTION = 1; - - // Run landmark detection. - LANDMARK_DETECTION = 2; - - // Run logo detection. - LOGO_DETECTION = 3; - - // Run label detection. - LABEL_DETECTION = 4; - - // 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. - TEXT_DETECTION = 5; - - // Run dense text document OCR. Takes precedence when both - // `DOCUMENT_TEXT_DETECTION` and `TEXT_DETECTION` are present. - DOCUMENT_TEXT_DETECTION = 11; - - // Run Safe Search to detect potentially unsafe - // or undesirable content. - SAFE_SEARCH_DETECTION = 6; - - // Compute a set of image properties, such as the - // image's dominant colors. - IMAGE_PROPERTIES = 7; - - // Run crop hints. - CROP_HINTS = 9; - - // Run web detection. - WEB_DETECTION = 10; - - // Run Product Search. - PRODUCT_SEARCH = 12; - - // Run localizer for object detection. - OBJECT_LOCALIZATION = 19; - } - - // The feature type. - Type type = 1; - - // Maximum number of results of this type. Does not apply to - // `TEXT_DETECTION`, `DOCUMENT_TEXT_DETECTION`, or `CROP_HINTS`. - int32 max_results = 2; - - // Model to use for the feature. - // Supported values: "builtin/stable" (the default if unset) and - // "builtin/latest". - string model = 3; -} - -// External image source (Google Cloud Storage or web URL image location). -message ImageSource { - // **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](https://cloud.google.com/storage/docs/reference-uris) for more info. - string gcs_image_uri = 1; - - // 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](https://cloud.google.com/storage/docs/reference-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. - string image_uri = 2; -} - -// Client image to perform Google Cloud Vision API tasks over. -message Image { - // 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. - bytes content = 1; - - // 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. - ImageSource source = 2; -} - -// A bucketized representation of likelihood, which is intended to give clients -// highly stable results across model upgrades. -enum Likelihood { - // Unknown likelihood. - UNKNOWN = 0; - - // It is very unlikely. - VERY_UNLIKELY = 1; - - // It is unlikely. - UNLIKELY = 2; - - // It is possible. - POSSIBLE = 3; - - // It is likely. - LIKELY = 4; - - // It is very likely. - VERY_LIKELY = 5; -} - -// A face annotation object contains the results of face detection. -message FaceAnnotation { - // A face-specific landmark (for example, a face feature). - message Landmark { - // 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. - enum Type { - // Unknown face landmark detected. Should not be filled. - UNKNOWN_LANDMARK = 0; - - // Left eye. - LEFT_EYE = 1; - - // Right eye. - RIGHT_EYE = 2; - - // Left of left eyebrow. - LEFT_OF_LEFT_EYEBROW = 3; - - // Right of left eyebrow. - RIGHT_OF_LEFT_EYEBROW = 4; - - // Left of right eyebrow. - LEFT_OF_RIGHT_EYEBROW = 5; - - // Right of right eyebrow. - RIGHT_OF_RIGHT_EYEBROW = 6; - - // Midpoint between eyes. - MIDPOINT_BETWEEN_EYES = 7; - - // Nose tip. - NOSE_TIP = 8; - - // Upper lip. - UPPER_LIP = 9; - - // Lower lip. - LOWER_LIP = 10; - - // Mouth left. - MOUTH_LEFT = 11; - - // Mouth right. - MOUTH_RIGHT = 12; - - // Mouth center. - MOUTH_CENTER = 13; - - // Nose, bottom right. - NOSE_BOTTOM_RIGHT = 14; - - // Nose, bottom left. - NOSE_BOTTOM_LEFT = 15; - - // Nose, bottom center. - NOSE_BOTTOM_CENTER = 16; - - // Left eye, top boundary. - LEFT_EYE_TOP_BOUNDARY = 17; - - // Left eye, right corner. - LEFT_EYE_RIGHT_CORNER = 18; - - // Left eye, bottom boundary. - LEFT_EYE_BOTTOM_BOUNDARY = 19; - - // Left eye, left corner. - LEFT_EYE_LEFT_CORNER = 20; - - // Right eye, top boundary. - RIGHT_EYE_TOP_BOUNDARY = 21; - - // Right eye, right corner. - RIGHT_EYE_RIGHT_CORNER = 22; - - // Right eye, bottom boundary. - RIGHT_EYE_BOTTOM_BOUNDARY = 23; - - // Right eye, left corner. - RIGHT_EYE_LEFT_CORNER = 24; - - // Left eyebrow, upper midpoint. - LEFT_EYEBROW_UPPER_MIDPOINT = 25; - - // Right eyebrow, upper midpoint. - RIGHT_EYEBROW_UPPER_MIDPOINT = 26; - - // Left ear tragion. - LEFT_EAR_TRAGION = 27; - - // Right ear tragion. - RIGHT_EAR_TRAGION = 28; - - // Left eye pupil. - LEFT_EYE_PUPIL = 29; - - // Right eye pupil. - RIGHT_EYE_PUPIL = 30; - - // Forehead glabella. - FOREHEAD_GLABELLA = 31; - - // Chin gnathion. - CHIN_GNATHION = 32; - - // Chin left gonion. - CHIN_LEFT_GONION = 33; - - // Chin right gonion. - CHIN_RIGHT_GONION = 34; - } - - // Face landmark type. - Type type = 3; - - // Face landmark position. - Position position = 4; - } - - // 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. - BoundingPoly bounding_poly = 1; - - // 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. - BoundingPoly fd_bounding_poly = 2; - - // Detected face landmarks. - repeated Landmark landmarks = 3; - - // 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]. - float roll_angle = 4; - - // 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]. - float pan_angle = 5; - - // Pitch angle, which indicates the upwards/downwards angle that the face is - // pointing relative to the image's horizontal plane. Range [-180,180]. - float tilt_angle = 6; - - // Detection confidence. Range [0, 1]. - float detection_confidence = 7; - - // Face landmarking confidence. Range [0, 1]. - float landmarking_confidence = 8; - - // Joy likelihood. - Likelihood joy_likelihood = 9; - - // Sorrow likelihood. - Likelihood sorrow_likelihood = 10; - - // Anger likelihood. - Likelihood anger_likelihood = 11; - - // Surprise likelihood. - Likelihood surprise_likelihood = 12; - - // Under-exposed likelihood. - Likelihood under_exposed_likelihood = 13; - - // Blurred likelihood. - Likelihood blurred_likelihood = 14; - - // Headwear likelihood. - Likelihood headwear_likelihood = 15; - - // 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. - repeated FaceRecognitionResult recognition_result = 16; -} - -// Detected entity location information. -message LocationInfo { - // lat/long location coordinates. - google.type.LatLng lat_lng = 1; -} - -// A `Property` consists of a user-supplied name/value pair. -message Property { - // Name of the property. - string name = 1; - - // Value of the property. - string value = 2; - - // Value of numeric properties. - uint64 uint64_value = 3; -} - -// Set of detected entity features. -message EntityAnnotation { - // Opaque entity ID. Some IDs may be available in - // [Google Knowledge Graph Search - // API](https://developers.google.com/knowledge-graph/). - string mid = 1; - - // The language code for the locale in which the entity textual - // `description` is expressed. - string locale = 2; - - // Entity textual description, expressed in its `locale` language. - string description = 3; - - // Overall score of the result. Range [0, 1]. - float score = 4; - - // **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]. - float confidence = 5 [deprecated = true]; - - // 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]. - float topicality = 6; - - // Image region to which this entity belongs. Not produced - // for `LABEL_DETECTION` features. - BoundingPoly bounding_poly = 7; - - // 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. - repeated LocationInfo locations = 8; - - // Some entities may have optional user-supplied `Property` (name/value) - // fields, such a score or string that qualifies the entity. - repeated Property properties = 9; -} - -// Set of detected objects with bounding boxes. -message LocalizedObjectAnnotation { - // Object ID that should align with EntityAnnotation mid. - string mid = 1; - - // 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. - string language_code = 2; - - // Object name, expressed in its `language_code` language. - string name = 3; - - // Score of the result. Range [0, 1]. - float score = 4; - - // Image region to which this object belongs. This must be populated. - BoundingPoly bounding_poly = 5; -} - -// Set of features pertaining to the image, computed by computer vision -// methods over safe-search verticals (for example, adult, spoof, medical, -// violence). -message SafeSearchAnnotation { - // Represents the adult content likelihood for the image. Adult content may - // contain elements such as nudity, pornographic images or cartoons, or - // sexual activities. - Likelihood adult = 1; - - // Spoof likelihood. The likelihood that an modification - // was made to the image's canonical version to make it appear - // funny or offensive. - Likelihood spoof = 2; - - // Likelihood that this is a medical image. - Likelihood medical = 3; - - // Likelihood that this image contains violent content. - Likelihood violence = 4; - - // 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. - Likelihood racy = 9; -} - -// Rectangle determined by min and max `LatLng` pairs. -message LatLongRect { - // Min lat/long pair. - google.type.LatLng min_lat_lng = 1; - - // Max lat/long pair. - google.type.LatLng max_lat_lng = 2; -} - -// Color information consists of RGB channels, score, and the fraction of -// the image that the color occupies in the image. -message ColorInfo { - // RGB components of the color. - google.type.Color color = 1; - - // Image-specific score for this color. Value in range [0, 1]. - float score = 2; - - // The fraction of pixels the color occupies in the image. - // Value in range [0, 1]. - float pixel_fraction = 3; -} - -// Set of dominant colors and their corresponding scores. -message DominantColorsAnnotation { - // RGB color values with their score and pixel fraction. - repeated ColorInfo colors = 1; -} - -// Stores image properties, such as dominant colors. -message ImageProperties { - // If present, dominant colors completed successfully. - DominantColorsAnnotation dominant_colors = 1; -} - -// Single crop hint that is used to generate a new crop when serving an image. -message CropHint { - // The bounding polygon for the crop region. The coordinates of the bounding - // box are in the original image's scale. - BoundingPoly bounding_poly = 1; - - // Confidence of this being a salient region. Range [0, 1]. - float confidence = 2; - - // Fraction of importance of this salient region with respect to the original - // image. - float importance_fraction = 3; -} - -// Set of crop hints that are used to generate new crops when serving images. -message CropHintsAnnotation { - // Crop hint results. - repeated CropHint crop_hints = 1; -} - -// Parameters for crop hints annotation request. -message CropHintsParams { - // 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. - repeated float aspect_ratios = 1; -} - -// Parameters for web detection request. -message WebDetectionParams { - // Whether to include results derived from the geo information in the image. - bool include_geo_results = 2; -} - -// Parameters for text detections. This is used to control TEXT_DETECTION and -// DOCUMENT_TEXT_DETECTION features. -message TextDetectionParams { - - // By default, Cloud Vision API only includes confidence score for - // DOCUMENT_TEXT_DETECTION result. Set the flag to true to include confidence - // score for TEXT_DETECTION as well. - bool enable_text_detection_confidence_score = 9; -} - -// Image context and/or feature-specific parameters. -message ImageContext { - // Not used. - LatLongRect lat_long_rect = 1; - - // 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](https://cloud.google.com/vision/docs/languages). - repeated string language_hints = 2; - - // Parameters for crop hints annotation request. - CropHintsParams crop_hints_params = 4; - - // Parameters for face recognition. - FaceRecognitionParams face_recognition_params = 10; - - // Parameters for product search. - ProductSearchParams product_search_params = 5; - - // Parameters for web detection. - WebDetectionParams web_detection_params = 6; - - // Parameters for text detection and document text detection. - TextDetectionParams text_detection_params = 12; -} - -// Request for performing Google Cloud Vision API tasks over a user-provided -// image, with user-requested features, and with context information. -message AnnotateImageRequest { - // The image to be processed. - Image image = 1; - - // Requested features. - repeated Feature features = 2; - - // Additional context that may accompany the image. - ImageContext image_context = 3; -} - -// If an image was produced from a file (e.g. a PDF), this message gives -// information about the source of that image. -message ImageAnnotationContext { - // The URI of the file used to produce the image. - string uri = 1; - - // If the file was a PDF or TIFF, this field gives the page number within - // the file used to produce the image. - int32 page_number = 2; -} - -// Response to an image annotation request. -message AnnotateImageResponse { - // If present, face detection has completed successfully. - repeated FaceAnnotation face_annotations = 1; - - // If present, landmark detection has completed successfully. - repeated EntityAnnotation landmark_annotations = 2; - - // If present, logo detection has completed successfully. - repeated EntityAnnotation logo_annotations = 3; - - // If present, label detection has completed successfully. - repeated EntityAnnotation label_annotations = 4; - - // If present, localized object detection has completed successfully. - // This will be sorted descending by confidence score. - repeated LocalizedObjectAnnotation localized_object_annotations = 22; - - // If present, text (OCR) detection has completed successfully. - repeated EntityAnnotation text_annotations = 5; - - // If present, text (OCR) detection or document (OCR) text detection has - // completed successfully. - // This annotation provides the structural hierarchy for the OCR detected - // text. - TextAnnotation full_text_annotation = 12; - - // If present, safe-search annotation has completed successfully. - SafeSearchAnnotation safe_search_annotation = 6; - - // If present, image properties were extracted successfully. - ImageProperties image_properties_annotation = 8; - - // If present, crop hints have completed successfully. - CropHintsAnnotation crop_hints_annotation = 11; - - // If present, web detection has completed successfully. - WebDetection web_detection = 13; - - // If present, product search has completed successfully. - ProductSearchResults product_search_results = 14; - - // 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. - google.rpc.Status error = 9; - - // If present, contextual information is needed to understand where this image - // comes from. - ImageAnnotationContext context = 21; -} - -// Multiple image annotation requests are batched into a single service call. -message BatchAnnotateImagesRequest { - // Required. Individual image annotation requests for this batch. - repeated AnnotateImageRequest requests = 1 [(google.api.field_behavior) = REQUIRED]; -} - -// Response to a batch image annotation request. -message BatchAnnotateImagesResponse { - // Individual responses to image annotation requests within the batch. - repeated AnnotateImageResponse responses = 1; -} - -// A request to annotate one single file, e.g. a PDF, TIFF or GIF file. -message AnnotateFileRequest { - // Required. Information about the input file. - InputConfig input_config = 1; - - // Required. Requested features. - repeated Feature features = 2; - - // Additional context that may accompany the image(s) in the file. - ImageContext image_context = 3; - - // 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. - repeated int32 pages = 4; -} - -// Response to a single file annotation request. A file may contain one or more -// images, which individually have their own responses. -message AnnotateFileResponse { - // Information about the file for which this response is generated. - InputConfig input_config = 1; - - // Individual responses to images found within the file. This field will be - // empty if the `error` field is set. - repeated AnnotateImageResponse responses = 2; - - // This field gives the total number of pages in the file. - int32 total_pages = 3; - - // If set, represents the error message for the failed request. The - // `responses` field will not be set in this case. - google.rpc.Status error = 4; -} - -// A list of requests to annotate files using the BatchAnnotateFiles API. -message BatchAnnotateFilesRequest { - // Required. The list of file annotation requests. Right now we support only - // one AnnotateFileRequest in BatchAnnotateFilesRequest. - repeated AnnotateFileRequest requests = 1 - [(google.api.field_behavior) = REQUIRED]; -} - -// A list of file annotation responses. -message BatchAnnotateFilesResponse { - // The list of file annotation responses, each response corresponding to each - // AnnotateFileRequest in BatchAnnotateFilesRequest. - repeated AnnotateFileResponse responses = 1; -} - -// An offline file annotation request. -message AsyncAnnotateFileRequest { - // Required. Information about the input file. - InputConfig input_config = 1; - - // Required. Requested features. - repeated Feature features = 2; - - // Additional context that may accompany the image(s) in the file. - ImageContext image_context = 3; - - // Required. The desired output location and metadata (e.g. format). - OutputConfig output_config = 4; -} - -// The response for a single offline file annotation request. -message AsyncAnnotateFileResponse { - // The output location and metadata from AsyncAnnotateFileRequest. - OutputConfig output_config = 1; -} - -// Request for async image annotation for a list of images. -message AsyncBatchAnnotateImagesRequest { - // Required. Individual image annotation requests for this batch. - repeated AnnotateImageRequest requests = 1 - [(google.api.field_behavior) = REQUIRED]; - - // Required. The desired output location and metadata (e.g. format). - OutputConfig output_config = 2 [(google.api.field_behavior) = REQUIRED]; -} - -// Response to an async batch image annotation request. -message AsyncBatchAnnotateImagesResponse { - // The output location and metadata from AsyncBatchAnnotateImagesRequest. - OutputConfig output_config = 1; -} - -// Multiple async file annotation requests are batched into a single service -// call. -message AsyncBatchAnnotateFilesRequest { - // Required. Individual async file annotation requests for this batch. - repeated AsyncAnnotateFileRequest requests = 1 - [(google.api.field_behavior) = REQUIRED]; -} - -// Response to an async batch file annotation request. -message AsyncBatchAnnotateFilesResponse { - // The list of file annotation responses, one for each request in - // AsyncBatchAnnotateFilesRequest. - repeated AsyncAnnotateFileResponse responses = 1; -} - -// The desired input location and metadata. -message InputConfig { - // The Google Cloud Storage location to read the input from. - GcsSource gcs_source = 1; - - // 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. - bytes content = 3; - - // The type of the file. Currently only "application/pdf", "image/tiff" and - // "image/gif" are supported. Wildcards are not supported. - string mime_type = 2; -} - -// The desired output location and metadata. -message OutputConfig { - // The Google Cloud Storage location to write the output(s) to. - GcsDestination gcs_destination = 1; - - // 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. - int32 batch_size = 2; -} - -// The Google Cloud Storage location where the input will be read from. -message GcsSource { - // Google Cloud Storage URI for the input file. This must only be a - // Google Cloud Storage object. Wildcards are not currently supported. - string uri = 1; -} - -// The Google Cloud Storage location where the output will be written to. -message GcsDestination { - // 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. - string uri = 1; -} - -// Contains metadata for the BatchAnnotateImages operation. -message OperationMetadata { - // Batch operation states. - enum State { - // Invalid. - STATE_UNSPECIFIED = 0; - - // Request is received. - CREATED = 1; - - // Request is actively being processed. - RUNNING = 2; - - // The batch processing is done. - DONE = 3; - - // The batch processing was cancelled. - CANCELLED = 4; - } - - // Current state of the batch operation. - State state = 1; - - // The time when the batch request was received. - google.protobuf.Timestamp create_time = 5; - - // The time when the operation result was last updated. - google.protobuf.Timestamp update_time = 6; -} diff --git a/google/cloud/vision_v1p4beta1/proto/product_search.proto b/google/cloud/vision_v1p4beta1/proto/product_search.proto deleted file mode 100644 index 15baed1f..00000000 --- a/google/cloud/vision_v1p4beta1/proto/product_search.proto +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.vision.v1p4beta1; - -import "google/api/annotations.proto"; -import "google/api/resource.proto"; -import "google/cloud/vision/v1p4beta1/geometry.proto"; -import "google/cloud/vision/v1p4beta1/product_search_service.proto"; -import "google/protobuf/timestamp.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "ProductSearchProto"; -option java_package = "com.google.cloud.vision.v1p4beta1"; -option objc_class_prefix = "GCVN"; - -// Parameters for a product search request. -message ProductSearchParams { - // The bounding polygon around the area of interest in the image. - // If it is not specified, system discretion will be applied. - BoundingPoly bounding_poly = 9; - - // 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`. - string product_set = 6 [(google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - }]; - - // 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. - 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. 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 '='. - string filter = 8; -} - -// Results for a product search request. -message ProductSearchResults { - // 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). - float score = 2; - - // The resource name of the image from the product that is the closest match - // to the query. - string image = 3; - } - - // Prediction for what the object in the bounding box is. - message ObjectAnnotation { - // Object ID that should align with EntityAnnotation mid. - string mid = 1; - - // 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. - string language_code = 2; - - // Object name, expressed in its `language_code` language. - string name = 3; - - // Score of the result. Range [0, 1]. - float score = 4; - } - - // Information about the products similar to a single product in a query - // image. - message GroupedResult { - // The bounding polygon around the product detected in the query image. - BoundingPoly bounding_poly = 1; - - // List of results, one for each product match. - repeated Result results = 2; - - // List of generic predictions for the object in the bounding box. - repeated ObjectAnnotation object_annotations = 3; - } - - // 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. - google.protobuf.Timestamp index_time = 2; - - // List of results, one for each product match. - repeated Result results = 5; - - // 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. - repeated GroupedResult product_grouped_results = 6; -} diff --git a/google/cloud/vision_v1p4beta1/proto/product_search_service.proto b/google/cloud/vision_v1p4beta1/proto/product_search_service.proto deleted file mode 100644 index df7bc7a3..00000000 --- a/google/cloud/vision_v1p4beta1/proto/product_search_service.proto +++ /dev/null @@ -1,1039 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.vision.v1p4beta1; - -import "google/api/annotations.proto"; -import "google/api/client.proto"; -import "google/api/field_behavior.proto"; -import "google/api/resource.proto"; -import "google/cloud/vision/v1p4beta1/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/v1p4beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "ProductSearchServiceProto"; -option java_package = "com.google.cloud.vision.v1p4beta1"; -option objc_class_prefix = "GCVN"; - -// 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/*` -service ProductSearch { - option (google.api.default_host) = "vision.googleapis.com"; - option (google.api.oauth_scopes) = - "https://www.googleapis.com/auth/cloud-platform," - "https://www.googleapis.com/auth/cloud-vision"; - - // 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: "/v1p4beta1/{parent=projects/*/locations/*}/productSets" - body: "product_set" - }; - option (google.api.method_signature) = "parent,product_set,product_set_id"; - } - - // 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: "/v1p4beta1/{parent=projects/*/locations/*}/productSets" - }; - option (google.api.method_signature) = "parent"; - } - - // 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: "/v1p4beta1/{name=projects/*/locations/*/productSets/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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: "/v1p4beta1/{product_set.name=projects/*/locations/*/productSets/*}" - body: "product_set" - }; - option (google.api.method_signature) = "product_set,update_mask"; - } - - // Permanently deletes a ProductSet. Products and ReferenceImages in the - // ProductSet are not deleted. - // - // The actual image files are not deleted from Google Cloud Storage. - rpc DeleteProductSet(DeleteProductSetRequest) - returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v1p4beta1/{name=projects/*/locations/*/productSets/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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: "/v1p4beta1/{parent=projects/*/locations/*}/products" - body: "product" - }; - option (google.api.method_signature) = "parent,product,product_id"; - } - - // 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: "/v1p4beta1/{parent=projects/*/locations/*}/products" - }; - option (google.api.method_signature) = "parent"; - } - - // 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: "/v1p4beta1/{name=projects/*/locations/*/products/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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. - rpc UpdateProduct(UpdateProductRequest) returns (Product) { - option (google.api.http) = { - patch: "/v1p4beta1/{product.name=projects/*/locations/*/products/*}" - body: "product" - }; - option (google.api.method_signature) = "product,update_mask"; - } - - // 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. - rpc DeleteProduct(DeleteProductRequest) returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v1p4beta1/{name=projects/*/locations/*/products/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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: "/v1p4beta1/{parent=projects/*/locations/*/products/*}/referenceImages" - body: "reference_image" - }; - option (google.api.method_signature) = - "parent,reference_image,reference_image_id"; - } - - // 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. - rpc DeleteReferenceImage(DeleteReferenceImageRequest) - returns (google.protobuf.Empty) { - option (google.api.http) = { - delete: "/v1p4beta1/{name=projects/*/locations/*/products/*/referenceImages/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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: "/v1p4beta1/{parent=projects/*/locations/*/products/*}/referenceImages" - }; - option (google.api.method_signature) = "parent"; - } - - // 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: "/v1p4beta1/{name=projects/*/locations/*/products/*/referenceImages/*}" - }; - option (google.api.method_signature) = "name"; - } - - // 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: "/v1p4beta1/{name=projects/*/locations/*/productSets/*}:addProduct" - body: "*" - }; - option (google.api.method_signature) = "name,product"; - } - - // Removes a Product from the specified ProductSet. - rpc RemoveProductFromProductSet(RemoveProductFromProductSetRequest) - returns (google.protobuf.Empty) { - option (google.api.http) = { - post: "/v1p4beta1/{name=projects/*/locations/*/productSets/*}:removeProduct" - body: "*" - }; - option (google.api.method_signature) = "name,product"; - } - - // 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: "/v1p4beta1/{name=projects/*/locations/*/productSets/*}/products" - }; - option (google.api.method_signature) = "name"; - } - - // 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]. - rpc ImportProductSets(ImportProductSetsRequest) - returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v1p4beta1/{parent=projects/*/locations/*}/productSets:import" - body: "*" - }; - option (google.api.method_signature) = "parent,input_config"; - option (google.longrunning.operation_info) = { - response_type: "ImportProductSetsResponse" - metadata_type: "BatchOperationMetadata" - }; - } - - // 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) - rpc PurgeProducts(PurgeProductsRequest) - returns (google.longrunning.Operation) { - option (google.api.http) = { - post: "/v1p4beta1/{parent=projects/*/locations/*}/products:purge" - body: "*" - }; - option (google.api.method_signature) = "parent"; - option (google.longrunning.operation_info) = { - response_type: "google.protobuf.Empty" - metadata_type: "BatchOperationMetadata" - }; - } -} - -// A Product contains ReferenceImages. -message Product { - option (google.api.resource) = { - type: "vision.googleapis.com/Product" - pattern: "projects/{project}/locations/{location}/products/{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; - - // 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. - string product_category = 4 [(google.api.field_behavior) = IMMUTABLE]; - - // 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. - 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 { - option (google.api.resource) = { - type: "vision.googleapis.com/ProductSet" - pattern: "projects/{project}/locations/{location}/productSets/{product_set}" - }; - - // 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 timestamp is the default value - // "1970-01-01T00:00:00Z". - // - // This field is ignored when creating a ProductSet. - google.protobuf.Timestamp index_time = 3 - [(google.api.field_behavior) = OUTPUT_ONLY]; - - // 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 [(google.api.field_behavior) = OUTPUT_ONLY]; -} - -// A `ReferenceImage` represents a product image and its associated metadata, -// such as bounding boxes. -message ReferenceImage { - option (google.api.resource) = { - type: "vision.googleapis.com/ReferenceImage" - pattern: "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}" - }; - - // 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; - - // Required. The Google Cloud Storage URI of the reference image. - // - // The URI must start with `gs://`. - string uri = 2 [(google.api.field_behavior) = REQUIRED]; - - // 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). - repeated BoundingPoly bounding_polys = 3 - [(google.api.field_behavior) = OPTIONAL]; -} - -// Request message for the `CreateProduct` method. -message CreateProductRequest { - // Required. The project in which the Product should be created. - // - // Format is - // `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Required. The product to create. - Product product = 2 [(google.api.field_behavior) = REQUIRED]; - - // 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 { - // Required. The project OR ProductSet from which Products should be listed. - // - // Format: - // `projects/PROJECT_ID/locations/LOC_ID` - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // 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 { - // Required. Resource name of the Product to get. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { type: "vision.googleapis.com/Product" } - ]; -} - -// Request message for the `UpdateProduct` method. -message UpdateProductRequest { - // Required. The Product resource which replaces the one on the server. - // product.name is immutable. - Product product = 1 [(google.api.field_behavior) = REQUIRED]; - - // 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 { - // Required. Resource name of product to delete. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { type: "vision.googleapis.com/Product" } - ]; -} - -// Request message for the `CreateProductSet` method. -message CreateProductSetRequest { - // Required. The project in which the ProductSet should be created. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Required. The ProductSet to create. - ProductSet product_set = 2 [(google.api.field_behavior) = REQUIRED]; - - // 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 { - // Required. The project from which ProductSets should be listed. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // 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 { - // Required. Resource name of the ProductSet to get. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - } - ]; -} - -// Request message for the `UpdateProductSet` method. -message UpdateProductSetRequest { - // Required. The ProductSet resource which replaces the one on the server. - ProductSet product_set = 1 [(google.api.field_behavior) = REQUIRED]; - - // 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 { - // Required. Resource name of the ProductSet to delete. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - } - ]; -} - -// Request message for the `CreateReferenceImage` method. -message CreateReferenceImageRequest { - // Required. 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 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { type: "vision.googleapis.com/Product" } - ]; - - // Required. The reference image to create. - // If an image ID is specified, it is ignored. - ReferenceImage reference_image = 2 [(google.api.field_behavior) = REQUIRED]; - - // 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 { - // Required. Resource name of the product containing the reference images. - // - // Format is - // `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { type: "vision.googleapis.com/Product" } - ]; - - // 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 { - // Required. 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 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ReferenceImage" - } - ]; -} - -// Request message for the `DeleteReferenceImage` method. -message DeleteReferenceImageRequest { - // Required. 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 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ReferenceImage" - } - ]; -} - -// Request message for the `AddProductToProductSet` method. -message AddProductToProductSetRequest { - // Required. The resource name for the ProductSet to modify. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - } - ]; - - // Required. 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 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { type: "vision.googleapis.com/Product" } - ]; -} - -// Request message for the `RemoveProductFromProductSet` method. -message RemoveProductFromProductSetRequest { - // Required. The resource name for the ProductSet to modify. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - } - ]; - - // Required. 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 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { type: "vision.googleapis.com/Product" } - ]; -} - -// Request message for the `ListProductsInProductSet` method. -message ListProductsInProductSetRequest { - // Required. The ProductSet resource for which to retrieve Products. - // - // Format is: - // `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID` - string name = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "vision.googleapis.com/ProductSet" - } - ]; - - // 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 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). - 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 { - // Required. The project in which the ProductSets should be imported. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // Required. The input content for the list of requests. - ImportProductSetsInputConfig input_config = 2 - [(google.api.field_behavior) = REQUIRED]; -} - -// 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; -} - -// Config to control which ProductSet contains the Products to be deleted. -message ProductSetPurgeConfig { - // 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. - string product_set_id = 1; -} - -// Request message for the `PurgeProducts` method. -message PurgeProductsRequest { - // The Products to delete. - oneof target { - // Specify which ProductSet contains the Products to be deleted. - ProductSetPurgeConfig product_set_purge_config = 2; - - // If delete_orphan_products is true, all Products that are not in any - // ProductSet will be deleted. - bool delete_orphan_products = 3; - } - - // Required. The project and location in which the Products should be deleted. - // - // Format is `projects/PROJECT_ID/locations/LOC_ID`. - string parent = 1 [ - (google.api.field_behavior) = REQUIRED, - (google.api.resource_reference) = { - type: "locations.googleapis.com/Location" - } - ]; - - // The default value is false. Override this value to true to actually perform - // the purge. - bool force = 4; -} diff --git a/google/cloud/vision_v1p4beta1/proto/text_annotation.proto b/google/cloud/vision_v1p4beta1/proto/text_annotation.proto deleted file mode 100644 index fbc35bb5..00000000 --- a/google/cloud/vision_v1p4beta1/proto/text_annotation.proto +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.vision.v1p4beta1; - -import "google/api/annotations.proto"; -import "google/cloud/vision/v1p4beta1/geometry.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "TextAnnotationProto"; -option java_package = "com.google.cloud.vision.v1p4beta1"; -option objc_class_prefix = "GCVN"; - -// 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. -message TextAnnotation { - // Detected language for a structural component. - message DetectedLanguage { - // 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. - string language_code = 1; - - // Confidence of detected language. Range [0, 1]. - float confidence = 2; - } - - // Detected start or end of a structural component. - message DetectedBreak { - // Enum to denote the type of break found. New line, space etc. - enum BreakType { - // Unknown break label type. - UNKNOWN = 0; - - // Regular space. - SPACE = 1; - - // Sure space (very wide). - SURE_SPACE = 2; - - // Line-wrapping break. - EOL_SURE_SPACE = 3; - - // End-line hyphen that is not present in text; does not co-occur with - // `SPACE`, `LEADER_SPACE`, or `LINE_BREAK`. - HYPHEN = 4; - - // Line break that ends a paragraph. - LINE_BREAK = 5; - } - - // Detected break type. - BreakType type = 1; - - // True if break prepends the element. - bool is_prefix = 2; - } - - // Additional information detected on the structural component. - message TextProperty { - // A list of detected languages together with confidence. - repeated DetectedLanguage detected_languages = 1; - - // Detected start or end of a text segment. - DetectedBreak detected_break = 2; - } - - // List of pages detected by OCR. - repeated Page pages = 1; - - // UTF-8 text detected on the pages. - string text = 2; -} - -// Detected page from OCR. -message Page { - // Additional information detected on the page. - TextAnnotation.TextProperty property = 1; - - // Page width. For PDFs the unit is points. For images (including - // TIFFs) the unit is pixels. - int32 width = 2; - - // Page height. For PDFs the unit is points. For images (including - // TIFFs) the unit is pixels. - int32 height = 3; - - // List of blocks of text, images etc on this page. - repeated Block blocks = 4; - - // Confidence of the OCR results on the page. Range [0, 1]. - float confidence = 5; -} - -// Logical element on the page. -message Block { - // Type of a block (text, image etc) as identified by OCR. - enum BlockType { - // Unknown block type. - UNKNOWN = 0; - - // Regular text block. - TEXT = 1; - - // Table block. - TABLE = 2; - - // Image block. - PICTURE = 3; - - // Horizontal/vertical line box. - RULER = 4; - - // Barcode block. - BARCODE = 5; - } - - // Additional information detected for the block. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // List of paragraphs in this block (if this blocks is of type text). - repeated Paragraph paragraphs = 3; - - // Detected block type (text, image etc) for this block. - BlockType block_type = 4; - - // Confidence of the OCR results on the block. Range [0, 1]. - float confidence = 5; -} - -// Structural unit of text representing a number of words in certain order. -message Paragraph { - // Additional information detected for the paragraph. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // List of all words in this paragraph. - repeated Word words = 3; - - // Confidence of the OCR results for the paragraph. Range [0, 1]. - float confidence = 4; -} - -// A word representation. -message Word { - // Additional information detected for the word. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // List of symbols in the word. - // The order of the symbols follows the natural reading order. - repeated Symbol symbols = 3; - - // Confidence of the OCR results for the word. Range [0, 1]. - float confidence = 4; -} - -// A single symbol representation. -message Symbol { - // Additional information detected for the symbol. - TextAnnotation.TextProperty property = 1; - - // 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). - BoundingPoly bounding_box = 2; - - // The actual UTF-8 representation of the symbol. - string text = 3; - - // Confidence of the OCR results for the symbol. Range [0, 1]. - float confidence = 4; -} diff --git a/google/cloud/vision_v1p4beta1/proto/web_detection.proto b/google/cloud/vision_v1p4beta1/proto/web_detection.proto deleted file mode 100644 index 446a937f..00000000 --- a/google/cloud/vision_v1p4beta1/proto/web_detection.proto +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2019 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. -// - -syntax = "proto3"; - -package google.cloud.vision.v1p4beta1; - -import "google/api/annotations.proto"; - -option cc_enable_arenas = true; -option go_package = "google.golang.org/genproto/googleapis/cloud/vision/v1p4beta1;vision"; -option java_multiple_files = true; -option java_outer_classname = "WebDetectionProto"; -option java_package = "com.google.cloud.vision.v1p4beta1"; -option objc_class_prefix = "GCVN"; - -// Relevant information for the image from the Internet. -message WebDetection { - // Entity deduced from similar images on the Internet. - message WebEntity { - // Opaque entity ID. - string entity_id = 1; - - // Overall relevancy score for the entity. - // Not normalized and not comparable across different image queries. - float score = 2; - - // Canonical description of the entity, in English. - string description = 3; - } - - // Metadata for online images. - message WebImage { - // The result image URL. - string url = 1; - - // (Deprecated) Overall relevancy score for the image. - float score = 2; - } - - // Metadata for web pages. - message WebPage { - // The result web page URL. - string url = 1; - - // (Deprecated) Overall relevancy score for the web page. - float score = 2; - - // Title for the web page, may contain HTML markups. - string page_title = 3; - - // Fully matching images on the page. - // Can include resized copies of the query image. - repeated WebImage full_matching_images = 4; - - // 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. - repeated WebImage partial_matching_images = 5; - } - - // Label to provide extra metadata for the web detection. - message WebLabel { - // Label for extra metadata. - string label = 1; - - // 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. - string language_code = 2; - } - - // Deduced entities from similar images on the Internet. - repeated WebEntity web_entities = 1; - - // Fully matching images from the Internet. - // Can include resized copies of the query image. - repeated WebImage full_matching_images = 2; - - // 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. - repeated WebImage partial_matching_images = 3; - - // Web pages containing the matching images from the Internet. - repeated WebPage pages_with_matching_images = 4; - - // The visually similar image results. - repeated WebImage visually_similar_images = 6; - - // The service's best guess as to the topic of the request image. - // Inferred from similar images on the open web. - repeated WebLabel best_guess_labels = 8; -} diff --git a/google/cloud/vision_v1p4beta1/services/__init__.py b/google/cloud/vision_v1p4beta1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/vision_v1p4beta1/services/__init__.py +++ b/google/cloud/vision_v1p4beta1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/__init__.py b/google/cloud/vision_v1p4beta1/services/image_annotator/__init__.py index 2b601881..422732ba 100644 --- a/google/cloud/vision_v1p4beta1/services/image_annotator/__init__.py +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ImageAnnotatorClient from .async_client import 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 index 44907205..37e9e7cd 100644 --- a/google/cloud/vision_v1p4beta1/services/image_annotator/async_client.py +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,16 +20,15 @@ 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 exceptions as core_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 import credentials as ga_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 @@ -53,31 +50,26 @@ class ImageAnnotatorAsyncClient: parse_product_path = staticmethod(ImageAnnotatorClient.parse_product_path) product_set_path = staticmethod(ImageAnnotatorClient.product_set_path) parse_product_set_path = staticmethod(ImageAnnotatorClient.parse_product_set_path) - common_billing_account_path = staticmethod( ImageAnnotatorClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ImageAnnotatorClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ImageAnnotatorClient.common_folder_path) parse_common_folder_path = staticmethod( ImageAnnotatorClient.parse_common_folder_path ) - common_organization_path = staticmethod( ImageAnnotatorClient.common_organization_path ) parse_common_organization_path = staticmethod( ImageAnnotatorClient.parse_common_organization_path ) - common_project_path = staticmethod(ImageAnnotatorClient.common_project_path) parse_common_project_path = staticmethod( ImageAnnotatorClient.parse_common_project_path ) - common_location_path = staticmethod(ImageAnnotatorClient.common_location_path) parse_common_location_path = staticmethod( ImageAnnotatorClient.parse_common_location_path @@ -85,7 +77,8 @@ class ImageAnnotatorAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -100,7 +93,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -117,7 +110,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ImageAnnotatorTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ImageAnnotatorTransport: The transport used by the client instance. @@ -131,12 +124,12 @@ def transport(self) -> ImageAnnotatorTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_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. + """Instantiates the image annotator client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -168,7 +161,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ImageAnnotatorClient( credentials=credentials, transport=transport, @@ -199,7 +191,6 @@ async def batch_annotate_images( 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. @@ -226,7 +217,6 @@ async def batch_annotate_images( # If we have keyword arguments corresponding to fields on the # request, apply these. - if requests: request.requests.extend(requests) @@ -282,7 +272,6 @@ async def batch_annotate_files( 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. @@ -307,7 +296,6 @@ async def batch_annotate_files( # If we have keyword arguments corresponding to fields on the # request, apply these. - if requests: request.requests.extend(requests) @@ -373,7 +361,6 @@ async def async_batch_annotate_images( 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. @@ -403,10 +390,8 @@ async def async_batch_annotate_images( # If we have keyword arguments corresponding to fields on the # request, apply these. - if output_config is not None: request.output_config = output_config - if requests: request.requests.extend(requests) @@ -467,7 +452,6 @@ async def async_batch_annotate_files( 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. @@ -497,7 +481,6 @@ async def async_batch_annotate_files( # If we have keyword arguments corresponding to fields on the # request, apply these. - if requests: request.requests.extend(requests) diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/client.py b/google/cloud/vision_v1p4beta1/services/image_annotator/client.py index 340a462f..215eca07 100644 --- a/google/cloud/vision_v1p4beta1/services/image_annotator/client.py +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ 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 exceptions as core_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 import credentials as ga_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 @@ -35,7 +33,6 @@ 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 @@ -56,7 +53,7 @@ class ImageAnnotatorClientMeta(type): _transport_registry["grpc_asyncio"] = ImageAnnotatorGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ImageAnnotatorTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -83,7 +80,8 @@ class ImageAnnotatorClient(metaclass=ImageAnnotatorClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -117,7 +115,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -134,7 +133,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -153,23 +152,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ImageAnnotatorTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ImageAnnotatorTransport: The transport used by the client instance. + ImageAnnotatorTransport: The transport used by the client + instance. """ return self._transport @staticmethod def product_path(project: str, location: str, product: str,) -> str: - """Return a fully-qualified product string.""" + """Returns 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.""" + """Parses a product path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", path, @@ -178,14 +178,14 @@ def parse_product_path(path: str) -> Dict[str, str]: @staticmethod def product_set_path(project: str, location: str, product_set: str,) -> str: - """Return a fully-qualified product_set string.""" + """Returns 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.""" + """Parses a product_set path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", path, @@ -194,7 +194,7 @@ def parse_product_set_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -207,7 +207,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -218,7 +218,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -229,7 +229,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -240,7 +240,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -254,12 +254,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_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. + """Instantiates the image annotator client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -314,9 +314,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -328,12 +329,14 @@ def __init__( 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 - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -348,8 +351,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -387,7 +390,6 @@ def batch_annotate_images( 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. @@ -419,10 +421,8 @@ def batch_annotate_images( 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 @@ -467,7 +467,6 @@ def batch_annotate_files( 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. @@ -497,10 +496,8 @@ def batch_annotate_files( 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 @@ -555,7 +552,6 @@ def async_batch_annotate_images( 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. @@ -590,10 +586,8 @@ def async_batch_annotate_images( 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: @@ -647,7 +641,6 @@ def async_batch_annotate_files( 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. @@ -682,10 +675,8 @@ def async_batch_annotate_files( 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 diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/__init__.py b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/__init__.py index e2a0c3ea..419b4293 100644 --- a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/__init__.py +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py index 00cbd367..3607c6ec 100644 --- a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_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.auth import credentials as ga_credentials # type: ignore from google.cloud.vision_v1p4beta1.types import image_annotator -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -37,6 +36,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ImageAnnotatorTransport(abc.ABC): """Abstract transport class for ImageAnnotator.""" @@ -46,21 +56,24 @@ class ImageAnnotatorTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-vision", ) + DEFAULT_HOST: str = "vision.googleapis.com" + 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, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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. + 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 @@ -69,7 +82,7 @@ def __init__( 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. + scopes (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): @@ -83,29 +96,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -167,11 +227,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def batch_annotate_images( self, - ) -> typing.Callable[ + ) -> Callable[ [image_annotator.BatchAnnotateImagesRequest], - typing.Union[ + Union[ image_annotator.BatchAnnotateImagesResponse, - typing.Awaitable[image_annotator.BatchAnnotateImagesResponse], + Awaitable[image_annotator.BatchAnnotateImagesResponse], ], ]: raise NotImplementedError() @@ -179,11 +239,11 @@ def batch_annotate_images( @property def batch_annotate_files( self, - ) -> typing.Callable[ + ) -> Callable[ [image_annotator.BatchAnnotateFilesRequest], - typing.Union[ + Union[ image_annotator.BatchAnnotateFilesResponse, - typing.Awaitable[image_annotator.BatchAnnotateFilesResponse], + Awaitable[image_annotator.BatchAnnotateFilesResponse], ], ]: raise NotImplementedError() @@ -191,18 +251,18 @@ def batch_annotate_files( @property def async_batch_annotate_images( self, - ) -> typing.Callable[ + ) -> Callable[ [image_annotator.AsyncBatchAnnotateImagesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def async_batch_annotate_files( self, - ) -> typing.Callable[ + ) -> Callable[ [image_annotator.AsyncBatchAnnotateFilesRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py index e31b0cf1..dac4f91d 100644 --- a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # 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 typing import Callable, Dict, Optional, Sequence, Tuple, Union 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 +import google.auth # type: ignore +from google.auth import credentials as ga_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 google.longrunning import operations_pb2 # type: ignore from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO @@ -55,7 +52,7 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -69,7 +66,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -180,7 +178,7 @@ def __init__( def create_channel( cls, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -211,13 +209,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -311,7 +311,7 @@ def batch_annotate_files( def async_batch_annotate_images( self, ) -> Callable[ - [image_annotator.AsyncBatchAnnotateImagesRequest], operations.Operation + [image_annotator.AsyncBatchAnnotateImagesRequest], operations_pb2.Operation ]: r"""Return a callable for the async batch annotate images method over gRPC. @@ -342,7 +342,7 @@ def async_batch_annotate_images( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["async_batch_annotate_images"] @@ -350,7 +350,7 @@ def async_batch_annotate_images( def async_batch_annotate_files( self, ) -> Callable[ - [image_annotator.AsyncBatchAnnotateFilesRequest], operations.Operation + [image_annotator.AsyncBatchAnnotateFilesRequest], operations_pb2.Operation ]: r"""Return a callable for the async batch annotate files method over gRPC. @@ -376,7 +376,7 @@ def async_batch_annotate_files( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["async_batch_annotate_files"] 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 index 2febab6d..e42a0357 100644 --- a/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc_asyncio.py +++ b/google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union 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 import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version 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 google.longrunning import operations_pb2 # type: ignore from .base import ImageAnnotatorTransport, DEFAULT_CLIENT_INFO from .grpc import ImageAnnotatorGrpcTransport @@ -58,7 +55,7 @@ class ImageAnnotatorGrpcAsyncIOTransport(ImageAnnotatorTransport): def create_channel( cls, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -85,13 +82,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -99,7 +98,7 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -113,7 +112,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -172,7 +172,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -318,7 +317,7 @@ def async_batch_annotate_images( self, ) -> Callable[ [image_annotator.AsyncBatchAnnotateImagesRequest], - Awaitable[operations.Operation], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the async batch annotate images method over gRPC. @@ -349,7 +348,7 @@ def async_batch_annotate_images( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["async_batch_annotate_images"] @@ -358,7 +357,7 @@ def async_batch_annotate_files( self, ) -> Callable[ [image_annotator.AsyncBatchAnnotateFilesRequest], - Awaitable[operations.Operation], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the async batch annotate files method over gRPC. @@ -384,7 +383,7 @@ def async_batch_annotate_files( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["async_batch_annotate_files"] diff --git a/google/cloud/vision_v1p4beta1/services/product_search/__init__.py b/google/cloud/vision_v1p4beta1/services/product_search/__init__.py index e82b5909..f357996e 100644 --- a/google/cloud/vision_v1p4beta1/services/product_search/__init__.py +++ b/google/cloud/vision_v1p4beta1/services/product_search/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import ProductSearchClient from .async_client import 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 index f6e10a3c..2115e0e1 100644 --- a/google/cloud/vision_v1p4beta1/services/product_search/async_client.py +++ b/google/cloud/vision_v1p4beta1/services/product_search/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ 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 exceptions as core_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 import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -33,11 +31,10 @@ 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 google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport from .client import ProductSearchClient @@ -79,31 +76,26 @@ class ProductSearchAsyncClient: parse_reference_image_path = staticmethod( ProductSearchClient.parse_reference_image_path ) - common_billing_account_path = staticmethod( ProductSearchClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( ProductSearchClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(ProductSearchClient.common_folder_path) parse_common_folder_path = staticmethod( ProductSearchClient.parse_common_folder_path ) - common_organization_path = staticmethod( ProductSearchClient.common_organization_path ) parse_common_organization_path = staticmethod( ProductSearchClient.parse_common_organization_path ) - common_project_path = staticmethod(ProductSearchClient.common_project_path) parse_common_project_path = staticmethod( ProductSearchClient.parse_common_project_path ) - common_location_path = staticmethod(ProductSearchClient.common_location_path) parse_common_location_path = staticmethod( ProductSearchClient.parse_common_location_path @@ -111,7 +103,8 @@ class ProductSearchAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +119,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -143,7 +136,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ProductSearchTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: ProductSearchTransport: The transport used by the client instance. @@ -157,12 +150,12 @@ def transport(self) -> ProductSearchTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_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. + """Instantiates the product search client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -194,7 +187,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = ProductSearchClient( credentials=credentials, transport=transport, @@ -248,7 +240,6 @@ async def create_product_set( 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. @@ -278,7 +269,6 @@ async def create_product_set( # 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: @@ -342,7 +332,6 @@ async def list_product_sets( 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. @@ -371,7 +360,6 @@ async def list_product_sets( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -384,7 +372,8 @@ async def list_product_sets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -438,7 +427,6 @@ async def get_product_set( 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. @@ -468,7 +456,6 @@ async def get_product_set( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -481,7 +468,8 @@ async def get_product_set( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -506,7 +494,7 @@ async def update_product_set( request: product_search_service.UpdateProductSetRequest = None, *, product_set: product_search_service.ProductSet = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -541,7 +529,6 @@ async def update_product_set( 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. @@ -571,7 +558,6 @@ async def update_product_set( # 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: @@ -633,7 +619,6 @@ async def delete_product_set( 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. @@ -654,7 +639,6 @@ async def delete_product_set( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -667,7 +651,8 @@ async def delete_product_set( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -736,7 +721,6 @@ async def create_product( 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. @@ -761,7 +745,6 @@ async def create_product( # 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: @@ -825,7 +808,6 @@ async def list_products( 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. @@ -854,7 +836,6 @@ async def list_products( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -867,7 +848,8 @@ async def list_products( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -921,7 +903,6 @@ async def get_product( 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. @@ -946,7 +927,6 @@ async def get_product( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -959,7 +939,8 @@ async def get_product( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -984,7 +965,7 @@ async def update_product( request: product_search_service.UpdateProductRequest = None, *, product: product_search_service.Product = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1028,7 +1009,6 @@ async def update_product( 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. @@ -1053,7 +1033,6 @@ async def update_product( # 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: @@ -1117,7 +1096,6 @@ async def delete_product( 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. @@ -1138,7 +1116,6 @@ async def delete_product( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1151,7 +1128,8 @@ async def delete_product( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1236,7 +1214,6 @@ async def create_reference_image( 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. @@ -1263,7 +1240,6 @@ async def create_reference_image( # 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: @@ -1330,7 +1306,6 @@ async def delete_reference_image( 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. @@ -1351,7 +1326,6 @@ async def delete_reference_image( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1364,7 +1338,8 @@ async def delete_reference_image( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1414,7 +1389,6 @@ async def list_reference_images( 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. @@ -1443,7 +1417,6 @@ async def list_reference_images( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -1456,7 +1429,8 @@ async def list_reference_images( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1512,7 +1486,6 @@ async def get_reference_image( 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. @@ -1539,7 +1512,6 @@ async def get_reference_image( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1552,7 +1524,8 @@ async def get_reference_image( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1616,7 +1589,6 @@ async def add_product_to_product_set( 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. @@ -1637,7 +1609,6 @@ async def add_product_to_product_set( # 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: @@ -1705,7 +1676,6 @@ async def remove_product_from_product_set( 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. @@ -1726,7 +1696,6 @@ async def remove_product_from_product_set( # 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: @@ -1790,7 +1759,6 @@ async def list_products_in_product_set( 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. @@ -1820,7 +1788,6 @@ async def list_products_in_product_set( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -1833,7 +1800,8 @@ async def list_products_in_product_set( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -1902,7 +1870,6 @@ async def import_product_sets( 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. @@ -1938,7 +1905,6 @@ async def import_product_sets( # 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: @@ -2029,7 +1995,6 @@ async def purge_products( 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. @@ -2069,7 +2034,6 @@ async def purge_products( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -2094,7 +2058,7 @@ async def purge_products( response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=product_search_service.BatchOperationMetadata, ) diff --git a/google/cloud/vision_v1p4beta1/services/product_search/client.py b/google/cloud/vision_v1p4beta1/services/product_search/client.py index 485d3ebd..c4bbf7f7 100644 --- a/google/cloud/vision_v1p4beta1/services/product_search/client.py +++ b/google/cloud/vision_v1p4beta1/services/product_search/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ 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 exceptions as core_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 import credentials as ga_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 @@ -37,11 +35,10 @@ 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 google.protobuf import empty_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore from .transports.base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .transports.grpc import ProductSearchGrpcTransport from .transports.grpc_asyncio import ProductSearchGrpcAsyncIOTransport @@ -60,7 +57,7 @@ class ProductSearchClientMeta(type): _transport_registry["grpc_asyncio"] = ProductSearchGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[ProductSearchTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -103,7 +100,8 @@ class ProductSearchClient(metaclass=ProductSearchClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -137,7 +135,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -154,7 +153,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -173,23 +172,24 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> ProductSearchTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - ProductSearchTransport: The transport used by the client instance. + ProductSearchTransport: The transport used by the client + instance. """ return self._transport @staticmethod def product_path(project: str, location: str, product: str,) -> str: - """Return a fully-qualified product string.""" + """Returns 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.""" + """Parses a product path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)$", path, @@ -198,14 +198,14 @@ def parse_product_path(path: str) -> Dict[str, str]: @staticmethod def product_set_path(project: str, location: str, product_set: str,) -> str: - """Return a fully-qualified product_set string.""" + """Returns 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.""" + """Parses a product_set path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/productSets/(?P.+?)$", path, @@ -216,7 +216,7 @@ def parse_product_set_path(path: str) -> Dict[str, str]: def reference_image_path( project: str, location: str, product: str, reference_image: str, ) -> str: - """Return a fully-qualified reference_image string.""" + """Returns a fully-qualified reference_image string.""" return "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( project=project, location=location, @@ -226,7 +226,7 @@ def reference_image_path( @staticmethod def parse_reference_image_path(path: str) -> Dict[str, str]: - """Parse a reference_image path into its component segments.""" + """Parses a reference_image path into its component segments.""" m = re.match( r"^projects/(?P.+?)/locations/(?P.+?)/products/(?P.+?)/referenceImages/(?P.+?)$", path, @@ -235,7 +235,7 @@ def parse_reference_image_path(path: str) -> Dict[str, str]: @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -248,7 +248,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -259,7 +259,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -270,7 +270,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -281,7 +281,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -295,12 +295,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_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. + """Instantiates the product search client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -355,9 +355,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -369,12 +370,14 @@ def __init__( 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 - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -389,8 +392,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -451,7 +454,6 @@ def create_product_set( 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. @@ -483,10 +485,8 @@ def create_product_set( # 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: @@ -539,7 +539,6 @@ def list_product_sets( 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. @@ -570,10 +569,8 @@ def list_product_sets( # 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 @@ -627,7 +624,6 @@ def get_product_set( 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. @@ -659,10 +655,8 @@ def get_product_set( # 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 @@ -687,7 +681,7 @@ def update_product_set( request: product_search_service.UpdateProductSetRequest = None, *, product_set: product_search_service.ProductSet = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -722,7 +716,6 @@ def update_product_set( 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. @@ -754,10 +747,8 @@ def update_product_set( # 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: @@ -808,7 +799,6 @@ def delete_product_set( 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. @@ -831,10 +821,8 @@ def delete_product_set( # 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 @@ -903,7 +891,6 @@ def create_product( 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. @@ -930,10 +917,8 @@ def create_product( # 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: @@ -986,7 +971,6 @@ def list_products( 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. @@ -1017,10 +1001,8 @@ def list_products( # 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 @@ -1074,7 +1056,6 @@ def get_product( 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. @@ -1101,10 +1082,8 @@ def get_product( # 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 @@ -1129,7 +1108,7 @@ def update_product( request: product_search_service.UpdateProductRequest = None, *, product: product_search_service.Product = None, - update_mask: field_mask.FieldMask = None, + update_mask: field_mask_pb2.FieldMask = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), @@ -1173,7 +1152,6 @@ def update_product( 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. @@ -1200,10 +1178,8 @@ def update_product( # 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: @@ -1256,7 +1232,6 @@ def delete_product( 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. @@ -1279,10 +1254,8 @@ def delete_product( # 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 @@ -1367,7 +1340,6 @@ def create_reference_image( 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. @@ -1396,10 +1368,8 @@ def create_reference_image( # 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: @@ -1455,7 +1425,6 @@ def delete_reference_image( 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. @@ -1478,10 +1447,8 @@ def delete_reference_image( # 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 @@ -1531,7 +1498,6 @@ def list_reference_images( 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. @@ -1562,10 +1528,8 @@ def list_reference_images( # 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 @@ -1621,7 +1585,6 @@ def get_reference_image( 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. @@ -1650,10 +1613,8 @@ def get_reference_image( # 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 @@ -1717,7 +1678,6 @@ def add_product_to_product_set( 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. @@ -1742,10 +1702,8 @@ def add_product_to_product_set( 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: @@ -1804,7 +1762,6 @@ def remove_product_from_product_set( 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. @@ -1829,10 +1786,8 @@ def remove_product_from_product_set( 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: @@ -1887,7 +1842,6 @@ def list_products_in_product_set( 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. @@ -1921,10 +1875,8 @@ def list_products_in_product_set( 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 @@ -1995,7 +1947,6 @@ def import_product_sets( 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. @@ -2033,10 +1984,8 @@ def import_product_sets( # 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: @@ -2116,7 +2065,6 @@ def purge_products( 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. @@ -2158,10 +2106,8 @@ def purge_products( # 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 @@ -2182,7 +2128,7 @@ def purge_products( response = operation.from_gapic( response, self._transport.operations_client, - empty.Empty, + empty_pb2.Empty, metadata_type=product_search_service.BatchOperationMetadata, ) diff --git a/google/cloud/vision_v1p4beta1/services/product_search/pagers.py b/google/cloud/vision_v1p4beta1/services/product_search/pagers.py index 2786380e..738c7402 100644 --- a/google/cloud/vision_v1p4beta1/services/product_search/pagers.py +++ b/google/cloud/vision_v1p4beta1/services/product_search/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -119,7 +117,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -249,7 +247,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -379,7 +377,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -513,7 +511,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and diff --git a/google/cloud/vision_v1p4beta1/services/product_search/transports/__init__.py b/google/cloud/vision_v1p4beta1/services/product_search/transports/__init__.py index 8295a6de..f38d3aef 100644 --- a/google/cloud/vision_v1p4beta1/services/product_search/transports/__init__.py +++ b/google/cloud/vision_v1p4beta1/services/product_search/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/vision_v1p4beta1/services/product_search/transports/base.py b/google/cloud/vision_v1p4beta1/services/product_search/transports/base.py index 8a2f9f2a..b1d184d6 100644 --- a/google/cloud/vision_v1p4beta1/services/product_search/transports/base.py +++ b/google/cloud/vision_v1p4beta1/services/product_search/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_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.auth import credentials as ga_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 - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -38,6 +37,17 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class ProductSearchTransport(abc.ABC): """Abstract transport class for ProductSearch.""" @@ -47,21 +57,24 @@ class ProductSearchTransport(abc.ABC): "https://www.googleapis.com/auth/cloud-vision", ) + DEFAULT_HOST: str = "vision.googleapis.com" + 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, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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. + 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 @@ -70,7 +83,7 @@ def __init__( 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. + scopes (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): @@ -84,29 +97,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -129,7 +189,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -143,7 +204,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -169,7 +231,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -195,7 +258,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -209,7 +273,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -235,7 +300,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -261,7 +327,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -275,7 +342,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -289,7 +357,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -327,7 +396,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=600.0, ), @@ -359,11 +429,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def create_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.CreateProductSetRequest], - typing.Union[ + Union[ product_search_service.ProductSet, - typing.Awaitable[product_search_service.ProductSet], + Awaitable[product_search_service.ProductSet], ], ]: raise NotImplementedError() @@ -371,11 +441,11 @@ def create_product_set( @property def list_product_sets( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.ListProductSetsRequest], - typing.Union[ + Union[ product_search_service.ListProductSetsResponse, - typing.Awaitable[product_search_service.ListProductSetsResponse], + Awaitable[product_search_service.ListProductSetsResponse], ], ]: raise NotImplementedError() @@ -383,11 +453,11 @@ def list_product_sets( @property def get_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.GetProductSetRequest], - typing.Union[ + Union[ product_search_service.ProductSet, - typing.Awaitable[product_search_service.ProductSet], + Awaitable[product_search_service.ProductSet], ], ]: raise NotImplementedError() @@ -395,11 +465,11 @@ def get_product_set( @property def update_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.UpdateProductSetRequest], - typing.Union[ + Union[ product_search_service.ProductSet, - typing.Awaitable[product_search_service.ProductSet], + Awaitable[product_search_service.ProductSet], ], ]: raise NotImplementedError() @@ -407,20 +477,19 @@ def update_product_set( @property def delete_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.DeleteProductSetRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def create_product( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.CreateProductRequest], - typing.Union[ - product_search_service.Product, - typing.Awaitable[product_search_service.Product], + Union[ + product_search_service.Product, Awaitable[product_search_service.Product] ], ]: raise NotImplementedError() @@ -428,11 +497,11 @@ def create_product( @property def list_products( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.ListProductsRequest], - typing.Union[ + Union[ product_search_service.ListProductsResponse, - typing.Awaitable[product_search_service.ListProductsResponse], + Awaitable[product_search_service.ListProductsResponse], ], ]: raise NotImplementedError() @@ -440,11 +509,10 @@ def list_products( @property def get_product( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.GetProductRequest], - typing.Union[ - product_search_service.Product, - typing.Awaitable[product_search_service.Product], + Union[ + product_search_service.Product, Awaitable[product_search_service.Product] ], ]: raise NotImplementedError() @@ -452,11 +520,10 @@ def get_product( @property def update_product( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.UpdateProductRequest], - typing.Union[ - product_search_service.Product, - typing.Awaitable[product_search_service.Product], + Union[ + product_search_service.Product, Awaitable[product_search_service.Product] ], ]: raise NotImplementedError() @@ -464,20 +531,20 @@ def update_product( @property def delete_product( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.DeleteProductRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def create_reference_image( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.CreateReferenceImageRequest], - typing.Union[ + Union[ product_search_service.ReferenceImage, - typing.Awaitable[product_search_service.ReferenceImage], + Awaitable[product_search_service.ReferenceImage], ], ]: raise NotImplementedError() @@ -485,20 +552,20 @@ def create_reference_image( @property def delete_reference_image( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.DeleteReferenceImageRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def list_reference_images( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.ListReferenceImagesRequest], - typing.Union[ + Union[ product_search_service.ListReferenceImagesResponse, - typing.Awaitable[product_search_service.ListReferenceImagesResponse], + Awaitable[product_search_service.ListReferenceImagesResponse], ], ]: raise NotImplementedError() @@ -506,11 +573,11 @@ def list_reference_images( @property def get_reference_image( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.GetReferenceImageRequest], - typing.Union[ + Union[ product_search_service.ReferenceImage, - typing.Awaitable[product_search_service.ReferenceImage], + Awaitable[product_search_service.ReferenceImage], ], ]: raise NotImplementedError() @@ -518,29 +585,29 @@ def get_reference_image( @property def add_product_to_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.AddProductToProductSetRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def remove_product_from_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.RemoveProductFromProductSetRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def list_products_in_product_set( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.ListProductsInProductSetRequest], - typing.Union[ + Union[ product_search_service.ListProductsInProductSetResponse, - typing.Awaitable[product_search_service.ListProductsInProductSetResponse], + Awaitable[product_search_service.ListProductsInProductSetResponse], ], ]: raise NotImplementedError() @@ -548,18 +615,18 @@ def list_products_in_product_set( @property def import_product_sets( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.ImportProductSetsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def purge_products( self, - ) -> typing.Callable[ + ) -> Callable[ [product_search_service.PurgeProductsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() diff --git a/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py b/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py index ef133008..bb2f61e7 100644 --- a/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py +++ b/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # 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 typing import Callable, Dict, Optional, Sequence, Tuple, Union 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 +import google.auth # type: ignore +from google.auth import credentials as ga_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 google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO @@ -72,7 +69,7 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -86,7 +83,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -197,7 +195,7 @@ def __init__( def create_channel( cls, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -228,13 +226,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -398,7 +398,7 @@ def update_product_set( @property def delete_product_set( self, - ) -> Callable[[product_search_service.DeleteProductSetRequest], empty.Empty]: + ) -> Callable[[product_search_service.DeleteProductSetRequest], empty_pb2.Empty]: r"""Return a callable for the delete product set method over gRPC. Permanently deletes a ProductSet. Products and @@ -420,7 +420,7 @@ def delete_product_set( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_product_set"] @@ -573,7 +573,7 @@ def update_product( @property def delete_product( self, - ) -> Callable[[product_search_service.DeleteProductRequest], empty.Empty]: + ) -> Callable[[product_search_service.DeleteProductRequest], empty_pb2.Empty]: r"""Return a callable for the delete product method over gRPC. Permanently deletes a product and its reference @@ -597,7 +597,7 @@ def delete_product( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_product"] @@ -654,7 +654,9 @@ def create_reference_image( @property def delete_reference_image( self, - ) -> Callable[[product_search_service.DeleteReferenceImageRequest], empty.Empty]: + ) -> Callable[ + [product_search_service.DeleteReferenceImageRequest], empty_pb2.Empty + ]: r"""Return a callable for the delete reference image method over gRPC. Permanently deletes a reference image. @@ -679,7 +681,7 @@ def delete_reference_image( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_reference_image"] @@ -754,7 +756,9 @@ def get_reference_image( @property def add_product_to_product_set( self, - ) -> Callable[[product_search_service.AddProductToProductSetRequest], empty.Empty]: + ) -> Callable[ + [product_search_service.AddProductToProductSetRequest], empty_pb2.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 @@ -781,7 +785,7 @@ def add_product_to_product_set( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["add_product_to_product_set"] @@ -789,7 +793,7 @@ def add_product_to_product_set( def remove_product_from_product_set( self, ) -> Callable[ - [product_search_service.RemoveProductFromProductSetRequest], empty.Empty + [product_search_service.RemoveProductFromProductSetRequest], empty_pb2.Empty ]: r"""Return a callable for the remove product from product set method over gRPC. @@ -812,7 +816,7 @@ def 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["remove_product_from_product_set"] @@ -856,7 +860,7 @@ def list_products_in_product_set( def import_product_sets( self, ) -> Callable[ - [product_search_service.ImportProductSetsRequest], operations.Operation + [product_search_service.ImportProductSetsRequest], operations_pb2.Operation ]: r"""Return a callable for the import product sets method over gRPC. @@ -887,14 +891,16 @@ def import_product_sets( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_product_sets"] @property def purge_products( self, - ) -> Callable[[product_search_service.PurgeProductsRequest], operations.Operation]: + ) -> Callable[ + [product_search_service.PurgeProductsRequest], operations_pb2.Operation + ]: r"""Return a callable for the purge products method over gRPC. Asynchronous API to delete all Products in a ProductSet or all @@ -939,7 +945,7 @@ def purge_products( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["purge_products"] 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 index 04bc1521..31ba0ffe 100644 --- a/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc_asyncio.py +++ b/google/cloud/vision_v1p4beta1/services/product_search/transports/grpc_asyncio.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union 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 import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version 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 google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import ProductSearchTransport, DEFAULT_CLIENT_INFO from .grpc import ProductSearchGrpcTransport @@ -75,7 +72,7 @@ class ProductSearchGrpcAsyncIOTransport(ProductSearchTransport): def create_channel( cls, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -102,13 +99,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -116,7 +115,7 @@ def __init__( self, *, host: str = "vision.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -130,7 +129,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -189,7 +189,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -406,7 +405,7 @@ def update_product_set( def delete_product_set( self, ) -> Callable[ - [product_search_service.DeleteProductSetRequest], Awaitable[empty.Empty] + [product_search_service.DeleteProductSetRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete product set method over gRPC. @@ -429,7 +428,7 @@ def delete_product_set( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_product_set"] @@ -586,7 +585,7 @@ def update_product( def delete_product( self, ) -> Callable[ - [product_search_service.DeleteProductRequest], Awaitable[empty.Empty] + [product_search_service.DeleteProductRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete product method over gRPC. @@ -611,7 +610,7 @@ def delete_product( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_product"] @@ -669,7 +668,7 @@ def create_reference_image( def delete_reference_image( self, ) -> Callable[ - [product_search_service.DeleteReferenceImageRequest], Awaitable[empty.Empty] + [product_search_service.DeleteReferenceImageRequest], Awaitable[empty_pb2.Empty] ]: r"""Return a callable for the delete reference image method over gRPC. @@ -695,7 +694,7 @@ def delete_reference_image( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_reference_image"] @@ -771,7 +770,8 @@ def get_reference_image( def add_product_to_product_set( self, ) -> Callable[ - [product_search_service.AddProductToProductSetRequest], Awaitable[empty.Empty] + [product_search_service.AddProductToProductSetRequest], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the add product to product set method over gRPC. @@ -799,7 +799,7 @@ def add_product_to_product_set( 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["add_product_to_product_set"] @@ -808,7 +808,7 @@ def remove_product_from_product_set( self, ) -> Callable[ [product_search_service.RemoveProductFromProductSetRequest], - Awaitable[empty.Empty], + Awaitable[empty_pb2.Empty], ]: r"""Return a callable for the remove product from product set method over gRPC. @@ -831,7 +831,7 @@ def 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, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["remove_product_from_product_set"] @@ -876,7 +876,7 @@ def import_product_sets( self, ) -> Callable[ [product_search_service.ImportProductSetsRequest], - Awaitable[operations.Operation], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the import product sets method over gRPC. @@ -907,7 +907,7 @@ def import_product_sets( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["import_product_sets"] @@ -915,7 +915,8 @@ def import_product_sets( def purge_products( self, ) -> Callable[ - [product_search_service.PurgeProductsRequest], Awaitable[operations.Operation] + [product_search_service.PurgeProductsRequest], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the purge products method over gRPC. @@ -961,7 +962,7 @@ def purge_products( 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, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["purge_products"] diff --git a/google/cloud/vision_v1p4beta1/types/__init__.py b/google/cloud/vision_v1p4beta1/types/__init__.py index fd5dd48d..9e1748dd 100644 --- a/google/cloud/vision_v1p4beta1/types/__init__.py +++ b/google/cloud/vision_v1p4beta1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .face import ( Celebrity, FaceRecognitionParams, diff --git a/google/cloud/vision_v1p4beta1/types/face.py b/google/cloud/vision_v1p4beta1/types/face.py index 89fbc30b..4586f25d 100644 --- a/google/cloud/vision_v1p4beta1/types/face.py +++ b/google/cloud/vision_v1p4beta1/types/face.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -26,7 +24,6 @@ class FaceRecognitionParams(proto.Message): r"""Parameters for a celebrity recognition request. - Attributes: celebrity_set (Sequence[str]): The resource names for one or more @@ -37,12 +34,11 @@ class FaceRecognitionParams(proto.Message): Celebrities in the CelebritySets. """ - celebrity_set = proto.RepeatedField(proto.STRING, number=1) + 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 @@ -53,16 +49,13 @@ class Celebrity(proto.Message): 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) + 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 (google.cloud.vision_v1p4beta1.types.Celebrity): The [Celebrity][google.cloud.vision.v1p4beta1.Celebrity] @@ -72,8 +65,7 @@ class FaceRecognitionResult(proto.Message): """ celebrity = proto.Field(proto.MESSAGE, number=1, message="Celebrity",) - - confidence = proto.Field(proto.FLOAT, number=2) + 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 index b43c8d06..87fc605d 100644 --- a/google/cloud/vision_v1p4beta1/types/geometry.py +++ b/google/cloud/vision_v1p4beta1/types/geometry.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -36,9 +34,8 @@ class Vertex(proto.Message): Y coordinate. """ - x = proto.Field(proto.INT32, number=1) - - y = proto.Field(proto.INT32, number=2) + x = proto.Field(proto.INT32, number=1,) + y = proto.Field(proto.INT32, number=2,) class NormalizedVertex(proto.Message): @@ -53,14 +50,12 @@ class NormalizedVertex(proto.Message): Y coordinate. """ - x = proto.Field(proto.FLOAT, number=1) - - y = proto.Field(proto.FLOAT, number=2) + 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[google.cloud.vision_v1p4beta1.types.Vertex]): The bounding polygon vertices. @@ -69,7 +64,6 @@ class BoundingPoly(proto.Message): """ vertices = proto.RepeatedField(proto.MESSAGE, number=1, message="Vertex",) - normalized_vertices = proto.RepeatedField( proto.MESSAGE, number=2, message="NormalizedVertex", ) @@ -90,11 +84,9 @@ class Position(proto.Message): 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) + 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 index b4e3b321..99e6c7b4 100644 --- a/google/cloud/vision_v1p4beta1/types/image_annotator.py +++ b/google/cloud/vision_v1p4beta1/types/image_annotator.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,19 +13,17 @@ # 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 +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +from google.type import color_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore __protobuf__ = proto.module( @@ -123,10 +120,8 @@ class Type(proto.Enum): 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) + max_results = proto.Field(proto.INT32, number=2,) + model = proto.Field(proto.STRING, number=3,) class ImageSource(proto.Message): @@ -164,14 +159,12 @@ class ImageSource(proto.Message): ``image_uri`` takes precedence. """ - gcs_image_uri = proto.Field(proto.STRING, number=1) - - image_uri = proto.Field(proto.STRING, number=2) + 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 @@ -184,8 +177,7 @@ class Image(proto.Message): perform the image annotation request. """ - content = proto.Field(proto.BYTES, number=1) - + content = proto.Field(proto.BYTES, number=1,) source = proto.Field(proto.MESSAGE, number=2, message="ImageSource",) @@ -256,7 +248,6 @@ class FaceAnnotation(proto.Message): class Landmark(proto.Message): r"""A face-specific landmark (for example, a face feature). - Attributes: type_ (google.cloud.vision_v1p4beta1.types.FaceAnnotation.Landmark.Type): Face landmark type. @@ -307,41 +298,25 @@ class Type(proto.Enum): 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) - + 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, ) @@ -349,18 +324,16 @@ class Type(proto.Enum): class LocationInfo(proto.Message): r"""Detected entity location information. - Attributes: lat_lng (google.type.latlng_pb2.LatLng): lat/long location coordinates. """ - lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng.LatLng,) + lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng_pb2.LatLng,) class Property(proto.Message): r"""A ``Property`` consists of a user-supplied name/value pair. - Attributes: name (str): Name of the property. @@ -370,16 +343,13 @@ class Property(proto.Message): 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) + 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 @@ -422,28 +392,19 @@ class EntityAnnotation(proto.Message): 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) - + 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 @@ -461,14 +422,10 @@ class LocalizedObjectAnnotation(proto.Message): 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) - + 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,) @@ -502,19 +459,14 @@ class SafeSearchAnnotation(proto.Message): """ 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 (google.type.latlng_pb2.LatLng): Min lat/long pair. @@ -522,9 +474,8 @@ class LatLongRect(proto.Message): 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,) + min_lat_lng = proto.Field(proto.MESSAGE, number=1, message=latlng_pb2.LatLng,) + max_lat_lng = proto.Field(proto.MESSAGE, number=2, message=latlng_pb2.LatLng,) class ColorInfo(proto.Message): @@ -541,16 +492,13 @@ class ColorInfo(proto.Message): 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) + color = proto.Field(proto.MESSAGE, number=1, message=color_pb2.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[google.cloud.vision_v1p4beta1.types.ColorInfo]): RGB color values with their score and pixel @@ -562,7 +510,6 @@ class DominantColorsAnnotation(proto.Message): class ImageProperties(proto.Message): r"""Stores image properties, such as dominant colors. - Attributes: dominant_colors (google.cloud.vision_v1p4beta1.types.DominantColorsAnnotation): If present, dominant colors completed @@ -591,10 +538,8 @@ class CropHint(proto.Message): """ 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) + confidence = proto.Field(proto.FLOAT, number=2,) + importance_fraction = proto.Field(proto.FLOAT, number=3,) class CropHintsAnnotation(proto.Message): @@ -611,7 +556,6 @@ class CropHintsAnnotation(proto.Message): class CropHintsParams(proto.Message): r"""Parameters for crop hints annotation request. - Attributes: aspect_ratios (Sequence[float]): Aspect ratios in floats, representing the @@ -624,19 +568,18 @@ class CropHintsParams(proto.Message): provided after the 16th are ignored. """ - aspect_ratios = proto.RepeatedField(proto.FLOAT, number=1) + 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) + include_geo_results = proto.Field(proto.BOOL, number=2,) class TextDetectionParams(proto.Message): @@ -650,12 +593,11 @@ class TextDetectionParams(proto.Message): include confidence score for TEXT_DETECTION as well. """ - enable_text_detection_confidence_score = proto.Field(proto.BOOL, number=9) + enable_text_detection_confidence_score = proto.Field(proto.BOOL, number=9,) class ImageContext(proto.Message): r"""Image context and/or feature-specific parameters. - Attributes: lat_long_rect (google.cloud.vision_v1p4beta1.types.LatLongRect): Not used. @@ -684,23 +626,17 @@ class ImageContext(proto.Message): """ lat_long_rect = proto.Field(proto.MESSAGE, number=1, message="LatLongRect",) - - language_hints = proto.RepeatedField(proto.STRING, number=2) - + 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", ) - text_detection_params = proto.Field( proto.MESSAGE, number=12, message="TextDetectionParams", ) @@ -722,9 +658,7 @@ class AnnotateImageRequest(proto.Message): """ 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",) @@ -742,14 +676,12 @@ class ImageAnnotationContext(proto.Message): produce the image. """ - uri = proto.Field(proto.STRING, number=1) - - page_number = proto.Field(proto.INT32, number=2) + 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[google.cloud.vision_v1p4beta1.types.FaceAnnotation]): If present, face detection has completed @@ -802,53 +734,40 @@ class AnnotateImageResponse(proto.Message): 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,) - + error = proto.Field(proto.MESSAGE, number=9, message=status_pb2.Status,) context = proto.Field(proto.MESSAGE, number=21, message="ImageAnnotationContext",) @@ -869,7 +788,6 @@ class BatchAnnotateImagesRequest(proto.Message): class BatchAnnotateImagesResponse(proto.Message): r"""Response to a batch image annotation request. - Attributes: responses (Sequence[google.cloud.vision_v1p4beta1.types.AnnotateImageResponse]): Individual responses to image annotation @@ -912,12 +830,9 @@ class AnnotateFileRequest(proto.Message): """ 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) + pages = proto.RepeatedField(proto.INT32, number=4,) class AnnotateFileResponse(proto.Message): @@ -941,14 +856,11 @@ class AnnotateFileResponse(proto.Message): """ 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,) + total_pages = proto.Field(proto.INT32, number=3,) + error = proto.Field(proto.MESSAGE, number=4, message=status_pb2.Status,) class BatchAnnotateFilesRequest(proto.Message): @@ -970,7 +882,6 @@ class BatchAnnotateFilesRequest(proto.Message): class BatchAnnotateFilesResponse(proto.Message): r"""A list of file annotation responses. - Attributes: responses (Sequence[google.cloud.vision_v1p4beta1.types.AnnotateFileResponse]): The list of file annotation responses, each @@ -986,7 +897,6 @@ class BatchAnnotateFilesResponse(proto.Message): class AsyncAnnotateFileRequest(proto.Message): r"""An offline file annotation request. - Attributes: input_config (google.cloud.vision_v1p4beta1.types.InputConfig): Required. Information about the input file. @@ -1001,17 +911,13 @@ class AsyncAnnotateFileRequest(proto.Message): """ 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 (google.cloud.vision_v1p4beta1.types.OutputConfig): The output location and metadata from @@ -1023,7 +929,6 @@ class AsyncAnnotateFileResponse(proto.Message): class AsyncBatchAnnotateImagesRequest(proto.Message): r"""Request for async image annotation for a list of images. - Attributes: requests (Sequence[google.cloud.vision_v1p4beta1.types.AnnotateImageRequest]): Required. Individual image annotation @@ -1036,13 +941,11 @@ class AsyncBatchAnnotateImagesRequest(proto.Message): 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 (google.cloud.vision_v1p4beta1.types.OutputConfig): The output location and metadata from @@ -1069,7 +972,6 @@ class AsyncBatchAnnotateFilesRequest(proto.Message): class AsyncBatchAnnotateFilesResponse(proto.Message): r"""Response to an async batch file annotation request. - Attributes: responses (Sequence[google.cloud.vision_v1p4beta1.types.AsyncAnnotateFileResponse]): The list of file annotation responses, one @@ -1084,7 +986,6 @@ class AsyncBatchAnnotateFilesResponse(proto.Message): class InputConfig(proto.Message): r"""The desired input location and metadata. - Attributes: gcs_source (google.cloud.vision_v1p4beta1.types.GcsSource): The Google Cloud Storage location to read the @@ -1104,15 +1005,12 @@ class InputConfig(proto.Message): """ 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) + 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 (google.cloud.vision_v1p4beta1.types.GcsDestination): The Google Cloud Storage location to write @@ -1132,8 +1030,7 @@ class OutputConfig(proto.Message): """ gcs_destination = proto.Field(proto.MESSAGE, number=1, message="GcsDestination",) - - batch_size = proto.Field(proto.INT32, number=2) + batch_size = proto.Field(proto.INT32, number=2,) class GcsSource(proto.Message): @@ -1147,7 +1044,7 @@ class GcsSource(proto.Message): Wildcards are not currently supported. """ - uri = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) class GcsDestination(proto.Message): @@ -1184,12 +1081,11 @@ class GcsDestination(proto.Message): overflows into multiple sharded files. """ - uri = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) class OperationMetadata(proto.Message): r"""Contains metadata for the BatchAnnotateImages operation. - Attributes: state (google.cloud.vision_v1p4beta1.types.OperationMetadata.State): Current state of the batch operation. @@ -1209,10 +1105,8 @@ class State(proto.Enum): 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,) + create_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) + update_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.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 index f0aa53b8..b69426bf 100644 --- a/google/cloud/vision_v1p4beta1/types/product_search.py +++ b/google/cloud/vision_v1p4beta1/types/product_search.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # 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 +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -31,7 +28,6 @@ class ProductSearchParams(proto.Message): r"""Parameters for a product search request. - Attributes: bounding_poly (google.cloud.vision_v1p4beta1.types.BoundingPoly): The bounding polygon around the area of @@ -71,17 +67,13 @@ class ProductSearchParams(proto.Message): """ 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) + 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 (google.protobuf.timestamp_pb2.Timestamp): Timestamp of the index which provided these @@ -101,7 +93,6 @@ class ProductSearchResults(proto.Message): class Result(proto.Message): r"""Information about a product. - Attributes: product (google.cloud.vision_v1p4beta1.types.Product): The Product. @@ -116,14 +107,11 @@ class Result(proto.Message): 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) + 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 @@ -138,13 +126,10 @@ class ObjectAnnotation(proto.Message): 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) + 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 @@ -164,19 +149,15 @@ class GroupedResult(proto.Message): 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,) - + index_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) results = proto.RepeatedField(proto.MESSAGE, number=5, message=Result,) - product_grouped_results = proto.RepeatedField( proto.MESSAGE, number=6, message=GroupedResult, ) diff --git a/google/cloud/vision_v1p4beta1/types/product_search_service.py b/google/cloud/vision_v1p4beta1/types/product_search_service.py index 25df6719..28dc7191 100644 --- a/google/cloud/vision_v1p4beta1/types/product_search_service.py +++ b/google/cloud/vision_v1p4beta1/types/product_search_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,14 +13,12 @@ # 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 +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore __protobuf__ = proto.module( @@ -64,7 +61,6 @@ class Product(proto.Message): r"""A Product contains ReferenceImages. - Attributes: name (str): The resource name of the product. @@ -107,7 +103,6 @@ class Product(proto.Message): 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. @@ -118,18 +113,13 @@ class KeyValue(proto.Message): 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) + 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,) @@ -168,13 +158,10 @@ class ProductSet(proto.Message): 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,) + 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_pb2.Timestamp,) + index_error = proto.Field(proto.MESSAGE, number=4, message=status_pb2.Status,) class ReferenceImage(proto.Message): @@ -208,10 +195,8 @@ class ReferenceImage(proto.Message): 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) - + 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, ) @@ -219,7 +204,6 @@ class ReferenceImage(proto.Message): class CreateProductRequest(proto.Message): r"""Request message for the ``CreateProduct`` method. - Attributes: parent (str): Required. The project in which the Product should be @@ -236,16 +220,13 @@ class CreateProductRequest(proto.Message): cannot contain the character ``/``. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) product = proto.Field(proto.MESSAGE, number=2, message="Product",) - - product_id = proto.Field(proto.STRING, number=3) + 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 @@ -260,16 +241,13 @@ class ListProductsRequest(proto.Message): 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) + 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[google.cloud.vision_v1p4beta1.types.Product]): List of products. @@ -284,13 +262,11 @@ def raw_page(self): return self products = proto.RepeatedField(proto.MESSAGE, number=1, message="Product",) - - next_page_token = proto.Field(proto.STRING, number=2) + 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. @@ -299,12 +275,11 @@ class GetProductRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateProductRequest(proto.Message): r"""Request message for the ``UpdateProduct`` method. - Attributes: product (google.cloud.vision_v1p4beta1.types.Product): Required. The Product resource which replaces @@ -318,13 +293,13 @@ class UpdateProductRequest(proto.Message): """ product = proto.Field(proto.MESSAGE, number=1, message="Product",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteProductRequest(proto.Message): r"""Request message for the ``DeleteProduct`` method. - Attributes: name (str): Required. Resource name of product to delete. @@ -333,12 +308,11 @@ class DeleteProductRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field(proto.STRING, number=1) + 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 @@ -355,16 +329,13 @@ class CreateProductSetRequest(proto.Message): cannot contain the character ``/``. """ - parent = proto.Field(proto.STRING, number=1) - + 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) + 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 @@ -379,16 +350,13 @@ class ListProductSetsRequest(proto.Message): 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) + 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[google.cloud.vision_v1p4beta1.types.ProductSet]): List of ProductSets. @@ -403,13 +371,11 @@ 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) + 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. @@ -418,12 +384,11 @@ class GetProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateProductSetRequest(proto.Message): r"""Request message for the ``UpdateProductSet`` method. - Attributes: product_set (google.cloud.vision_v1p4beta1.types.ProductSet): Required. The ProductSet resource which @@ -436,13 +401,13 @@ class UpdateProductSetRequest(proto.Message): """ product_set = proto.Field(proto.MESSAGE, number=1, message="ProductSet",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteProductSetRequest(proto.Message): r"""Request message for the ``DeleteProductSet`` method. - Attributes: name (str): Required. Resource name of the ProductSet to delete. @@ -451,12 +416,11 @@ class DeleteProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`` """ - name = proto.Field(proto.STRING, number=1) + 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 @@ -475,16 +439,13 @@ class CreateReferenceImageRequest(proto.Message): characters long. It cannot contain the character ``/``. """ - parent = proto.Field(proto.STRING, number=1) - + 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) + 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 @@ -503,16 +464,13 @@ class ListReferenceImagesRequest(proto.Message): 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) + 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[google.cloud.vision_v1p4beta1.types.ReferenceImage]): The list of reference images. @@ -531,15 +489,12 @@ def raw_page(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) + 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. @@ -549,12 +504,11 @@ class GetReferenceImageRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID``. """ - name = proto.Field(proto.STRING, number=1) + 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 @@ -565,12 +519,11 @@ class DeleteReferenceImageRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`` """ - name = proto.Field(proto.STRING, number=1) + 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. @@ -585,14 +538,12 @@ class AddProductToProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field(proto.STRING, number=1) - - product = proto.Field(proto.STRING, number=2) + 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. @@ -607,14 +558,12 @@ class RemoveProductFromProductSetRequest(proto.Message): ``projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`` """ - name = proto.Field(proto.STRING, number=1) - - product = proto.Field(proto.STRING, number=2) + 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 @@ -630,16 +579,13 @@ class ListProductsInProductSetRequest(proto.Message): 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) + 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[google.cloud.vision_v1p4beta1.types.Product]): The list of Products. @@ -654,8 +600,7 @@ def raw_page(self): return self products = proto.RepeatedField(proto.MESSAGE, number=1, message="Product",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class ImportProductSetsGcsSource(proto.Message): @@ -739,12 +684,11 @@ class ImportProductSetsGcsSource(proto.Message): too large to process (larger than 20MP). """ - csv_file_uri = proto.Field(proto.STRING, number=1) + csv_file_uri = proto.Field(proto.STRING, number=1,) class ImportProductSetsInputConfig(proto.Message): r"""The input content for the ``ImportProductSets`` method. - Attributes: gcs_source (google.cloud.vision_v1p4beta1.types.ImportProductSetsGcsSource): The Google Cloud Storage location for a csv @@ -759,7 +703,6 @@ class ImportProductSetsInputConfig(proto.Message): class ImportProductSetsRequest(proto.Message): r"""Request message for the ``ImportProductSets`` method. - Attributes: parent (str): Required. The project in which the ProductSets should be @@ -771,8 +714,7 @@ class ImportProductSetsRequest(proto.Message): requests. """ - parent = proto.Field(proto.STRING, number=1) - + parent = proto.Field(proto.STRING, number=1,) input_config = proto.Field( proto.MESSAGE, number=2, message="ImportProductSetsInputConfig", ) @@ -803,8 +745,7 @@ class ImportProductSetsResponse(proto.Message): reference_images = proto.RepeatedField( proto.MESSAGE, number=1, message="ReferenceImage", ) - - statuses = proto.RepeatedField(proto.MESSAGE, number=2, message=status.Status,) + statuses = proto.RepeatedField(proto.MESSAGE, number=2, message=status_pb2.Status,) class BatchOperationMetadata(proto.Message): @@ -837,10 +778,8 @@ class State(proto.Enum): 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,) + submit_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) class ProductSetPurgeConfig(proto.Message): @@ -854,12 +793,11 @@ class ProductSetPurgeConfig(proto.Message): ProductSets, the Product will still be deleted. """ - product_set_id = proto.Field(proto.STRING, number=1) + 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 (google.cloud.vision_v1p4beta1.types.ProductSetPurgeConfig): Specify which ProductSet contains the @@ -880,12 +818,9 @@ class PurgeProductsRequest(proto.Message): 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) + 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 index ee384d68..4fa23fa0 100644 --- a/google/cloud/vision_v1p4beta1/types/text_annotation.py +++ b/google/cloud/vision_v1p4beta1/types/text_annotation.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # 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 @@ -46,7 +43,6 @@ class TextAnnotation(proto.Message): 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 @@ -56,13 +52,11 @@ class DetectedLanguage(proto.Message): Confidence of detected language. Range [0, 1]. """ - language_code = proto.Field(proto.STRING, number=1) - - confidence = proto.Field(proto.FLOAT, number=2) + 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_ (google.cloud.vision_v1p4beta1.types.TextAnnotation.DetectedBreak.BreakType): Detected break type. @@ -82,12 +76,10 @@ class BreakType(proto.Enum): type_ = proto.Field( proto.ENUM, number=1, enum="TextAnnotation.DetectedBreak.BreakType", ) - - is_prefix = proto.Field(proto.BOOL, number=2) + is_prefix = proto.Field(proto.BOOL, number=2,) class TextProperty(proto.Message): r"""Additional information detected on the structural component. - Attributes: detected_languages (Sequence[google.cloud.vision_v1p4beta1.types.TextAnnotation.DetectedLanguage]): A list of detected languages together with @@ -99,19 +91,16 @@ class TextProperty(proto.Message): 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) + text = proto.Field(proto.STRING, number=2,) class Page(proto.Message): r"""Detected page from OCR. - Attributes: property (google.cloud.vision_v1p4beta1.types.TextAnnotation.TextProperty): Additional information detected on the page. @@ -131,19 +120,14 @@ class Page(proto.Message): property = proto.Field( proto.MESSAGE, number=1, message="TextAnnotation.TextProperty", ) - - width = proto.Field(proto.INT32, number=2) - - height = proto.Field(proto.INT32, number=3) - + 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) + confidence = proto.Field(proto.FLOAT, number=5,) class Block(proto.Message): r"""Logical element on the page. - Attributes: property (google.cloud.vision_v1p4beta1.types.TextAnnotation.TextProperty): Additional information detected for the @@ -195,14 +179,10 @@ class BlockType(proto.Enum): 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) + confidence = proto.Field(proto.FLOAT, number=5,) class Paragraph(proto.Message): @@ -235,17 +215,13 @@ class Paragraph(proto.Message): 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) + confidence = proto.Field(proto.FLOAT, number=4,) class Word(proto.Message): r"""A word representation. - Attributes: property (google.cloud.vision_v1p4beta1.types.TextAnnotation.TextProperty): Additional information detected for the word. @@ -272,17 +248,13 @@ class Word(proto.Message): 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) + confidence = proto.Field(proto.FLOAT, number=4,) class Symbol(proto.Message): r"""A single symbol representation. - Attributes: property (google.cloud.vision_v1p4beta1.types.TextAnnotation.TextProperty): Additional information detected for the @@ -309,12 +281,9 @@ class Symbol(proto.Message): 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) + 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 index c9efe25e..b843b5da 100644 --- a/google/cloud/vision_v1p4beta1/types/web_detection.py +++ b/google/cloud/vision_v1p4beta1/types/web_detection.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore @@ -25,7 +23,6 @@ class WebDetection(proto.Message): r"""Relevant information for the image from the Internet. - Attributes: web_entities (Sequence[google.cloud.vision_v1p4beta1.types.WebDetection.WebEntity]): Deduced entities from similar images on the @@ -52,7 +49,6 @@ class WebDetection(proto.Message): class WebEntity(proto.Message): r"""Entity deduced from similar images on the Internet. - Attributes: entity_id (str): Opaque entity ID. @@ -65,15 +61,12 @@ class WebEntity(proto.Message): English. """ - entity_id = proto.Field(proto.STRING, number=1) - - score = proto.Field(proto.FLOAT, number=2) - - description = proto.Field(proto.STRING, number=3) + 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. @@ -82,13 +75,11 @@ class WebImage(proto.Message): image. """ - url = proto.Field(proto.STRING, number=1) - - score = proto.Field(proto.FLOAT, number=2) + 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. @@ -109,23 +100,18 @@ class WebPage(proto.Message): crops. """ - url = proto.Field(proto.STRING, number=1) - - score = proto.Field(proto.FLOAT, number=2) - - page_title = proto.Field(proto.STRING, number=3) - + 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. @@ -135,28 +121,22 @@ class WebLabel(proto.Message): http://www.unicode.org/reports/tr35/#Unicode_locale_identifier. """ - label = proto.Field(proto.STRING, number=1) - - language_code = proto.Field(proto.STRING, number=2) + 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,) diff --git a/noxfile.py b/noxfile.py index c68a880d..7d7db4ef 100644 --- a/noxfile.py +++ b/noxfile.py @@ -62,16 +62,9 @@ def lint(session): session.run("flake8", "google", "tests") -@nox.session(python="3.6") +@nox.session(python=DEFAULT_PYTHON_VERSION) def blacken(session): - """Run black. - - Format code to uniform standard. - - This currently uses Python 3.6 due to the automated Kokoro run of synthtool. - That run uses an image that doesn't have 3.6 installed. Before updating this - check the state of the `gcp_ubuntu_config` we use for that Kokoro run. - """ + """Run black. Format code to uniform standard.""" session.install(BLACK_VERSION) session.run( "black", *BLACK_PATHS, @@ -131,9 +124,6 @@ def system(session): # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": session.skip("RUN_SYSTEM_TESTS is set to false, skipping") - # Sanity check: Only run tests if the environment variable is set. - if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): - session.skip("Credentials must be set via environment variable") # Install pyopenssl for mTLS testing. if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": session.install("pyopenssl") diff --git a/synth.py b/owlbot.py similarity index 68% rename from synth.py rename to owlbot.py index 6153313e..52c433a4 100644 --- a/synth.py +++ b/owlbot.py @@ -18,39 +18,21 @@ from synthtool import gcp from synthtool.languages import python -gapic = gcp.GAPICBazel() common = gcp.CommonTemplates() -versions = ["v1", "v1p1beta1", "v1p2beta1", "v1p3beta1", "v1p4beta1"] +default_version = "v1" -# ---------------------------------------------------------------------------- -# Generate vision GAPIC layer -# ---------------------------------------------------------------------------- -for version in versions: - library = gapic.py_library( - service="vision", - version=version, - bazel_target=f"//google/cloud/vision/{version}:vision-{version}-py", - include_protos=True - ) - - s.move(library / f"google/cloud/vision_{version}/proto") - 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/vision_{version}") +for library in s.get_staging_dirs(default_version): + if library.name == "v1": + s.replace( + library / "google/cloud/vision/__init__.py", + "from google.cloud.vision_v1.services.image_annotator.client import ImageAnnotatorClient", + "from google.cloud.vision_v1 import ImageAnnotatorClient" + ) # Add vision helpers to each version s.replace( - f"google/cloud/vision_{version}/__init__.py", + library / f"google/cloud/vision_{library.name}/__init__.py", "from .services.image_annotator import ImageAnnotatorClient", "from google.cloud.vision_helpers.decorators import " "add_single_feature_methods\n" @@ -59,7 +41,7 @@ ) s.replace( - f"google/cloud/vision_{version}/__init__.py", + library / f"google/cloud/vision_{library.name}/__init__.py", "__all__ = \(", "@add_single_feature_methods\n" "class ImageAnnotatorClient(VisionHelpers, IacImageAnnotatorClient):\n" @@ -70,31 +52,34 @@ # Temporary workaround due to bug https://github.com/googleapis/proto-plus-python/issues/135 s.replace( - f"google/cloud/vision_{version}/services/image_annotator/client.py", + library / f"google/cloud/vision_{library.name}/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}/services/image_annotator/client.py", + library / f"google/cloud/vision_{library.name}/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", + library / f"google/cloud/vision_{library.name}/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", + library / f"google/cloud/vision_{library.name}/services/image_annotator/client.py", "request = image_annotator.AsyncBatchAnnotateFilesRequest\(request\)", "request = image_annotator.AsyncBatchAnnotateFilesRequest(request)\n" " if requests is not None:\n" @@ -102,14 +87,21 @@ " requests[i] = image_annotator.AsyncAnnotateFileRequest(requests[i])" ) -s.replace( - "google/cloud/vision/__init__.py", - "from google.cloud.vision_v1.services.image_annotator.client import ImageAnnotatorClient", - "from google.cloud.vision_v1 import ImageAnnotatorClient" -) + s.move(library / f"google/cloud/vision_{library.name}/proto") + s.move(library / f"google/cloud/vision_{library.name}/services") + s.move(library / f"google/cloud/vision_{library.name}/types") + s.move(library / f"google/cloud/vision_{library.name}/__init__.py") + s.move(library / f"google/cloud/vision_{library.name}/py.typed") + s.move(library / f"tests/unit/gapic/vision_{library.name}") + + # don't publish docs for these versions + if library.name != "v1p1beta1": + s.move(library / f"docs/vision_{library.name}") + + # Move docs configuration + s.move(library / f"docs/conf.py") -# Move docs configuration -s.move(library / f"docs/conf.py") +s.remove_staging_dirs() # ---------------------------------------------------------------------------- # Add templated files @@ -128,6 +120,6 @@ python.py_samples(skip_readmes=True) # TODO(busunkim): Use latest sphinx after microgenerator transition -s.replace("noxfile.py", """['"]sphinx['"]""", '"sphinx<3.0.0"') +s.replace("noxfile.py", """['"]sphinx==4.0.1['"]""", '"sphinx<3.0.0"') s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/renovate.json b/renovate.json index f08bc22c..c0489556 100644 --- a/renovate.json +++ b/renovate.json @@ -2,5 +2,8 @@ "extends": [ "config:base", ":preserveSemverRanges" ], - "ignorePaths": [".pre-commit-config.yaml"] + "ignorePaths": [".pre-commit-config.yaml"], + "pip_requirements": { + "fileMatch": ["requirements-test.txt", "samples/[\\S/]*constraints.txt", "samples/[\\S/]*constraints-test.txt"] + } } diff --git a/samples/snippets/crop_hints/noxfile.py b/samples/snippets/crop_hints/noxfile.py index 97bf7da8..5ff9e1db 100644 --- a/samples/snippets/crop_hints/noxfile.py +++ b/samples/snippets/crop_hints/noxfile.py @@ -50,7 +50,10 @@ # to use your own Cloud project. 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - + # If you need to use a specific version of pip, + # change pip_version_override to the string representation + # of the version number, for example, "20.2.4" + "pip_version_override": None, # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. 'envs': {}, @@ -170,12 +173,21 @@ def blacken(session: nox.sessions.Session) -> None: def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None: + if TEST_CONFIG["pip_version_override"]: + pip_version = TEST_CONFIG["pip_version_override"] + session.install(f"pip=={pip_version}") """Runs py.test for a particular project.""" if os.path.exists("requirements.txt"): - session.install("-r", "requirements.txt") + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") if os.path.exists("requirements-test.txt"): - session.install("-r", "requirements-test.txt") + if os.path.exists("constraints-test.txt"): + session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt") + else: + session.install("-r", "requirements-test.txt") if INSTALL_LIBRARY_FROM_SOURCE: session.install("-e", _get_repo_root()) diff --git a/samples/snippets/crop_hints/requirements-test.txt b/samples/snippets/crop_hints/requirements-test.txt index 7e460c8c..95ea1e6a 100644 --- a/samples/snippets/crop_hints/requirements-test.txt +++ b/samples/snippets/crop_hints/requirements-test.txt @@ -1 +1 @@ -pytest==6.0.1 +pytest==6.2.4 diff --git a/samples/snippets/crop_hints/requirements.txt b/samples/snippets/crop_hints/requirements.txt index 056a2279..f3c585e9 100644 --- a/samples/snippets/crop_hints/requirements.txt +++ b/samples/snippets/crop_hints/requirements.txt @@ -1,2 +1,2 @@ -google-cloud-vision==2.3.0 +google-cloud-vision==2.3.1 pillow==8.2.0 diff --git a/samples/snippets/detect/noxfile.py b/samples/snippets/detect/noxfile.py index 97bf7da8..5ff9e1db 100644 --- a/samples/snippets/detect/noxfile.py +++ b/samples/snippets/detect/noxfile.py @@ -50,7 +50,10 @@ # to use your own Cloud project. 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - + # If you need to use a specific version of pip, + # change pip_version_override to the string representation + # of the version number, for example, "20.2.4" + "pip_version_override": None, # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. 'envs': {}, @@ -170,12 +173,21 @@ def blacken(session: nox.sessions.Session) -> None: def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None: + if TEST_CONFIG["pip_version_override"]: + pip_version = TEST_CONFIG["pip_version_override"] + session.install(f"pip=={pip_version}") """Runs py.test for a particular project.""" if os.path.exists("requirements.txt"): - session.install("-r", "requirements.txt") + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") if os.path.exists("requirements-test.txt"): - session.install("-r", "requirements-test.txt") + if os.path.exists("constraints-test.txt"): + session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt") + else: + session.install("-r", "requirements-test.txt") if INSTALL_LIBRARY_FROM_SOURCE: session.install("-e", _get_repo_root()) diff --git a/samples/snippets/detect/requirements-test.txt b/samples/snippets/detect/requirements-test.txt index 11251b00..88d5e51d 100644 --- a/samples/snippets/detect/requirements-test.txt +++ b/samples/snippets/detect/requirements-test.txt @@ -1,3 +1,3 @@ backoff==1.10.0 -pytest==6.0.1 +pytest==6.2.4 flaky==3.7.0 diff --git a/samples/snippets/detect/requirements.txt b/samples/snippets/detect/requirements.txt index ff426be1..bc0ef7c5 100644 --- a/samples/snippets/detect/requirements.txt +++ b/samples/snippets/detect/requirements.txt @@ -1,2 +1,2 @@ -google-cloud-vision==2.3.0 -google-cloud-storage==1.37.0 +google-cloud-vision==2.3.1 +google-cloud-storage==1.38.0 diff --git a/samples/snippets/document_text/noxfile.py b/samples/snippets/document_text/noxfile.py index 97bf7da8..5ff9e1db 100644 --- a/samples/snippets/document_text/noxfile.py +++ b/samples/snippets/document_text/noxfile.py @@ -50,7 +50,10 @@ # to use your own Cloud project. 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - + # If you need to use a specific version of pip, + # change pip_version_override to the string representation + # of the version number, for example, "20.2.4" + "pip_version_override": None, # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. 'envs': {}, @@ -170,12 +173,21 @@ def blacken(session: nox.sessions.Session) -> None: def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None: + if TEST_CONFIG["pip_version_override"]: + pip_version = TEST_CONFIG["pip_version_override"] + session.install(f"pip=={pip_version}") """Runs py.test for a particular project.""" if os.path.exists("requirements.txt"): - session.install("-r", "requirements.txt") + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") if os.path.exists("requirements-test.txt"): - session.install("-r", "requirements-test.txt") + if os.path.exists("constraints-test.txt"): + session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt") + else: + session.install("-r", "requirements-test.txt") if INSTALL_LIBRARY_FROM_SOURCE: session.install("-e", _get_repo_root()) diff --git a/samples/snippets/document_text/requirements-test.txt b/samples/snippets/document_text/requirements-test.txt index 7e460c8c..95ea1e6a 100644 --- a/samples/snippets/document_text/requirements-test.txt +++ b/samples/snippets/document_text/requirements-test.txt @@ -1 +1 @@ -pytest==6.0.1 +pytest==6.2.4 diff --git a/samples/snippets/document_text/requirements.txt b/samples/snippets/document_text/requirements.txt index 056a2279..f3c585e9 100644 --- a/samples/snippets/document_text/requirements.txt +++ b/samples/snippets/document_text/requirements.txt @@ -1,2 +1,2 @@ -google-cloud-vision==2.3.0 +google-cloud-vision==2.3.1 pillow==8.2.0 diff --git a/samples/snippets/face_detection/noxfile.py b/samples/snippets/face_detection/noxfile.py index 97bf7da8..5ff9e1db 100644 --- a/samples/snippets/face_detection/noxfile.py +++ b/samples/snippets/face_detection/noxfile.py @@ -50,7 +50,10 @@ # to use your own Cloud project. 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - + # If you need to use a specific version of pip, + # change pip_version_override to the string representation + # of the version number, for example, "20.2.4" + "pip_version_override": None, # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. 'envs': {}, @@ -170,12 +173,21 @@ def blacken(session: nox.sessions.Session) -> None: def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None: + if TEST_CONFIG["pip_version_override"]: + pip_version = TEST_CONFIG["pip_version_override"] + session.install(f"pip=={pip_version}") """Runs py.test for a particular project.""" if os.path.exists("requirements.txt"): - session.install("-r", "requirements.txt") + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") if os.path.exists("requirements-test.txt"): - session.install("-r", "requirements-test.txt") + if os.path.exists("constraints-test.txt"): + session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt") + else: + session.install("-r", "requirements-test.txt") if INSTALL_LIBRARY_FROM_SOURCE: session.install("-e", _get_repo_root()) diff --git a/samples/snippets/face_detection/requirements-test.txt b/samples/snippets/face_detection/requirements-test.txt index 7e460c8c..95ea1e6a 100644 --- a/samples/snippets/face_detection/requirements-test.txt +++ b/samples/snippets/face_detection/requirements-test.txt @@ -1 +1 @@ -pytest==6.0.1 +pytest==6.2.4 diff --git a/samples/snippets/face_detection/requirements.txt b/samples/snippets/face_detection/requirements.txt index 056a2279..f3c585e9 100644 --- a/samples/snippets/face_detection/requirements.txt +++ b/samples/snippets/face_detection/requirements.txt @@ -1,2 +1,2 @@ -google-cloud-vision==2.3.0 +google-cloud-vision==2.3.1 pillow==8.2.0 diff --git a/samples/snippets/product_search/noxfile.py b/samples/snippets/product_search/noxfile.py index 97bf7da8..5ff9e1db 100644 --- a/samples/snippets/product_search/noxfile.py +++ b/samples/snippets/product_search/noxfile.py @@ -50,7 +50,10 @@ # to use your own Cloud project. 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - + # If you need to use a specific version of pip, + # change pip_version_override to the string representation + # of the version number, for example, "20.2.4" + "pip_version_override": None, # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. 'envs': {}, @@ -170,12 +173,21 @@ def blacken(session: nox.sessions.Session) -> None: def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None: + if TEST_CONFIG["pip_version_override"]: + pip_version = TEST_CONFIG["pip_version_override"] + session.install(f"pip=={pip_version}") """Runs py.test for a particular project.""" if os.path.exists("requirements.txt"): - session.install("-r", "requirements.txt") + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") if os.path.exists("requirements-test.txt"): - session.install("-r", "requirements-test.txt") + if os.path.exists("constraints-test.txt"): + session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt") + else: + session.install("-r", "requirements-test.txt") if INSTALL_LIBRARY_FROM_SOURCE: session.install("-e", _get_repo_root()) 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 282bc8d8..5dec3c2a 100755 --- a/samples/snippets/product_search/product_in_product_set_management.py +++ b/samples/snippets/product_search/product_in_product_set_management.py @@ -147,7 +147,7 @@ def purge_products_in_product_set( "force": force }) - operation.result(timeout=300) + operation.result(timeout=500) print('Deleted products in product set.') # [END vision_product_search_purge_products_in_product_set] diff --git a/samples/snippets/product_search/product_management.py b/samples/snippets/product_search/product_management.py index 96eb5872..75697ddf 100755 --- a/samples/snippets/product_search/product_management.py +++ b/samples/snippets/product_search/product_management.py @@ -206,7 +206,7 @@ def purge_orphan_products(project_id, location, force): "force": force }) - operation.result(timeout=300) + operation.result(timeout=500) print('Orphan products deleted.') # [END vision_product_search_purge_orphan_products] diff --git a/samples/snippets/product_search/requirements-test.txt b/samples/snippets/product_search/requirements-test.txt index 95614446..eb03b265 100644 --- a/samples/snippets/product_search/requirements-test.txt +++ b/samples/snippets/product_search/requirements-test.txt @@ -1,2 +1,2 @@ -pytest==6.0.1 +pytest==6.2.4 flaky==3.7.0 \ No newline at end of file diff --git a/samples/snippets/product_search/requirements.txt b/samples/snippets/product_search/requirements.txt index 624f1ebd..5c71413a 100644 --- a/samples/snippets/product_search/requirements.txt +++ b/samples/snippets/product_search/requirements.txt @@ -1,2 +1,2 @@ -google-cloud-vision==2.3.0 -google-cloud-storage==1.37.0 \ No newline at end of file +google-cloud-vision==2.3.1 +google-cloud-storage==1.38.0 \ No newline at end of file diff --git a/samples/snippets/quickstart/noxfile.py b/samples/snippets/quickstart/noxfile.py index 97bf7da8..5ff9e1db 100644 --- a/samples/snippets/quickstart/noxfile.py +++ b/samples/snippets/quickstart/noxfile.py @@ -50,7 +50,10 @@ # to use your own Cloud project. 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - + # If you need to use a specific version of pip, + # change pip_version_override to the string representation + # of the version number, for example, "20.2.4" + "pip_version_override": None, # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. 'envs': {}, @@ -170,12 +173,21 @@ def blacken(session: nox.sessions.Session) -> None: def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None: + if TEST_CONFIG["pip_version_override"]: + pip_version = TEST_CONFIG["pip_version_override"] + session.install(f"pip=={pip_version}") """Runs py.test for a particular project.""" if os.path.exists("requirements.txt"): - session.install("-r", "requirements.txt") + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") if os.path.exists("requirements-test.txt"): - session.install("-r", "requirements-test.txt") + if os.path.exists("constraints-test.txt"): + session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt") + else: + session.install("-r", "requirements-test.txt") if INSTALL_LIBRARY_FROM_SOURCE: session.install("-e", _get_repo_root()) diff --git a/samples/snippets/quickstart/requirements-test.txt b/samples/snippets/quickstart/requirements-test.txt index 7e460c8c..95ea1e6a 100644 --- a/samples/snippets/quickstart/requirements-test.txt +++ b/samples/snippets/quickstart/requirements-test.txt @@ -1 +1 @@ -pytest==6.0.1 +pytest==6.2.4 diff --git a/samples/snippets/quickstart/requirements.txt b/samples/snippets/quickstart/requirements.txt index f2a3609a..0c4d8ac3 100644 --- a/samples/snippets/quickstart/requirements.txt +++ b/samples/snippets/quickstart/requirements.txt @@ -1 +1 @@ -google-cloud-vision==2.3.0 +google-cloud-vision==2.3.1 diff --git a/samples/snippets/web/noxfile.py b/samples/snippets/web/noxfile.py index 97bf7da8..5ff9e1db 100644 --- a/samples/snippets/web/noxfile.py +++ b/samples/snippets/web/noxfile.py @@ -50,7 +50,10 @@ # to use your own Cloud project. 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - + # If you need to use a specific version of pip, + # change pip_version_override to the string representation + # of the version number, for example, "20.2.4" + "pip_version_override": None, # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. 'envs': {}, @@ -170,12 +173,21 @@ def blacken(session: nox.sessions.Session) -> None: def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None: + if TEST_CONFIG["pip_version_override"]: + pip_version = TEST_CONFIG["pip_version_override"] + session.install(f"pip=={pip_version}") """Runs py.test for a particular project.""" if os.path.exists("requirements.txt"): - session.install("-r", "requirements.txt") + if os.path.exists("constraints.txt"): + session.install("-r", "requirements.txt", "-c", "constraints.txt") + else: + session.install("-r", "requirements.txt") if os.path.exists("requirements-test.txt"): - session.install("-r", "requirements-test.txt") + if os.path.exists("constraints-test.txt"): + session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt") + else: + session.install("-r", "requirements-test.txt") if INSTALL_LIBRARY_FROM_SOURCE: session.install("-e", _get_repo_root()) diff --git a/samples/snippets/web/requirements-test.txt b/samples/snippets/web/requirements-test.txt index f8230db6..6efe8ab4 100644 --- a/samples/snippets/web/requirements-test.txt +++ b/samples/snippets/web/requirements-test.txt @@ -1,2 +1,2 @@ flaky==3.7.0 -pytest==6.0.1 +pytest==6.2.4 diff --git a/samples/snippets/web/requirements.txt b/samples/snippets/web/requirements.txt index f2a3609a..0c4d8ac3 100644 --- a/samples/snippets/web/requirements.txt +++ b/samples/snippets/web/requirements.txt @@ -1 +1 @@ -google-cloud-vision==2.3.0 +google-cloud-vision==2.3.1 diff --git a/setup.py b/setup.py index cb84f4ae..e8f6ba73 100644 --- a/setup.py +++ b/setup.py @@ -19,11 +19,12 @@ name = "google-cloud-vision" description = "Cloud Vision API API client library" -version = "2.3.1" +version = "2.3.2" release_status = "Development Status :: 5 - Production/Stable" dependencies = [ "google-api-core[grpc] >= 1.22.2, < 2.0.0dev", "proto-plus >= 1.15.0", + "packaging >= 14.3", ] extras = {"libcst": "libcst >= 0.2.5"} diff --git a/synth.metadata b/synth.metadata deleted file mode 100644 index 369a351c..00000000 --- a/synth.metadata +++ /dev/null @@ -1,324 +0,0 @@ -{ - "sources": [ - { - "git": { - "name": ".", - "remote": "https://github.com/googleapis/python-vision.git", - "sha": "44c0bf5749a2cd8197b04905e4299b97e38357d3" - } - }, - { - "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "c539b9b08b3366ee00c0ec1950f4df711552a269", - "internalRef": "365759522" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "5b5bf6d519b2d658d9f2e483d9f6f3d0ba8ee6bc" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "5b5bf6d519b2d658d9f2e483d9f6f3d0ba8ee6bc" - } - } - ], - "destinations": [ - { - "client": { - "source": "googleapis", - "apiName": "vision", - "apiVersion": "v1", - "language": "python", - "generator": "bazel" - } - }, - { - "client": { - "source": "googleapis", - "apiName": "vision", - "apiVersion": "v1p1beta1", - "language": "python", - "generator": "bazel" - } - }, - { - "client": { - "source": "googleapis", - "apiName": "vision", - "apiVersion": "v1p2beta1", - "language": "python", - "generator": "bazel" - } - }, - { - "client": { - "source": "googleapis", - "apiName": "vision", - "apiVersion": "v1p3beta1", - "language": "python", - "generator": "bazel" - } - }, - { - "client": { - "source": "googleapis", - "apiName": "vision", - "apiVersion": "v1p4beta1", - "language": "python", - "generator": "bazel" - } - } - ], - "generatedFiles": [ - ".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/header-checker-lint.yml", - ".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/populate-secrets.sh", - ".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-head.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-head.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-head.cfg", - ".kokoro/samples/python3.8/periodic.cfg", - ".kokoro/samples/python3.8/presubmit.cfg", - ".kokoro/test-samples-against-head.sh", - ".kokoro/test-samples-impl.sh", - ".kokoro/test-samples.sh", - ".kokoro/trampoline.sh", - ".kokoro/trampoline_v2.sh", - ".pre-commit-config.yaml", - ".trampolinerc", - "CODE_OF_CONDUCT.md", - "CONTRIBUTING.rst", - "LICENSE", - "MANIFEST.in", - "docs/_static/custom.css", - "docs/_templates/layout.html", - "docs/conf.py", - "docs/multiprocessing.rst", - "docs/vision_v1/image_annotator.rst", - "docs/vision_v1/product_search.rst", - "docs/vision_v1/services.rst", - "docs/vision_v1/types.rst", - "docs/vision_v1p2beta1/image_annotator.rst", - "docs/vision_v1p2beta1/services.rst", - "docs/vision_v1p2beta1/types.rst", - "docs/vision_v1p3beta1/image_annotator.rst", - "docs/vision_v1p3beta1/product_search.rst", - "docs/vision_v1p3beta1/services.rst", - "docs/vision_v1p3beta1/types.rst", - "docs/vision_v1p4beta1/image_annotator.rst", - "docs/vision_v1p4beta1/product_search.rst", - "docs/vision_v1p4beta1/services.rst", - "docs/vision_v1p4beta1/types.rst", - "google/cloud/vision/__init__.py", - "google/cloud/vision/py.typed", - "google/cloud/vision_v1/__init__.py", - "google/cloud/vision_v1/proto/geometry.proto", - "google/cloud/vision_v1/proto/image_annotator.proto", - "google/cloud/vision_v1/proto/product_search.proto", - "google/cloud/vision_v1/proto/product_search_service.proto", - "google/cloud/vision_v1/proto/text_annotation.proto", - "google/cloud/vision_v1/proto/web_detection.proto", - "google/cloud/vision_v1/py.typed", - "google/cloud/vision_v1/services/__init__.py", - "google/cloud/vision_v1/services/image_annotator/__init__.py", - "google/cloud/vision_v1/services/image_annotator/async_client.py", - "google/cloud/vision_v1/services/image_annotator/client.py", - "google/cloud/vision_v1/services/image_annotator/transports/__init__.py", - "google/cloud/vision_v1/services/image_annotator/transports/base.py", - "google/cloud/vision_v1/services/image_annotator/transports/grpc.py", - "google/cloud/vision_v1/services/image_annotator/transports/grpc_asyncio.py", - "google/cloud/vision_v1/services/product_search/__init__.py", - "google/cloud/vision_v1/services/product_search/async_client.py", - "google/cloud/vision_v1/services/product_search/client.py", - "google/cloud/vision_v1/services/product_search/pagers.py", - "google/cloud/vision_v1/services/product_search/transports/__init__.py", - "google/cloud/vision_v1/services/product_search/transports/base.py", - "google/cloud/vision_v1/services/product_search/transports/grpc.py", - "google/cloud/vision_v1/services/product_search/transports/grpc_asyncio.py", - "google/cloud/vision_v1/types/__init__.py", - "google/cloud/vision_v1/types/geometry.py", - "google/cloud/vision_v1/types/image_annotator.py", - "google/cloud/vision_v1/types/product_search.py", - "google/cloud/vision_v1/types/product_search_service.py", - "google/cloud/vision_v1/types/text_annotation.py", - "google/cloud/vision_v1/types/web_detection.py", - "google/cloud/vision_v1p1beta1/__init__.py", - "google/cloud/vision_v1p1beta1/proto/geometry.proto", - "google/cloud/vision_v1p1beta1/proto/image_annotator.proto", - "google/cloud/vision_v1p1beta1/proto/text_annotation.proto", - "google/cloud/vision_v1p1beta1/proto/web_detection.proto", - "google/cloud/vision_v1p1beta1/py.typed", - "google/cloud/vision_v1p1beta1/services/__init__.py", - "google/cloud/vision_v1p1beta1/services/image_annotator/__init__.py", - "google/cloud/vision_v1p1beta1/services/image_annotator/async_client.py", - "google/cloud/vision_v1p1beta1/services/image_annotator/client.py", - "google/cloud/vision_v1p1beta1/services/image_annotator/transports/__init__.py", - "google/cloud/vision_v1p1beta1/services/image_annotator/transports/base.py", - "google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc.py", - "google/cloud/vision_v1p1beta1/services/image_annotator/transports/grpc_asyncio.py", - "google/cloud/vision_v1p1beta1/types/__init__.py", - "google/cloud/vision_v1p1beta1/types/geometry.py", - "google/cloud/vision_v1p1beta1/types/image_annotator.py", - "google/cloud/vision_v1p1beta1/types/text_annotation.py", - "google/cloud/vision_v1p1beta1/types/web_detection.py", - "google/cloud/vision_v1p2beta1/__init__.py", - "google/cloud/vision_v1p2beta1/proto/geometry.proto", - "google/cloud/vision_v1p2beta1/proto/image_annotator.proto", - "google/cloud/vision_v1p2beta1/proto/text_annotation.proto", - "google/cloud/vision_v1p2beta1/proto/web_detection.proto", - "google/cloud/vision_v1p2beta1/py.typed", - "google/cloud/vision_v1p2beta1/services/__init__.py", - "google/cloud/vision_v1p2beta1/services/image_annotator/__init__.py", - "google/cloud/vision_v1p2beta1/services/image_annotator/async_client.py", - "google/cloud/vision_v1p2beta1/services/image_annotator/client.py", - "google/cloud/vision_v1p2beta1/services/image_annotator/transports/__init__.py", - "google/cloud/vision_v1p2beta1/services/image_annotator/transports/base.py", - "google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc.py", - "google/cloud/vision_v1p2beta1/services/image_annotator/transports/grpc_asyncio.py", - "google/cloud/vision_v1p2beta1/types/__init__.py", - "google/cloud/vision_v1p2beta1/types/geometry.py", - "google/cloud/vision_v1p2beta1/types/image_annotator.py", - "google/cloud/vision_v1p2beta1/types/text_annotation.py", - "google/cloud/vision_v1p2beta1/types/web_detection.py", - "google/cloud/vision_v1p3beta1/__init__.py", - "google/cloud/vision_v1p3beta1/proto/geometry.proto", - "google/cloud/vision_v1p3beta1/proto/image_annotator.proto", - "google/cloud/vision_v1p3beta1/proto/product_search.proto", - "google/cloud/vision_v1p3beta1/proto/product_search_service.proto", - "google/cloud/vision_v1p3beta1/proto/text_annotation.proto", - "google/cloud/vision_v1p3beta1/proto/web_detection.proto", - "google/cloud/vision_v1p3beta1/py.typed", - "google/cloud/vision_v1p3beta1/services/__init__.py", - "google/cloud/vision_v1p3beta1/services/image_annotator/__init__.py", - "google/cloud/vision_v1p3beta1/services/image_annotator/async_client.py", - "google/cloud/vision_v1p3beta1/services/image_annotator/client.py", - "google/cloud/vision_v1p3beta1/services/image_annotator/transports/__init__.py", - "google/cloud/vision_v1p3beta1/services/image_annotator/transports/base.py", - "google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc.py", - "google/cloud/vision_v1p3beta1/services/image_annotator/transports/grpc_asyncio.py", - "google/cloud/vision_v1p3beta1/services/product_search/__init__.py", - "google/cloud/vision_v1p3beta1/services/product_search/async_client.py", - "google/cloud/vision_v1p3beta1/services/product_search/client.py", - "google/cloud/vision_v1p3beta1/services/product_search/pagers.py", - "google/cloud/vision_v1p3beta1/services/product_search/transports/__init__.py", - "google/cloud/vision_v1p3beta1/services/product_search/transports/base.py", - "google/cloud/vision_v1p3beta1/services/product_search/transports/grpc.py", - "google/cloud/vision_v1p3beta1/services/product_search/transports/grpc_asyncio.py", - "google/cloud/vision_v1p3beta1/types/__init__.py", - "google/cloud/vision_v1p3beta1/types/geometry.py", - "google/cloud/vision_v1p3beta1/types/image_annotator.py", - "google/cloud/vision_v1p3beta1/types/product_search.py", - "google/cloud/vision_v1p3beta1/types/product_search_service.py", - "google/cloud/vision_v1p3beta1/types/text_annotation.py", - "google/cloud/vision_v1p3beta1/types/web_detection.py", - "google/cloud/vision_v1p4beta1/__init__.py", - "google/cloud/vision_v1p4beta1/proto/face.proto", - "google/cloud/vision_v1p4beta1/proto/geometry.proto", - "google/cloud/vision_v1p4beta1/proto/image_annotator.proto", - "google/cloud/vision_v1p4beta1/proto/product_search.proto", - "google/cloud/vision_v1p4beta1/proto/product_search_service.proto", - "google/cloud/vision_v1p4beta1/proto/text_annotation.proto", - "google/cloud/vision_v1p4beta1/proto/web_detection.proto", - "google/cloud/vision_v1p4beta1/py.typed", - "google/cloud/vision_v1p4beta1/services/__init__.py", - "google/cloud/vision_v1p4beta1/services/image_annotator/__init__.py", - "google/cloud/vision_v1p4beta1/services/image_annotator/async_client.py", - "google/cloud/vision_v1p4beta1/services/image_annotator/client.py", - "google/cloud/vision_v1p4beta1/services/image_annotator/transports/__init__.py", - "google/cloud/vision_v1p4beta1/services/image_annotator/transports/base.py", - "google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc.py", - "google/cloud/vision_v1p4beta1/services/image_annotator/transports/grpc_asyncio.py", - "google/cloud/vision_v1p4beta1/services/product_search/__init__.py", - "google/cloud/vision_v1p4beta1/services/product_search/async_client.py", - "google/cloud/vision_v1p4beta1/services/product_search/client.py", - "google/cloud/vision_v1p4beta1/services/product_search/pagers.py", - "google/cloud/vision_v1p4beta1/services/product_search/transports/__init__.py", - "google/cloud/vision_v1p4beta1/services/product_search/transports/base.py", - "google/cloud/vision_v1p4beta1/services/product_search/transports/grpc.py", - "google/cloud/vision_v1p4beta1/services/product_search/transports/grpc_asyncio.py", - "google/cloud/vision_v1p4beta1/types/__init__.py", - "google/cloud/vision_v1p4beta1/types/face.py", - "google/cloud/vision_v1p4beta1/types/geometry.py", - "google/cloud/vision_v1p4beta1/types/image_annotator.py", - "google/cloud/vision_v1p4beta1/types/product_search.py", - "google/cloud/vision_v1p4beta1/types/product_search_service.py", - "google/cloud/vision_v1p4beta1/types/text_annotation.py", - "google/cloud/vision_v1p4beta1/types/web_detection.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/vision_v1/__init__.py", - "tests/unit/gapic/vision_v1/test_image_annotator.py", - "tests/unit/gapic/vision_v1/test_product_search.py", - "tests/unit/gapic/vision_v1p1beta1/__init__.py", - "tests/unit/gapic/vision_v1p1beta1/test_image_annotator.py", - "tests/unit/gapic/vision_v1p2beta1/__init__.py", - "tests/unit/gapic/vision_v1p2beta1/test_image_annotator.py", - "tests/unit/gapic/vision_v1p3beta1/__init__.py", - "tests/unit/gapic/vision_v1p3beta1/test_image_annotator.py", - "tests/unit/gapic/vision_v1p3beta1/test_product_search.py", - "tests/unit/gapic/vision_v1p4beta1/__init__.py", - "tests/unit/gapic/vision_v1p4beta1/test_image_annotator.py", - "tests/unit/gapic/vision_v1p4beta1/test_product_search.py" - ] -} \ No newline at end of file diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index cc205f2a..29486a27 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -7,3 +7,4 @@ # Then this file should have foo==1.14.0 google-api-core==1.22.2 proto-plus==1.15.0 +packaging==14.3 diff --git a/tests/unit/gapic/vision_v1/__init__.py b/tests/unit/gapic/vision_v1/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/vision_v1/__init__.py +++ b/tests/unit/gapic/vision_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/vision_v1/test_image_annotator.py b/tests/unit/gapic/vision_v1/test_image_annotator.py index b1537280..fdc147d5 100644 --- a/tests/unit/gapic/vision_v1/test_image_annotator.py +++ b/tests/unit/gapic/vision_v1/test_image_annotator.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,26 +23,56 @@ 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 exceptions as core_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 import credentials as ga_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.services.image_annotator.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.vision_v1.services.image_annotator.transports.base import ( + _GOOGLE_AUTH_VERSION, +) 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 +from google.type import latlng_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -94,7 +123,7 @@ def test__get_default_mtls_endpoint(): "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient,] ) def test_image_annotator_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -111,7 +140,7 @@ def test_image_annotator_client_from_service_account_info(client_class): "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient,] ) def test_image_annotator_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -164,7 +193,7 @@ def test_image_annotator_client_client_options( ): # 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()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -452,7 +481,7 @@ def test_batch_annotate_images( transport: str = "grpc", request_type=image_annotator.BatchAnnotateImagesRequest ): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -465,17 +494,14 @@ def test_batch_annotate_images( ) 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) @@ -487,7 +513,7 @@ def test_batch_annotate_images_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -497,7 +523,6 @@ def test_batch_annotate_images_empty_call(): client.batch_annotate_images() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.BatchAnnotateImagesRequest() @@ -507,7 +532,7 @@ async def test_batch_annotate_images_async( request_type=image_annotator.BatchAnnotateImagesRequest, ): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -522,13 +547,11 @@ async def test_batch_annotate_images_async( 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] == image_annotator.BatchAnnotateImagesRequest() # Establish that the response is the type that we expect. @@ -541,7 +564,7 @@ async def test_batch_annotate_images_async_from_dict(): def test_batch_annotate_images_flattened(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -549,7 +572,6 @@ def test_batch_annotate_images_flattened(): ) 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( @@ -564,7 +586,6 @@ def test_batch_annotate_images_flattened(): # 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") @@ -573,7 +594,7 @@ def test_batch_annotate_images_flattened(): def test_batch_annotate_images_flattened_error(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -590,7 +611,9 @@ def test_batch_annotate_images_flattened_error(): @pytest.mark.asyncio async def test_batch_annotate_images_flattened_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -616,7 +639,6 @@ async def test_batch_annotate_images_flattened_async(): # 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") @@ -626,7 +648,9 @@ async def test_batch_annotate_images_flattened_async(): @pytest.mark.asyncio async def test_batch_annotate_images_flattened_error_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -645,7 +669,7 @@ def test_batch_annotate_files( transport: str = "grpc", request_type=image_annotator.BatchAnnotateFilesRequest ): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -658,17 +682,14 @@ def test_batch_annotate_files( ) 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) @@ -680,7 +701,7 @@ def test_batch_annotate_files_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -690,7 +711,6 @@ def test_batch_annotate_files_empty_call(): client.batch_annotate_files() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.BatchAnnotateFilesRequest() @@ -700,7 +720,7 @@ async def test_batch_annotate_files_async( request_type=image_annotator.BatchAnnotateFilesRequest, ): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -715,13 +735,11 @@ async def test_batch_annotate_files_async( 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] == image_annotator.BatchAnnotateFilesRequest() # Establish that the response is the type that we expect. @@ -734,7 +752,7 @@ async def test_batch_annotate_files_async_from_dict(): def test_batch_annotate_files_flattened(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -742,7 +760,6 @@ def test_batch_annotate_files_flattened(): ) 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( @@ -759,7 +776,6 @@ def test_batch_annotate_files_flattened(): # 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( @@ -770,7 +786,7 @@ def test_batch_annotate_files_flattened(): def test_batch_annotate_files_flattened_error(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -789,7 +805,9 @@ def test_batch_annotate_files_flattened_error(): @pytest.mark.asyncio async def test_batch_annotate_files_flattened_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -817,7 +835,6 @@ async def test_batch_annotate_files_flattened_async(): # 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( @@ -829,7 +846,9 @@ async def test_batch_annotate_files_flattened_async(): @pytest.mark.asyncio async def test_batch_annotate_files_flattened_error_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -851,7 +870,7 @@ def test_async_batch_annotate_images( request_type=image_annotator.AsyncBatchAnnotateImagesRequest, ): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -864,13 +883,11 @@ def test_async_batch_annotate_images( ) 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. @@ -885,7 +902,7 @@ def test_async_batch_annotate_images_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -895,7 +912,6 @@ def test_async_batch_annotate_images_empty_call(): client.async_batch_annotate_images() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.AsyncBatchAnnotateImagesRequest() @@ -905,7 +921,7 @@ async def test_async_batch_annotate_images_async( request_type=image_annotator.AsyncBatchAnnotateImagesRequest, ): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -920,13 +936,11 @@ async def test_async_batch_annotate_images_async( 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] == image_annotator.AsyncBatchAnnotateImagesRequest() # Establish that the response is the type that we expect. @@ -939,7 +953,7 @@ async def test_async_batch_annotate_images_async_from_dict(): def test_async_batch_annotate_images_flattened(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -947,7 +961,6 @@ def test_async_batch_annotate_images_flattened(): ) 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( @@ -965,20 +978,18 @@ def test_async_batch_annotate_images_flattened(): # 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(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -998,7 +1009,9 @@ def test_async_batch_annotate_images_flattened_error(): @pytest.mark.asyncio async def test_async_batch_annotate_images_flattened_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1027,13 +1040,11 @@ async def test_async_batch_annotate_images_flattened_async(): # 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") ) @@ -1041,7 +1052,9 @@ async def test_async_batch_annotate_images_flattened_async(): @pytest.mark.asyncio async def test_async_batch_annotate_images_flattened_error_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1063,7 +1076,7 @@ def test_async_batch_annotate_files( transport: str = "grpc", request_type=image_annotator.AsyncBatchAnnotateFilesRequest ): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1076,13 +1089,11 @@ def test_async_batch_annotate_files( ) 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. @@ -1097,7 +1108,7 @@ def test_async_batch_annotate_files_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1107,7 +1118,6 @@ def test_async_batch_annotate_files_empty_call(): client.async_batch_annotate_files() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.AsyncBatchAnnotateFilesRequest() @@ -1117,7 +1127,7 @@ async def test_async_batch_annotate_files_async( request_type=image_annotator.AsyncBatchAnnotateFilesRequest, ): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1132,13 +1142,11 @@ async def test_async_batch_annotate_files_async( 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] == image_annotator.AsyncBatchAnnotateFilesRequest() # Establish that the response is the type that we expect. @@ -1151,7 +1159,7 @@ async def test_async_batch_annotate_files_async_from_dict(): def test_async_batch_annotate_files_flattened(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1159,7 +1167,6 @@ def test_async_batch_annotate_files_flattened(): ) 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( @@ -1176,7 +1183,6 @@ def test_async_batch_annotate_files_flattened(): # 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( @@ -1187,7 +1193,7 @@ def test_async_batch_annotate_files_flattened(): def test_async_batch_annotate_files_flattened_error(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1206,7 +1212,9 @@ def test_async_batch_annotate_files_flattened_error(): @pytest.mark.asyncio async def test_async_batch_annotate_files_flattened_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1234,7 +1242,6 @@ async def test_async_batch_annotate_files_flattened_async(): # 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( @@ -1246,7 +1253,9 @@ async def test_async_batch_annotate_files_flattened_async(): @pytest.mark.asyncio async def test_async_batch_annotate_files_flattened_error_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1266,16 +1275,16 @@ async def test_async_batch_annotate_files_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImageAnnotatorClient( @@ -1285,7 +1294,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImageAnnotatorClient( @@ -1296,7 +1305,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ImageAnnotatorClient(transport=transport) assert client.transport is transport @@ -1305,13 +1314,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ImageAnnotatorGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1326,23 +1335,23 @@ def test_transport_get_channel(): ) 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) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_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(),) + client = ImageAnnotatorClient(credentials=ga_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): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ImageAnnotatorTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1354,7 +1363,7 @@ def test_image_annotator_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ImageAnnotatorTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1375,15 +1384,40 @@ def test_image_annotator_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 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" + google.auth, "load_credentials_from_file", autospec=True + ) 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 = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ImageAnnotatorTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_image_annotator_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) 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) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1399,19 +1433,36 @@ def test_image_annotator_base_transport_with_credentials_file(): 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( + with mock.patch.object(google.auth, "default", autospec=True) 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) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 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) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ImageAnnotatorClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_image_annotator_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) ImageAnnotatorClient() adc.assert_called_once_with( scopes=( @@ -1422,14 +1473,44 @@ def test_image_annotator_auth_adc(): ) -def test_image_annotator_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_image_annotator_transport_auth_adc(transport_class): # 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" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_image_annotator_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -1439,6 +1520,121 @@ def test_image_annotator_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ImageAnnotatorGrpcTransport, grpc_helpers), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_image_annotator_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + scopes=["1", "2"], + default_host="vision.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ImageAnnotatorGrpcTransport, grpc_helpers), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_image_annotator_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ImageAnnotatorGrpcTransport, grpc_helpers), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_image_annotator_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1447,7 +1643,7 @@ def test_image_annotator_transport_auth_adc(): ], ) def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1489,7 +1685,7 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_cl def test_image_annotator_host_no_port(): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="vision.googleapis.com" ), @@ -1499,7 +1695,7 @@ def test_image_annotator_host_no_port(): def test_image_annotator_host_with_port(): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="vision.googleapis.com:8000" ), @@ -1555,9 +1751,9 @@ def test_image_annotator_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1639,7 +1835,7 @@ def test_image_annotator_transport_channel_mtls_with_adc(transport_class): def test_image_annotator_grpc_lro_client(): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -1652,7 +1848,7 @@ def test_image_annotator_grpc_lro_client(): def test_image_annotator_grpc_lro_async_client(): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -1667,7 +1863,6 @@ def test_product_path(): project = "squid" location = "clam" product = "whelk" - expected = "projects/{project}/locations/{location}/products/{product}".format( project=project, location=location, product=product, ) @@ -1692,7 +1887,6 @@ def test_product_set_path(): project = "cuttlefish" location = "mussel" product_set = "winkle" - expected = "projects/{project}/locations/{location}/productSets/{product_set}".format( project=project, location=location, product_set=product_set, ) @@ -1715,7 +1909,6 @@ def test_parse_product_set_path(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1736,7 +1929,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = ImageAnnotatorClient.common_folder_path(folder) assert expected == actual @@ -1755,7 +1947,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = ImageAnnotatorClient.common_organization_path(organization) assert expected == actual @@ -1774,7 +1965,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = ImageAnnotatorClient.common_project_path(project) assert expected == actual @@ -1794,7 +1984,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1821,7 +2010,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ImageAnnotatorTransport, "_prep_wrapped_messages" ) as prep: client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1830,6 +2019,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ImageAnnotatorClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_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 index 10fc690e..6ae3f37b 100644 --- a/tests/unit/gapic/vision_v1/test_product_search.py +++ b/tests/unit/gapic/vision_v1/test_product_search.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,29 +23,59 @@ 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 exceptions as core_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 import credentials as ga_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.services.product_search.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.vision_v1.services.product_search.transports.base import ( + _GOOGLE_AUTH_VERSION, +) 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 +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -97,7 +126,7 @@ def test__get_default_mtls_endpoint(): "client_class", [ProductSearchClient, ProductSearchAsyncClient,] ) def test_product_search_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -114,7 +143,7 @@ def test_product_search_client_from_service_account_info(client_class): "client_class", [ProductSearchClient, ProductSearchAsyncClient,] ) def test_product_search_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -167,7 +196,7 @@ def test_product_search_client_client_options( ): # 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()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -455,7 +484,7 @@ def test_create_product_set( transport: str = "grpc", request_type=product_search_service.CreateProductSetRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -470,21 +499,16 @@ def test_create_product_set( 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" @@ -496,7 +520,7 @@ def test_create_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -506,7 +530,6 @@ def test_create_product_set_empty_call(): client.create_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.CreateProductSetRequest() @@ -516,7 +539,7 @@ async def test_create_product_set_async( request_type=product_search_service.CreateProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -533,20 +556,16 @@ async def test_create_product_set_async( 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] == 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" @@ -556,11 +575,12 @@ async def test_create_product_set_async_from_dict(): def test_create_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -568,7 +588,6 @@ def test_create_product_set_field_headers(): 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. @@ -583,11 +602,14 @@ def test_create_product_set_field_headers(): @pytest.mark.asyncio async def test_create_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -597,7 +619,6 @@ async def test_create_product_set_field_headers_async(): 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. @@ -611,7 +632,7 @@ async def test_create_product_set_field_headers_async(): def test_create_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -619,7 +640,6 @@ def test_create_product_set_flattened(): ) 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( @@ -632,18 +652,15 @@ def test_create_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -658,7 +675,9 @@ def test_create_product_set_flattened_error(): @pytest.mark.asyncio async def test_create_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -682,19 +701,18 @@ async def test_create_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -711,7 +729,7 @@ def test_list_product_sets( transport: str = "grpc", request_type=product_search_service.ListProductSetsRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -726,19 +744,15 @@ def test_list_product_sets( 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" @@ -750,7 +764,7 @@ def test_list_product_sets_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -760,7 +774,6 @@ def test_list_product_sets_empty_call(): client.list_product_sets() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.ListProductSetsRequest() @@ -770,7 +783,7 @@ async def test_list_product_sets_async( request_type=product_search_service.ListProductSetsRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -787,18 +800,15 @@ async def test_list_product_sets_async( 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] == product_search_service.ListProductSetsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductSetsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -808,11 +818,12 @@ async def test_list_product_sets_async_from_dict(): def test_list_product_sets_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -820,7 +831,6 @@ def test_list_product_sets_field_headers(): 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. @@ -835,11 +845,14 @@ def test_list_product_sets_field_headers(): @pytest.mark.asyncio async def test_list_product_sets_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -849,7 +862,6 @@ async def test_list_product_sets_field_headers_async(): 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. @@ -863,7 +875,7 @@ async def test_list_product_sets_field_headers_async(): def test_list_product_sets_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -871,7 +883,6 @@ def test_list_product_sets_flattened(): ) 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",) @@ -880,12 +891,11 @@ def test_list_product_sets_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -897,7 +907,9 @@ def test_list_product_sets_flattened_error(): @pytest.mark.asyncio async def test_list_product_sets_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -917,13 +929,14 @@ async def test_list_product_sets_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -934,7 +947,7 @@ async def test_list_product_sets_flattened_error_async(): def test_list_product_sets_pager(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -980,7 +993,7 @@ def test_list_product_sets_pager(): def test_list_product_sets_pages(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1018,7 +1031,7 @@ def test_list_product_sets_pages(): @pytest.mark.asyncio async def test_list_product_sets_async_pager(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1063,7 +1076,7 @@ async def test_list_product_sets_async_pager(): @pytest.mark.asyncio async def test_list_product_sets_async_pages(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1107,7 +1120,7 @@ def test_get_product_set( transport: str = "grpc", request_type=product_search_service.GetProductSetRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1120,21 +1133,16 @@ def test_get_product_set( 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" @@ -1146,7 +1154,7 @@ def test_get_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1154,7 +1162,6 @@ def test_get_product_set_empty_call(): client.get_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.GetProductSetRequest() @@ -1164,7 +1171,7 @@ async def test_get_product_set_async( request_type=product_search_service.GetProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1179,20 +1186,16 @@ async def test_get_product_set_async( 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] == 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" @@ -1202,17 +1205,17 @@ async def test_get_product_set_async_from_dict(): def test_get_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -1227,11 +1230,14 @@ def test_get_product_set_field_headers(): @pytest.mark.asyncio async def test_get_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -1239,7 +1245,6 @@ async def test_get_product_set_field_headers_async(): 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. @@ -1253,13 +1258,12 @@ async def test_get_product_set_field_headers_async(): def test_get_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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",) @@ -1268,12 +1272,11 @@ def test_get_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1285,7 +1288,9 @@ def test_get_product_set_flattened_error(): @pytest.mark.asyncio async def test_get_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -1303,13 +1308,14 @@ async def test_get_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1323,7 +1329,7 @@ def test_update_product_set( transport: str = "grpc", request_type=product_search_service.UpdateProductSetRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1338,21 +1344,16 @@ def test_update_product_set( 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" @@ -1364,7 +1365,7 @@ def test_update_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1374,7 +1375,6 @@ def test_update_product_set_empty_call(): client.update_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.UpdateProductSetRequest() @@ -1384,7 +1384,7 @@ async def test_update_product_set_async( request_type=product_search_service.UpdateProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1401,20 +1401,16 @@ async def test_update_product_set_async( 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] == 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" @@ -1424,11 +1420,12 @@ async def test_update_product_set_async_from_dict(): def test_update_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -1436,7 +1433,6 @@ def test_update_product_set_field_headers(): 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. @@ -1453,11 +1449,14 @@ def test_update_product_set_field_headers(): @pytest.mark.asyncio async def test_update_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -1467,7 +1466,6 @@ async def test_update_product_set_field_headers_async(): 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. @@ -1483,7 +1481,7 @@ async def test_update_product_set_field_headers_async(): def test_update_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1491,28 +1489,25 @@ def test_update_product_set_flattened(): ) 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"]), + update_mask=field_mask_pb2.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"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_product_set_flattened_error(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1520,13 +1515,15 @@ def test_update_product_set_flattened_error(): 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"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1542,24 +1539,24 @@ async def test_update_product_set_flattened_async(): # 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"]), + update_mask=field_mask_pb2.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"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_product_set_flattened_error_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1567,7 +1564,7 @@ async def test_update_product_set_flattened_error_async(): 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"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1575,7 +1572,7 @@ def test_delete_product_set( transport: str = "grpc", request_type=product_search_service.DeleteProductSetRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1588,13 +1585,11 @@ def test_delete_product_set( ) 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. @@ -1609,7 +1604,7 @@ def test_delete_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1619,7 +1614,6 @@ def test_delete_product_set_empty_call(): client.delete_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.DeleteProductSetRequest() @@ -1629,7 +1623,7 @@ async def test_delete_product_set_async( request_type=product_search_service.DeleteProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1642,13 +1636,11 @@ async def test_delete_product_set_async( ) 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] == product_search_service.DeleteProductSetRequest() # Establish that the response is the type that we expect. @@ -1661,11 +1653,12 @@ async def test_delete_product_set_async_from_dict(): def test_delete_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -1673,7 +1666,6 @@ def test_delete_product_set_field_headers(): 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. @@ -1688,11 +1680,14 @@ def test_delete_product_set_field_headers(): @pytest.mark.asyncio async def test_delete_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -1700,7 +1695,6 @@ async def test_delete_product_set_field_headers_async(): type(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. @@ -1714,7 +1708,7 @@ async def test_delete_product_set_field_headers_async(): def test_delete_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1722,7 +1716,6 @@ def test_delete_product_set_flattened(): ) 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",) @@ -1731,12 +1724,11 @@ def test_delete_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1748,7 +1740,9 @@ def test_delete_product_set_flattened_error(): @pytest.mark.asyncio async def test_delete_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1766,13 +1760,14 @@ async def test_delete_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1786,7 +1781,7 @@ def test_create_product( transport: str = "grpc", request_type=product_search_service.CreateProductRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1802,25 +1797,18 @@ def test_create_product( 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" @@ -1832,7 +1820,7 @@ def test_create_product_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1840,7 +1828,6 @@ def test_create_product_empty_call(): client.create_product() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.CreateProductRequest() @@ -1850,7 +1837,7 @@ async def test_create_product_async( request_type=product_search_service.CreateProductRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1868,24 +1855,18 @@ async def test_create_product_async( 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] == 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" @@ -1895,17 +1876,17 @@ async def test_create_product_async_from_dict(): def test_create_product_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -1920,11 +1901,14 @@ def test_create_product_field_headers(): @pytest.mark.asyncio async def test_create_product_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -1932,7 +1916,6 @@ async def test_create_product_field_headers_async(): 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. @@ -1946,13 +1929,12 @@ async def test_create_product_field_headers_async(): def test_create_product_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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( @@ -1965,16 +1947,13 @@ def test_create_product_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1989,7 +1968,9 @@ def test_create_product_flattened_error(): @pytest.mark.asyncio async def test_create_product_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -2011,17 +1992,16 @@ async def test_create_product_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2038,7 +2018,7 @@ def test_list_products( transport: str = "grpc", request_type=product_search_service.ListProductsRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2051,19 +2031,15 @@ def test_list_products( 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" @@ -2075,7 +2051,7 @@ def test_list_products_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2083,7 +2059,6 @@ def test_list_products_empty_call(): client.list_products() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.ListProductsRequest() @@ -2093,7 +2068,7 @@ async def test_list_products_async( request_type=product_search_service.ListProductsRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2108,18 +2083,15 @@ async def test_list_products_async( 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] == product_search_service.ListProductsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -2129,17 +2101,17 @@ async def test_list_products_async_from_dict(): def test_list_products_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -2154,11 +2126,14 @@ def test_list_products_field_headers(): @pytest.mark.asyncio async def test_list_products_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -2166,7 +2141,6 @@ async def test_list_products_field_headers_async(): 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. @@ -2180,13 +2154,12 @@ async def test_list_products_field_headers_async(): def test_list_products_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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",) @@ -2195,12 +2168,11 @@ def test_list_products_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2212,7 +2184,9 @@ def test_list_products_flattened_error(): @pytest.mark.asyncio async def test_list_products_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -2230,13 +2204,14 @@ async def test_list_products_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2247,7 +2222,7 @@ async def test_list_products_flattened_error_async(): def test_list_products_pager(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_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: @@ -2290,7 +2265,7 @@ def test_list_products_pager(): def test_list_products_pages(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_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: @@ -2325,7 +2300,7 @@ def test_list_products_pages(): @pytest.mark.asyncio async def test_list_products_async_pager(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2367,7 +2342,7 @@ async def test_list_products_async_pager(): @pytest.mark.asyncio async def test_list_products_async_pages(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2408,7 +2383,7 @@ def test_get_product( transport: str = "grpc", request_type=product_search_service.GetProductRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2424,25 +2399,18 @@ def test_get_product( 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" @@ -2454,7 +2422,7 @@ def test_get_product_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2462,7 +2430,6 @@ def test_get_product_empty_call(): client.get_product() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.GetProductRequest() @@ -2472,7 +2439,7 @@ async def test_get_product_async( request_type=product_search_service.GetProductRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2490,24 +2457,18 @@ async def test_get_product_async( 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] == 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" @@ -2517,17 +2478,17 @@ async def test_get_product_async_from_dict(): def test_get_product_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -2542,11 +2503,14 @@ def test_get_product_field_headers(): @pytest.mark.asyncio async def test_get_product_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -2554,7 +2518,6 @@ async def test_get_product_field_headers_async(): 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. @@ -2568,13 +2531,12 @@ async def test_get_product_field_headers_async(): def test_get_product_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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",) @@ -2583,12 +2545,11 @@ def test_get_product_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2600,7 +2561,9 @@ def test_get_product_flattened_error(): @pytest.mark.asyncio async def test_get_product_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -2618,13 +2581,14 @@ async def test_get_product_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2638,7 +2602,7 @@ def test_update_product( transport: str = "grpc", request_type=product_search_service.UpdateProductRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2654,25 +2618,18 @@ def test_update_product( 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" @@ -2684,7 +2641,7 @@ def test_update_product_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2692,7 +2649,6 @@ def test_update_product_empty_call(): client.update_product() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.UpdateProductRequest() @@ -2702,7 +2658,7 @@ async def test_update_product_async( request_type=product_search_service.UpdateProductRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2720,24 +2676,18 @@ async def test_update_product_async( 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] == 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" @@ -2747,17 +2697,17 @@ async def test_update_product_async_from_dict(): def test_update_product_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -2774,11 +2724,14 @@ def test_update_product_field_headers(): @pytest.mark.asyncio async def test_update_product_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -2786,7 +2739,6 @@ async def test_update_product_field_headers_async(): 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. @@ -2802,32 +2754,29 @@ async def test_update_product_field_headers_async(): def test_update_product_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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"]), + update_mask=field_mask_pb2.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"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_product_flattened_error(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2835,13 +2784,15 @@ def test_update_product_flattened_error(): client.update_product( product_search_service.UpdateProductRequest(), product=product_search_service.Product(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_product_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -2855,22 +2806,22 @@ async def test_update_product_flattened_async(): # 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"]), + update_mask=field_mask_pb2.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"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_product_flattened_error_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2878,7 +2829,7 @@ async def test_update_product_flattened_error_async(): await client.update_product( product_search_service.UpdateProductRequest(), product=product_search_service.Product(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -2886,7 +2837,7 @@ def test_delete_product( transport: str = "grpc", request_type=product_search_service.DeleteProductRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2897,13 +2848,11 @@ def test_delete_product( 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. @@ -2918,7 +2867,7 @@ def test_delete_product_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2926,7 +2875,6 @@ def test_delete_product_empty_call(): client.delete_product() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.DeleteProductRequest() @@ -2936,7 +2884,7 @@ async def test_delete_product_async( request_type=product_search_service.DeleteProductRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2947,13 +2895,11 @@ async def test_delete_product_async( with mock.patch.object(type(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] == product_search_service.DeleteProductRequest() # Establish that the response is the type that we expect. @@ -2966,17 +2912,17 @@ async def test_delete_product_async_from_dict(): def test_delete_product_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -2991,17 +2937,19 @@ def test_delete_product_field_headers(): @pytest.mark.asyncio async def test_delete_product_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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 = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_product(request) # Establish that the underlying gRPC stub method was called. @@ -3015,13 +2963,12 @@ async def test_delete_product_field_headers_async(): def test_delete_product_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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",) @@ -3030,12 +2977,11 @@ def test_delete_product_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3047,7 +2993,9 @@ def test_delete_product_flattened_error(): @pytest.mark.asyncio async def test_delete_product_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -3063,13 +3011,14 @@ async def test_delete_product_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3084,7 +3033,7 @@ def test_create_reference_image( request_type=product_search_service.CreateReferenceImageRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3099,21 +3048,16 @@ def test_create_reference_image( 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" @@ -3125,7 +3069,7 @@ def test_create_reference_image_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3135,7 +3079,6 @@ def test_create_reference_image_empty_call(): client.create_reference_image() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.CreateReferenceImageRequest() @@ -3145,7 +3088,7 @@ async def test_create_reference_image_async( request_type=product_search_service.CreateReferenceImageRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3160,20 +3103,16 @@ async def test_create_reference_image_async( 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] == 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" @@ -3183,11 +3122,12 @@ async def test_create_reference_image_async_from_dict(): def test_create_reference_image_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -3195,7 +3135,6 @@ def test_create_reference_image_field_headers(): 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. @@ -3210,11 +3149,14 @@ def test_create_reference_image_field_headers(): @pytest.mark.asyncio async def test_create_reference_image_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -3224,7 +3166,6 @@ async def test_create_reference_image_field_headers_async(): 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. @@ -3238,7 +3179,7 @@ async def test_create_reference_image_field_headers_async(): def test_create_reference_image_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3246,7 +3187,6 @@ def test_create_reference_image_flattened(): ) 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( @@ -3259,18 +3199,15 @@ def test_create_reference_image_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3285,7 +3222,9 @@ def test_create_reference_image_flattened_error(): @pytest.mark.asyncio async def test_create_reference_image_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3309,19 +3248,18 @@ async def test_create_reference_image_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3339,7 +3277,7 @@ def test_delete_reference_image( request_type=product_search_service.DeleteReferenceImageRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3352,13 +3290,11 @@ def test_delete_reference_image( ) 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. @@ -3373,7 +3309,7 @@ def test_delete_reference_image_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3383,7 +3319,6 @@ def test_delete_reference_image_empty_call(): client.delete_reference_image() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.DeleteReferenceImageRequest() @@ -3393,7 +3328,7 @@ async def test_delete_reference_image_async( request_type=product_search_service.DeleteReferenceImageRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3406,13 +3341,11 @@ async def test_delete_reference_image_async( ) 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] == product_search_service.DeleteReferenceImageRequest() # Establish that the response is the type that we expect. @@ -3425,11 +3358,12 @@ async def test_delete_reference_image_async_from_dict(): def test_delete_reference_image_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -3437,7 +3371,6 @@ def test_delete_reference_image_field_headers(): 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. @@ -3452,11 +3385,14 @@ def test_delete_reference_image_field_headers(): @pytest.mark.asyncio async def test_delete_reference_image_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -3464,7 +3400,6 @@ async def test_delete_reference_image_field_headers_async(): type(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. @@ -3478,7 +3413,7 @@ async def test_delete_reference_image_field_headers_async(): def test_delete_reference_image_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3486,7 +3421,6 @@ def test_delete_reference_image_flattened(): ) 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",) @@ -3495,12 +3429,11 @@ def test_delete_reference_image_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3512,7 +3445,9 @@ def test_delete_reference_image_flattened_error(): @pytest.mark.asyncio async def test_delete_reference_image_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3530,13 +3465,14 @@ async def test_delete_reference_image_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3551,7 +3487,7 @@ def test_list_reference_images( request_type=product_search_service.ListReferenceImagesRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3566,21 +3502,16 @@ def test_list_reference_images( 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" @@ -3592,7 +3523,7 @@ def test_list_reference_images_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3602,7 +3533,6 @@ def test_list_reference_images_empty_call(): client.list_reference_images() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.ListReferenceImagesRequest() @@ -3612,7 +3542,7 @@ async def test_list_reference_images_async( request_type=product_search_service.ListReferenceImagesRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3629,20 +3559,16 @@ async def test_list_reference_images_async( 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] == product_search_service.ListReferenceImagesRequest() # 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" @@ -3652,11 +3578,12 @@ async def test_list_reference_images_async_from_dict(): def test_list_reference_images_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -3664,7 +3591,6 @@ def test_list_reference_images_field_headers(): 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. @@ -3679,11 +3605,14 @@ def test_list_reference_images_field_headers(): @pytest.mark.asyncio async def test_list_reference_images_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -3693,7 +3622,6 @@ async def test_list_reference_images_field_headers_async(): 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. @@ -3707,7 +3635,7 @@ async def test_list_reference_images_field_headers_async(): def test_list_reference_images_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3715,7 +3643,6 @@ def test_list_reference_images_flattened(): ) 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",) @@ -3724,12 +3651,11 @@ def test_list_reference_images_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3741,7 +3667,9 @@ def test_list_reference_images_flattened_error(): @pytest.mark.asyncio async def test_list_reference_images_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3761,13 +3689,14 @@ async def test_list_reference_images_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3778,7 +3707,7 @@ async def test_list_reference_images_flattened_error_async(): def test_list_reference_images_pager(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3826,7 +3755,7 @@ def test_list_reference_images_pager(): def test_list_reference_images_pages(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3864,7 +3793,7 @@ def test_list_reference_images_pages(): @pytest.mark.asyncio async def test_list_reference_images_async_pager(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3911,7 +3840,7 @@ async def test_list_reference_images_async_pager(): @pytest.mark.asyncio async def test_list_reference_images_async_pages(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3956,7 +3885,7 @@ def test_get_reference_image( request_type=product_search_service.GetReferenceImageRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3971,21 +3900,16 @@ def test_get_reference_image( 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" @@ -3997,7 +3921,7 @@ def test_get_reference_image_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4007,7 +3931,6 @@ def test_get_reference_image_empty_call(): client.get_reference_image() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.GetReferenceImageRequest() @@ -4017,7 +3940,7 @@ async def test_get_reference_image_async( request_type=product_search_service.GetReferenceImageRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4032,20 +3955,16 @@ async def test_get_reference_image_async( 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] == 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" @@ -4055,11 +3974,12 @@ async def test_get_reference_image_async_from_dict(): def test_get_reference_image_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -4067,7 +3987,6 @@ def test_get_reference_image_field_headers(): 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. @@ -4082,11 +4001,14 @@ def test_get_reference_image_field_headers(): @pytest.mark.asyncio async def test_get_reference_image_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -4096,7 +4018,6 @@ async def test_get_reference_image_field_headers_async(): 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. @@ -4110,7 +4031,7 @@ async def test_get_reference_image_field_headers_async(): def test_get_reference_image_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4118,7 +4039,6 @@ def test_get_reference_image_flattened(): ) 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",) @@ -4127,12 +4047,11 @@ def test_get_reference_image_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4144,7 +4063,9 @@ def test_get_reference_image_flattened_error(): @pytest.mark.asyncio async def test_get_reference_image_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4164,13 +4085,14 @@ async def test_get_reference_image_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4185,7 +4107,7 @@ def test_add_product_to_product_set( request_type=product_search_service.AddProductToProductSetRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4198,13 +4120,11 @@ def test_add_product_to_product_set( ) 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. @@ -4219,7 +4139,7 @@ def test_add_product_to_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4229,7 +4149,6 @@ def test_add_product_to_product_set_empty_call(): client.add_product_to_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.AddProductToProductSetRequest() @@ -4239,7 +4158,7 @@ async def test_add_product_to_product_set_async( request_type=product_search_service.AddProductToProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4252,13 +4171,11 @@ async def test_add_product_to_product_set_async( ) 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] == product_search_service.AddProductToProductSetRequest() # Establish that the response is the type that we expect. @@ -4271,11 +4188,12 @@ async def test_add_product_to_product_set_async_from_dict(): def test_add_product_to_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -4283,7 +4201,6 @@ def test_add_product_to_product_set_field_headers(): 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. @@ -4298,11 +4215,14 @@ def test_add_product_to_product_set_field_headers(): @pytest.mark.asyncio async def test_add_product_to_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -4310,7 +4230,6 @@ async def test_add_product_to_product_set_field_headers_async(): type(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. @@ -4324,7 +4243,7 @@ async def test_add_product_to_product_set_field_headers_async(): def test_add_product_to_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4332,7 +4251,6 @@ def test_add_product_to_product_set_flattened(): ) 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( @@ -4343,14 +4261,12 @@ def test_add_product_to_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4364,7 +4280,9 @@ def test_add_product_to_product_set_flattened_error(): @pytest.mark.asyncio async def test_add_product_to_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4384,15 +4302,15 @@ async def test_add_product_to_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4409,7 +4327,7 @@ def test_remove_product_from_product_set( request_type=product_search_service.RemoveProductFromProductSetRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4422,13 +4340,11 @@ def test_remove_product_from_product_set( ) 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. @@ -4443,7 +4359,7 @@ def test_remove_product_from_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4453,7 +4369,6 @@ def test_remove_product_from_product_set_empty_call(): client.remove_product_from_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.RemoveProductFromProductSetRequest() @@ -4463,7 +4378,7 @@ async def test_remove_product_from_product_set_async( request_type=product_search_service.RemoveProductFromProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4476,13 +4391,11 @@ async def test_remove_product_from_product_set_async( ) 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] == product_search_service.RemoveProductFromProductSetRequest() # Establish that the response is the type that we expect. @@ -4495,11 +4408,12 @@ async def test_remove_product_from_product_set_async_from_dict(): def test_remove_product_from_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -4507,7 +4421,6 @@ def test_remove_product_from_product_set_field_headers(): 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. @@ -4522,11 +4435,14 @@ def test_remove_product_from_product_set_field_headers(): @pytest.mark.asyncio async def test_remove_product_from_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -4534,7 +4450,6 @@ async def test_remove_product_from_product_set_field_headers_async(): type(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. @@ -4548,7 +4463,7 @@ async def test_remove_product_from_product_set_field_headers_async(): def test_remove_product_from_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4556,7 +4471,6 @@ def test_remove_product_from_product_set_flattened(): ) 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( @@ -4567,14 +4481,12 @@ def test_remove_product_from_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4588,7 +4500,9 @@ def test_remove_product_from_product_set_flattened_error(): @pytest.mark.asyncio async def test_remove_product_from_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4608,15 +4522,15 @@ async def test_remove_product_from_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4633,7 +4547,7 @@ def test_list_products_in_product_set( request_type=product_search_service.ListProductsInProductSetRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4648,19 +4562,15 @@ def test_list_products_in_product_set( 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" @@ -4672,7 +4582,7 @@ def test_list_products_in_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4682,7 +4592,6 @@ def test_list_products_in_product_set_empty_call(): client.list_products_in_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.ListProductsInProductSetRequest() @@ -4692,7 +4601,7 @@ async def test_list_products_in_product_set_async( request_type=product_search_service.ListProductsInProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4709,18 +4618,15 @@ async def test_list_products_in_product_set_async( 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] == product_search_service.ListProductsInProductSetRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsInProductSetAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -4730,11 +4636,12 @@ async def test_list_products_in_product_set_async_from_dict(): def test_list_products_in_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -4742,7 +4649,6 @@ def test_list_products_in_product_set_field_headers(): 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. @@ -4757,11 +4663,14 @@ def test_list_products_in_product_set_field_headers(): @pytest.mark.asyncio async def test_list_products_in_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -4771,7 +4680,6 @@ async def test_list_products_in_product_set_field_headers_async(): 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. @@ -4785,7 +4693,7 @@ async def test_list_products_in_product_set_field_headers_async(): def test_list_products_in_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4793,7 +4701,6 @@ def test_list_products_in_product_set_flattened(): ) 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",) @@ -4802,12 +4709,11 @@ def test_list_products_in_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4819,7 +4725,9 @@ def test_list_products_in_product_set_flattened_error(): @pytest.mark.asyncio async def test_list_products_in_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4839,13 +4747,14 @@ async def test_list_products_in_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4856,7 +4765,7 @@ async def test_list_products_in_product_set_flattened_error_async(): def test_list_products_in_product_set_pager(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4901,7 +4810,7 @@ def test_list_products_in_product_set_pager(): def test_list_products_in_product_set_pages(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4938,7 +4847,7 @@ def test_list_products_in_product_set_pages(): @pytest.mark.asyncio async def test_list_products_in_product_set_async_pager(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4982,7 +4891,7 @@ async def test_list_products_in_product_set_async_pager(): @pytest.mark.asyncio async def test_list_products_in_product_set_async_pages(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -5028,7 +4937,7 @@ def test_import_product_sets( request_type=product_search_service.ImportProductSetsRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5041,13 +4950,11 @@ def test_import_product_sets( ) 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. @@ -5062,7 +4969,7 @@ def test_import_product_sets_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5072,7 +4979,6 @@ def test_import_product_sets_empty_call(): client.import_product_sets() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.ImportProductSetsRequest() @@ -5082,7 +4988,7 @@ async def test_import_product_sets_async( request_type=product_search_service.ImportProductSetsRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5097,13 +5003,11 @@ async def test_import_product_sets_async( 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] == product_search_service.ImportProductSetsRequest() # Establish that the response is the type that we expect. @@ -5116,11 +5020,12 @@ async def test_import_product_sets_async_from_dict(): def test_import_product_sets_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -5128,7 +5033,6 @@ def test_import_product_sets_field_headers(): 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. @@ -5143,11 +5047,14 @@ def test_import_product_sets_field_headers(): @pytest.mark.asyncio async def test_import_product_sets_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -5157,7 +5064,6 @@ async def test_import_product_sets_field_headers_async(): 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. @@ -5171,7 +5077,7 @@ async def test_import_product_sets_field_headers_async(): def test_import_product_sets_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -5179,7 +5085,6 @@ def test_import_product_sets_flattened(): ) 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( @@ -5195,9 +5100,7 @@ def test_import_product_sets_flattened(): # 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( @@ -5208,7 +5111,7 @@ def test_import_product_sets_flattened(): def test_import_product_sets_flattened_error(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5226,7 +5129,9 @@ def test_import_product_sets_flattened_error(): @pytest.mark.asyncio async def test_import_product_sets_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -5253,9 +5158,7 @@ async def test_import_product_sets_flattened_async(): # 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( @@ -5267,7 +5170,9 @@ async def test_import_product_sets_flattened_async(): @pytest.mark.asyncio async def test_import_product_sets_flattened_error_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5287,7 +5192,7 @@ def test_purge_products( transport: str = "grpc", request_type=product_search_service.PurgeProductsRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5298,13 +5203,11 @@ def test_purge_products( 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. @@ -5319,7 +5222,7 @@ def test_purge_products_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5327,7 +5230,6 @@ def test_purge_products_empty_call(): client.purge_products() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.PurgeProductsRequest() @@ -5337,7 +5239,7 @@ async def test_purge_products_async( request_type=product_search_service.PurgeProductsRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5350,13 +5252,11 @@ async def test_purge_products_async( 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] == product_search_service.PurgeProductsRequest() # Establish that the response is the type that we expect. @@ -5369,17 +5269,17 @@ async def test_purge_products_async_from_dict(): def test_purge_products_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -5394,11 +5294,14 @@ def test_purge_products_field_headers(): @pytest.mark.asyncio async def test_purge_products_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -5406,7 +5309,6 @@ async def test_purge_products_field_headers_async(): 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. @@ -5420,13 +5322,12 @@ async def test_purge_products_field_headers_async(): def test_purge_products_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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",) @@ -5435,12 +5336,11 @@ def test_purge_products_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5452,7 +5352,9 @@ def test_purge_products_flattened_error(): @pytest.mark.asyncio async def test_purge_products_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -5470,13 +5372,14 @@ async def test_purge_products_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5489,16 +5392,16 @@ async def test_purge_products_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ProductSearchGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ProductSearchGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ProductSearchClient( @@ -5508,7 +5411,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ProductSearchGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ProductSearchClient( @@ -5519,7 +5422,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ProductSearchGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ProductSearchClient(transport=transport) assert client.transport is transport @@ -5528,13 +5431,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ProductSearchGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ProductSearchGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -5549,23 +5452,23 @@ def test_transport_get_channel(): ) 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) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_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(),) + client = ProductSearchClient(credentials=ga_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): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ProductSearchTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -5577,7 +5480,7 @@ def test_product_search_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ProductSearchTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -5613,15 +5516,40 @@ def test_product_search_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 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" + google.auth, "load_credentials_from_file", autospec=True ) 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) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductSearchTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_product_search_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) 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 = (ga_credentials.AnonymousCredentials(), None) transport = transports.ProductSearchTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -5637,19 +5565,36 @@ def test_product_search_base_transport_with_credentials_file(): 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( + with mock.patch.object(google.auth, "default", autospec=True) 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) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ProductSearchTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 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) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ProductSearchClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_product_search_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) ProductSearchClient() adc.assert_called_once_with( scopes=( @@ -5660,14 +5605,44 @@ def test_product_search_auth_adc(): ) -def test_product_search_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_product_search_transport_auth_adc(transport_class): # 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" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_product_search_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -5677,6 +5652,121 @@ def test_product_search_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ProductSearchGrpcTransport, grpc_helpers), + (transports.ProductSearchGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_product_search_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + scopes=["1", "2"], + default_host="vision.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ProductSearchGrpcTransport, grpc_helpers), + (transports.ProductSearchGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_product_search_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ProductSearchGrpcTransport, grpc_helpers), + (transports.ProductSearchGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_product_search_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -5685,7 +5775,7 @@ def test_product_search_transport_auth_adc(): ], ) def test_product_search_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -5727,7 +5817,7 @@ def test_product_search_grpc_transport_client_cert_source_for_mtls(transport_cla def test_product_search_host_no_port(): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="vision.googleapis.com" ), @@ -5737,7 +5827,7 @@ def test_product_search_host_no_port(): def test_product_search_host_with_port(): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="vision.googleapis.com:8000" ), @@ -5791,9 +5881,9 @@ def test_product_search_transport_channel_mtls_with_client_cert_source(transport mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -5875,7 +5965,7 @@ def test_product_search_transport_channel_mtls_with_adc(transport_class): def test_product_search_grpc_lro_client(): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -5888,7 +5978,7 @@ def test_product_search_grpc_lro_client(): def test_product_search_grpc_lro_async_client(): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -5903,7 +5993,6 @@ def test_product_path(): project = "squid" location = "clam" product = "whelk" - expected = "projects/{project}/locations/{location}/products/{product}".format( project=project, location=location, product=product, ) @@ -5928,7 +6017,6 @@ def test_product_set_path(): project = "cuttlefish" location = "mussel" product_set = "winkle" - expected = "projects/{project}/locations/{location}/productSets/{product_set}".format( project=project, location=location, product_set=product_set, ) @@ -5954,7 +6042,6 @@ def test_reference_image_path(): location = "clam" product = "whelk" reference_image = "octopus" - expected = "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( project=project, location=location, @@ -5983,7 +6070,6 @@ def test_parse_reference_image_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -6004,7 +6090,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = ProductSearchClient.common_folder_path(folder) assert expected == actual @@ -6023,7 +6108,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = ProductSearchClient.common_organization_path(organization) assert expected == actual @@ -6042,7 +6126,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = ProductSearchClient.common_project_path(project) assert expected == actual @@ -6062,7 +6145,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -6089,7 +6171,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ProductSearchTransport, "_prep_wrapped_messages" ) as prep: client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -6098,6 +6180,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ProductSearchClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_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 index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/vision_v1p1beta1/__init__.py +++ b/tests/unit/gapic/vision_v1p1beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/vision_v1p1beta1/test_image_annotator.py b/tests/unit/gapic/vision_v1p1beta1/test_image_annotator.py index 8f0d08ea..f975c65d 100644 --- a/tests/unit/gapic/vision_v1p1beta1/test_image_annotator.py +++ b/tests/unit/gapic/vision_v1p1beta1/test_image_annotator.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,22 +23,52 @@ 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 exceptions as core_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 import credentials as ga_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.services.image_annotator.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.vision_v1p1beta1.services.image_annotator.transports.base import ( + _GOOGLE_AUTH_VERSION, +) 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 +from google.type import latlng_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -90,7 +119,7 @@ def test__get_default_mtls_endpoint(): "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient,] ) def test_image_annotator_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -107,7 +136,7 @@ def test_image_annotator_client_from_service_account_info(client_class): "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient,] ) def test_image_annotator_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -160,7 +189,7 @@ def test_image_annotator_client_client_options( ): # 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()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -448,7 +477,7 @@ def test_batch_annotate_images( transport: str = "grpc", request_type=image_annotator.BatchAnnotateImagesRequest ): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -461,17 +490,14 @@ def test_batch_annotate_images( ) 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) @@ -483,7 +509,7 @@ def test_batch_annotate_images_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -493,7 +519,6 @@ def test_batch_annotate_images_empty_call(): client.batch_annotate_images() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.BatchAnnotateImagesRequest() @@ -503,7 +528,7 @@ async def test_batch_annotate_images_async( request_type=image_annotator.BatchAnnotateImagesRequest, ): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -518,13 +543,11 @@ async def test_batch_annotate_images_async( 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] == image_annotator.BatchAnnotateImagesRequest() # Establish that the response is the type that we expect. @@ -537,7 +560,7 @@ async def test_batch_annotate_images_async_from_dict(): def test_batch_annotate_images_flattened(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -545,7 +568,6 @@ def test_batch_annotate_images_flattened(): ) 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( @@ -560,7 +582,6 @@ def test_batch_annotate_images_flattened(): # 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") @@ -569,7 +590,7 @@ def test_batch_annotate_images_flattened(): def test_batch_annotate_images_flattened_error(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -586,7 +607,9 @@ def test_batch_annotate_images_flattened_error(): @pytest.mark.asyncio async def test_batch_annotate_images_flattened_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -612,7 +635,6 @@ async def test_batch_annotate_images_flattened_async(): # 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") @@ -622,7 +644,9 @@ async def test_batch_annotate_images_flattened_async(): @pytest.mark.asyncio async def test_batch_annotate_images_flattened_error_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -640,16 +664,16 @@ async def test_batch_annotate_images_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImageAnnotatorClient( @@ -659,7 +683,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImageAnnotatorClient( @@ -670,7 +694,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ImageAnnotatorClient(transport=transport) assert client.transport is transport @@ -679,13 +703,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ImageAnnotatorGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -700,23 +724,23 @@ def test_transport_get_channel(): ) 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) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_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(),) + client = ImageAnnotatorClient(credentials=ga_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): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ImageAnnotatorTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -728,7 +752,7 @@ def test_image_annotator_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ImageAnnotatorTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -739,15 +763,40 @@ def test_image_annotator_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 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" + google.auth, "load_credentials_from_file", autospec=True + ) 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 = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ImageAnnotatorTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_image_annotator_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) 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) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -763,19 +812,36 @@ def test_image_annotator_base_transport_with_credentials_file(): 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( + with mock.patch.object(google.auth, "default", autospec=True) 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) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 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) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ImageAnnotatorClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_image_annotator_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) ImageAnnotatorClient() adc.assert_called_once_with( scopes=( @@ -786,14 +852,44 @@ def test_image_annotator_auth_adc(): ) -def test_image_annotator_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_image_annotator_transport_auth_adc(transport_class): # 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" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_image_annotator_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -803,6 +899,121 @@ def test_image_annotator_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ImageAnnotatorGrpcTransport, grpc_helpers), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_image_annotator_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + scopes=["1", "2"], + default_host="vision.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ImageAnnotatorGrpcTransport, grpc_helpers), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_image_annotator_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ImageAnnotatorGrpcTransport, grpc_helpers), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_image_annotator_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -811,7 +1022,7 @@ def test_image_annotator_transport_auth_adc(): ], ) def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -853,7 +1064,7 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_cl def test_image_annotator_host_no_port(): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="vision.googleapis.com" ), @@ -863,7 +1074,7 @@ def test_image_annotator_host_no_port(): def test_image_annotator_host_with_port(): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="vision.googleapis.com:8000" ), @@ -919,9 +1130,9 @@ def test_image_annotator_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1003,7 +1214,6 @@ def test_image_annotator_transport_channel_mtls_with_adc(transport_class): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1024,7 +1234,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = ImageAnnotatorClient.common_folder_path(folder) assert expected == actual @@ -1043,7 +1252,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = ImageAnnotatorClient.common_organization_path(organization) assert expected == actual @@ -1062,7 +1270,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = ImageAnnotatorClient.common_project_path(project) assert expected == actual @@ -1082,7 +1289,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1109,7 +1315,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ImageAnnotatorTransport, "_prep_wrapped_messages" ) as prep: client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1118,6 +1324,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ImageAnnotatorClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_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 index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/vision_v1p2beta1/__init__.py +++ b/tests/unit/gapic/vision_v1p2beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/vision_v1p2beta1/test_image_annotator.py b/tests/unit/gapic/vision_v1p2beta1/test_image_annotator.py index 67edd39f..e0de801a 100644 --- a/tests/unit/gapic/vision_v1p2beta1/test_image_annotator.py +++ b/tests/unit/gapic/vision_v1p2beta1/test_image_annotator.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,26 +23,56 @@ 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 exceptions as core_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 import credentials as ga_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.services.image_annotator.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.vision_v1p2beta1.services.image_annotator.transports.base import ( + _GOOGLE_AUTH_VERSION, +) 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 +from google.type import latlng_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -94,7 +123,7 @@ def test__get_default_mtls_endpoint(): "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient,] ) def test_image_annotator_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -111,7 +140,7 @@ def test_image_annotator_client_from_service_account_info(client_class): "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient,] ) def test_image_annotator_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -164,7 +193,7 @@ def test_image_annotator_client_client_options( ): # 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()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -452,7 +481,7 @@ def test_batch_annotate_images( transport: str = "grpc", request_type=image_annotator.BatchAnnotateImagesRequest ): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -465,17 +494,14 @@ def test_batch_annotate_images( ) 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) @@ -487,7 +513,7 @@ def test_batch_annotate_images_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -497,7 +523,6 @@ def test_batch_annotate_images_empty_call(): client.batch_annotate_images() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.BatchAnnotateImagesRequest() @@ -507,7 +532,7 @@ async def test_batch_annotate_images_async( request_type=image_annotator.BatchAnnotateImagesRequest, ): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -522,13 +547,11 @@ async def test_batch_annotate_images_async( 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] == image_annotator.BatchAnnotateImagesRequest() # Establish that the response is the type that we expect. @@ -541,7 +564,7 @@ async def test_batch_annotate_images_async_from_dict(): def test_batch_annotate_images_flattened(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -549,7 +572,6 @@ def test_batch_annotate_images_flattened(): ) 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( @@ -564,7 +586,6 @@ def test_batch_annotate_images_flattened(): # 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") @@ -573,7 +594,7 @@ def test_batch_annotate_images_flattened(): def test_batch_annotate_images_flattened_error(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -590,7 +611,9 @@ def test_batch_annotate_images_flattened_error(): @pytest.mark.asyncio async def test_batch_annotate_images_flattened_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -616,7 +639,6 @@ async def test_batch_annotate_images_flattened_async(): # 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") @@ -626,7 +648,9 @@ async def test_batch_annotate_images_flattened_async(): @pytest.mark.asyncio async def test_batch_annotate_images_flattened_error_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -645,7 +669,7 @@ def test_async_batch_annotate_files( transport: str = "grpc", request_type=image_annotator.AsyncBatchAnnotateFilesRequest ): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -658,13 +682,11 @@ def test_async_batch_annotate_files( ) 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. @@ -679,7 +701,7 @@ def test_async_batch_annotate_files_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -689,7 +711,6 @@ def test_async_batch_annotate_files_empty_call(): client.async_batch_annotate_files() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.AsyncBatchAnnotateFilesRequest() @@ -699,7 +720,7 @@ async def test_async_batch_annotate_files_async( request_type=image_annotator.AsyncBatchAnnotateFilesRequest, ): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -714,13 +735,11 @@ async def test_async_batch_annotate_files_async( 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] == image_annotator.AsyncBatchAnnotateFilesRequest() # Establish that the response is the type that we expect. @@ -733,7 +752,7 @@ async def test_async_batch_annotate_files_async_from_dict(): def test_async_batch_annotate_files_flattened(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -741,7 +760,6 @@ def test_async_batch_annotate_files_flattened(): ) 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( @@ -758,7 +776,6 @@ def test_async_batch_annotate_files_flattened(): # 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( @@ -769,7 +786,7 @@ def test_async_batch_annotate_files_flattened(): def test_async_batch_annotate_files_flattened_error(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -788,7 +805,9 @@ def test_async_batch_annotate_files_flattened_error(): @pytest.mark.asyncio async def test_async_batch_annotate_files_flattened_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -816,7 +835,6 @@ async def test_async_batch_annotate_files_flattened_async(): # 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( @@ -828,7 +846,9 @@ async def test_async_batch_annotate_files_flattened_async(): @pytest.mark.asyncio async def test_async_batch_annotate_files_flattened_error_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -848,16 +868,16 @@ async def test_async_batch_annotate_files_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImageAnnotatorClient( @@ -867,7 +887,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImageAnnotatorClient( @@ -878,7 +898,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ImageAnnotatorClient(transport=transport) assert client.transport is transport @@ -887,13 +907,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ImageAnnotatorGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -908,23 +928,23 @@ def test_transport_get_channel(): ) 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) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_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(),) + client = ImageAnnotatorClient(credentials=ga_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): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ImageAnnotatorTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -936,7 +956,7 @@ def test_image_annotator_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ImageAnnotatorTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -955,15 +975,40 @@ def test_image_annotator_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 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" + google.auth, "load_credentials_from_file", autospec=True + ) 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 = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ImageAnnotatorTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_image_annotator_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) 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) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -979,19 +1024,36 @@ def test_image_annotator_base_transport_with_credentials_file(): 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( + with mock.patch.object(google.auth, "default", autospec=True) 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) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 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) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ImageAnnotatorClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_image_annotator_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) ImageAnnotatorClient() adc.assert_called_once_with( scopes=( @@ -1002,14 +1064,44 @@ def test_image_annotator_auth_adc(): ) -def test_image_annotator_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_image_annotator_transport_auth_adc(transport_class): # 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" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_image_annotator_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -1019,6 +1111,121 @@ def test_image_annotator_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ImageAnnotatorGrpcTransport, grpc_helpers), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_image_annotator_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + scopes=["1", "2"], + default_host="vision.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ImageAnnotatorGrpcTransport, grpc_helpers), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_image_annotator_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ImageAnnotatorGrpcTransport, grpc_helpers), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_image_annotator_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1027,7 +1234,7 @@ def test_image_annotator_transport_auth_adc(): ], ) def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1069,7 +1276,7 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_cl def test_image_annotator_host_no_port(): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="vision.googleapis.com" ), @@ -1079,7 +1286,7 @@ def test_image_annotator_host_no_port(): def test_image_annotator_host_with_port(): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="vision.googleapis.com:8000" ), @@ -1135,9 +1342,9 @@ def test_image_annotator_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1219,7 +1426,7 @@ def test_image_annotator_transport_channel_mtls_with_adc(transport_class): def test_image_annotator_grpc_lro_client(): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -1232,7 +1439,7 @@ def test_image_annotator_grpc_lro_client(): def test_image_annotator_grpc_lro_async_client(): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -1245,7 +1452,6 @@ def test_image_annotator_grpc_lro_async_client(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1266,7 +1472,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = ImageAnnotatorClient.common_folder_path(folder) assert expected == actual @@ -1285,7 +1490,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = ImageAnnotatorClient.common_organization_path(organization) assert expected == actual @@ -1304,7 +1508,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = ImageAnnotatorClient.common_project_path(project) assert expected == actual @@ -1324,7 +1527,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1351,7 +1553,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ImageAnnotatorTransport, "_prep_wrapped_messages" ) as prep: client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1360,6 +1562,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ImageAnnotatorClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_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 index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/vision_v1p3beta1/__init__.py +++ b/tests/unit/gapic/vision_v1p3beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/vision_v1p3beta1/test_image_annotator.py b/tests/unit/gapic/vision_v1p3beta1/test_image_annotator.py index acf7e0d0..75218f56 100644 --- a/tests/unit/gapic/vision_v1p3beta1/test_image_annotator.py +++ b/tests/unit/gapic/vision_v1p3beta1/test_image_annotator.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,28 +23,58 @@ 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 exceptions as core_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 import credentials as ga_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.services.image_annotator.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.vision_v1p3beta1.services.image_annotator.transports.base import ( + _GOOGLE_AUTH_VERSION, +) 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 +from google.type import latlng_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -96,7 +125,7 @@ def test__get_default_mtls_endpoint(): "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient,] ) def test_image_annotator_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -113,7 +142,7 @@ def test_image_annotator_client_from_service_account_info(client_class): "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient,] ) def test_image_annotator_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -166,7 +195,7 @@ def test_image_annotator_client_client_options( ): # 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()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -454,7 +483,7 @@ def test_batch_annotate_images( transport: str = "grpc", request_type=image_annotator.BatchAnnotateImagesRequest ): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -467,17 +496,14 @@ def test_batch_annotate_images( ) 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) @@ -489,7 +515,7 @@ def test_batch_annotate_images_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -499,7 +525,6 @@ def test_batch_annotate_images_empty_call(): client.batch_annotate_images() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.BatchAnnotateImagesRequest() @@ -509,7 +534,7 @@ async def test_batch_annotate_images_async( request_type=image_annotator.BatchAnnotateImagesRequest, ): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -524,13 +549,11 @@ async def test_batch_annotate_images_async( 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] == image_annotator.BatchAnnotateImagesRequest() # Establish that the response is the type that we expect. @@ -543,7 +566,7 @@ async def test_batch_annotate_images_async_from_dict(): def test_batch_annotate_images_flattened(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -551,7 +574,6 @@ def test_batch_annotate_images_flattened(): ) 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( @@ -566,7 +588,6 @@ def test_batch_annotate_images_flattened(): # 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") @@ -575,7 +596,7 @@ def test_batch_annotate_images_flattened(): def test_batch_annotate_images_flattened_error(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -592,7 +613,9 @@ def test_batch_annotate_images_flattened_error(): @pytest.mark.asyncio async def test_batch_annotate_images_flattened_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -618,7 +641,6 @@ async def test_batch_annotate_images_flattened_async(): # 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") @@ -628,7 +650,9 @@ async def test_batch_annotate_images_flattened_async(): @pytest.mark.asyncio async def test_batch_annotate_images_flattened_error_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -647,7 +671,7 @@ def test_async_batch_annotate_files( transport: str = "grpc", request_type=image_annotator.AsyncBatchAnnotateFilesRequest ): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -660,13 +684,11 @@ def test_async_batch_annotate_files( ) 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. @@ -681,7 +703,7 @@ def test_async_batch_annotate_files_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -691,7 +713,6 @@ def test_async_batch_annotate_files_empty_call(): client.async_batch_annotate_files() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.AsyncBatchAnnotateFilesRequest() @@ -701,7 +722,7 @@ async def test_async_batch_annotate_files_async( request_type=image_annotator.AsyncBatchAnnotateFilesRequest, ): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -716,13 +737,11 @@ async def test_async_batch_annotate_files_async( 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] == image_annotator.AsyncBatchAnnotateFilesRequest() # Establish that the response is the type that we expect. @@ -735,7 +754,7 @@ async def test_async_batch_annotate_files_async_from_dict(): def test_async_batch_annotate_files_flattened(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -743,7 +762,6 @@ def test_async_batch_annotate_files_flattened(): ) 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( @@ -760,7 +778,6 @@ def test_async_batch_annotate_files_flattened(): # 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( @@ -771,7 +788,7 @@ def test_async_batch_annotate_files_flattened(): def test_async_batch_annotate_files_flattened_error(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -790,7 +807,9 @@ def test_async_batch_annotate_files_flattened_error(): @pytest.mark.asyncio async def test_async_batch_annotate_files_flattened_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -818,7 +837,6 @@ async def test_async_batch_annotate_files_flattened_async(): # 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( @@ -830,7 +848,9 @@ async def test_async_batch_annotate_files_flattened_async(): @pytest.mark.asyncio async def test_async_batch_annotate_files_flattened_error_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -850,16 +870,16 @@ async def test_async_batch_annotate_files_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImageAnnotatorClient( @@ -869,7 +889,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImageAnnotatorClient( @@ -880,7 +900,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ImageAnnotatorClient(transport=transport) assert client.transport is transport @@ -889,13 +909,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ImageAnnotatorGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -910,23 +930,23 @@ def test_transport_get_channel(): ) 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) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_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(),) + client = ImageAnnotatorClient(credentials=ga_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): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ImageAnnotatorTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -938,7 +958,7 @@ def test_image_annotator_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ImageAnnotatorTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -957,15 +977,40 @@ def test_image_annotator_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 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" + google.auth, "load_credentials_from_file", autospec=True ) 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) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ImageAnnotatorTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_image_annotator_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) 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 = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -981,19 +1026,36 @@ def test_image_annotator_base_transport_with_credentials_file(): 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( + with mock.patch.object(google.auth, "default", autospec=True) 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) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 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) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ImageAnnotatorClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_image_annotator_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) ImageAnnotatorClient() adc.assert_called_once_with( scopes=( @@ -1004,14 +1066,44 @@ def test_image_annotator_auth_adc(): ) -def test_image_annotator_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_image_annotator_transport_auth_adc(transport_class): # 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" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_image_annotator_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -1021,6 +1113,121 @@ def test_image_annotator_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ImageAnnotatorGrpcTransport, grpc_helpers), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_image_annotator_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + scopes=["1", "2"], + default_host="vision.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ImageAnnotatorGrpcTransport, grpc_helpers), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_image_annotator_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ImageAnnotatorGrpcTransport, grpc_helpers), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_image_annotator_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1029,7 +1236,7 @@ def test_image_annotator_transport_auth_adc(): ], ) def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1071,7 +1278,7 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_cl def test_image_annotator_host_no_port(): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="vision.googleapis.com" ), @@ -1081,7 +1288,7 @@ def test_image_annotator_host_no_port(): def test_image_annotator_host_with_port(): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="vision.googleapis.com:8000" ), @@ -1137,9 +1344,9 @@ def test_image_annotator_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1221,7 +1428,7 @@ def test_image_annotator_transport_channel_mtls_with_adc(transport_class): def test_image_annotator_grpc_lro_client(): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -1234,7 +1441,7 @@ def test_image_annotator_grpc_lro_client(): def test_image_annotator_grpc_lro_async_client(): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -1249,7 +1456,6 @@ def test_product_path(): project = "squid" location = "clam" product = "whelk" - expected = "projects/{project}/locations/{location}/products/{product}".format( project=project, location=location, product=product, ) @@ -1274,7 +1480,6 @@ def test_product_set_path(): project = "cuttlefish" location = "mussel" product_set = "winkle" - expected = "projects/{project}/locations/{location}/productSets/{product_set}".format( project=project, location=location, product_set=product_set, ) @@ -1297,7 +1502,6 @@ def test_parse_product_set_path(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1318,7 +1522,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = ImageAnnotatorClient.common_folder_path(folder) assert expected == actual @@ -1337,7 +1540,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = ImageAnnotatorClient.common_organization_path(organization) assert expected == actual @@ -1356,7 +1558,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = ImageAnnotatorClient.common_project_path(project) assert expected == actual @@ -1376,7 +1577,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1403,7 +1603,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ImageAnnotatorTransport, "_prep_wrapped_messages" ) as prep: client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1412,6 +1612,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ImageAnnotatorClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_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 index 56180fce..5f217a48 100644 --- a/tests/unit/gapic/vision_v1p3beta1/test_product_search.py +++ b/tests/unit/gapic/vision_v1p3beta1/test_product_search.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,16 +23,16 @@ 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 exceptions as core_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 import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.vision_v1p3beta1.services.product_search import ( ProductSearchAsyncClient, @@ -41,14 +40,44 @@ 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.services.product_search.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.vision_v1p3beta1.services.product_search.transports.base import ( + _GOOGLE_AUTH_VERSION, +) 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 +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -99,7 +128,7 @@ def test__get_default_mtls_endpoint(): "client_class", [ProductSearchClient, ProductSearchAsyncClient,] ) def test_product_search_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -116,7 +145,7 @@ def test_product_search_client_from_service_account_info(client_class): "client_class", [ProductSearchClient, ProductSearchAsyncClient,] ) def test_product_search_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -169,7 +198,7 @@ def test_product_search_client_client_options( ): # 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()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -457,7 +486,7 @@ def test_create_product_set( transport: str = "grpc", request_type=product_search_service.CreateProductSetRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -472,21 +501,16 @@ def test_create_product_set( 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" @@ -498,7 +522,7 @@ def test_create_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -508,7 +532,6 @@ def test_create_product_set_empty_call(): client.create_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.CreateProductSetRequest() @@ -518,7 +541,7 @@ async def test_create_product_set_async( request_type=product_search_service.CreateProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -535,20 +558,16 @@ async def test_create_product_set_async( 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] == 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" @@ -558,11 +577,12 @@ async def test_create_product_set_async_from_dict(): def test_create_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -570,7 +590,6 @@ def test_create_product_set_field_headers(): 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. @@ -585,11 +604,14 @@ def test_create_product_set_field_headers(): @pytest.mark.asyncio async def test_create_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -599,7 +621,6 @@ async def test_create_product_set_field_headers_async(): 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. @@ -613,7 +634,7 @@ async def test_create_product_set_field_headers_async(): def test_create_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -621,7 +642,6 @@ def test_create_product_set_flattened(): ) 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( @@ -634,18 +654,15 @@ def test_create_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -660,7 +677,9 @@ def test_create_product_set_flattened_error(): @pytest.mark.asyncio async def test_create_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -684,19 +703,18 @@ async def test_create_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -713,7 +731,7 @@ def test_list_product_sets( transport: str = "grpc", request_type=product_search_service.ListProductSetsRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -728,19 +746,15 @@ def test_list_product_sets( 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" @@ -752,7 +766,7 @@ def test_list_product_sets_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -762,7 +776,6 @@ def test_list_product_sets_empty_call(): client.list_product_sets() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.ListProductSetsRequest() @@ -772,7 +785,7 @@ async def test_list_product_sets_async( request_type=product_search_service.ListProductSetsRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -789,18 +802,15 @@ async def test_list_product_sets_async( 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] == product_search_service.ListProductSetsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductSetsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -810,11 +820,12 @@ async def test_list_product_sets_async_from_dict(): def test_list_product_sets_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -822,7 +833,6 @@ def test_list_product_sets_field_headers(): 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. @@ -837,11 +847,14 @@ def test_list_product_sets_field_headers(): @pytest.mark.asyncio async def test_list_product_sets_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -851,7 +864,6 @@ async def test_list_product_sets_field_headers_async(): 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. @@ -865,7 +877,7 @@ async def test_list_product_sets_field_headers_async(): def test_list_product_sets_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -873,7 +885,6 @@ def test_list_product_sets_flattened(): ) 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",) @@ -882,12 +893,11 @@ def test_list_product_sets_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -899,7 +909,9 @@ def test_list_product_sets_flattened_error(): @pytest.mark.asyncio async def test_list_product_sets_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -919,13 +931,14 @@ async def test_list_product_sets_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -936,7 +949,7 @@ async def test_list_product_sets_flattened_error_async(): def test_list_product_sets_pager(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -982,7 +995,7 @@ def test_list_product_sets_pager(): def test_list_product_sets_pages(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1020,7 +1033,7 @@ def test_list_product_sets_pages(): @pytest.mark.asyncio async def test_list_product_sets_async_pager(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1065,7 +1078,7 @@ async def test_list_product_sets_async_pager(): @pytest.mark.asyncio async def test_list_product_sets_async_pages(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1109,7 +1122,7 @@ def test_get_product_set( transport: str = "grpc", request_type=product_search_service.GetProductSetRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1122,21 +1135,16 @@ def test_get_product_set( 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" @@ -1148,7 +1156,7 @@ def test_get_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1156,7 +1164,6 @@ def test_get_product_set_empty_call(): client.get_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.GetProductSetRequest() @@ -1166,7 +1173,7 @@ async def test_get_product_set_async( request_type=product_search_service.GetProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1181,20 +1188,16 @@ async def test_get_product_set_async( 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] == 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" @@ -1204,17 +1207,17 @@ async def test_get_product_set_async_from_dict(): def test_get_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -1229,11 +1232,14 @@ def test_get_product_set_field_headers(): @pytest.mark.asyncio async def test_get_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -1241,7 +1247,6 @@ async def test_get_product_set_field_headers_async(): 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. @@ -1255,13 +1260,12 @@ async def test_get_product_set_field_headers_async(): def test_get_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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",) @@ -1270,12 +1274,11 @@ def test_get_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1287,7 +1290,9 @@ def test_get_product_set_flattened_error(): @pytest.mark.asyncio async def test_get_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -1305,13 +1310,14 @@ async def test_get_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1325,7 +1331,7 @@ def test_update_product_set( transport: str = "grpc", request_type=product_search_service.UpdateProductSetRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1340,21 +1346,16 @@ def test_update_product_set( 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" @@ -1366,7 +1367,7 @@ def test_update_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1376,7 +1377,6 @@ def test_update_product_set_empty_call(): client.update_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.UpdateProductSetRequest() @@ -1386,7 +1386,7 @@ async def test_update_product_set_async( request_type=product_search_service.UpdateProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1403,20 +1403,16 @@ async def test_update_product_set_async( 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] == 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" @@ -1426,11 +1422,12 @@ async def test_update_product_set_async_from_dict(): def test_update_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -1438,7 +1435,6 @@ def test_update_product_set_field_headers(): 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. @@ -1455,11 +1451,14 @@ def test_update_product_set_field_headers(): @pytest.mark.asyncio async def test_update_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -1469,7 +1468,6 @@ async def test_update_product_set_field_headers_async(): 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. @@ -1485,7 +1483,7 @@ async def test_update_product_set_field_headers_async(): def test_update_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1493,28 +1491,25 @@ def test_update_product_set_flattened(): ) 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"]), + update_mask=field_mask_pb2.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"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_product_set_flattened_error(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1522,13 +1517,15 @@ def test_update_product_set_flattened_error(): 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"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1544,24 +1541,24 @@ async def test_update_product_set_flattened_async(): # 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"]), + update_mask=field_mask_pb2.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"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_product_set_flattened_error_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1569,7 +1566,7 @@ async def test_update_product_set_flattened_error_async(): 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"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1577,7 +1574,7 @@ def test_delete_product_set( transport: str = "grpc", request_type=product_search_service.DeleteProductSetRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1590,13 +1587,11 @@ def test_delete_product_set( ) 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. @@ -1611,7 +1606,7 @@ def test_delete_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1621,7 +1616,6 @@ def test_delete_product_set_empty_call(): client.delete_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.DeleteProductSetRequest() @@ -1631,7 +1625,7 @@ async def test_delete_product_set_async( request_type=product_search_service.DeleteProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1644,13 +1638,11 @@ async def test_delete_product_set_async( ) 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] == product_search_service.DeleteProductSetRequest() # Establish that the response is the type that we expect. @@ -1663,11 +1655,12 @@ async def test_delete_product_set_async_from_dict(): def test_delete_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -1675,7 +1668,6 @@ def test_delete_product_set_field_headers(): 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. @@ -1690,11 +1682,14 @@ def test_delete_product_set_field_headers(): @pytest.mark.asyncio async def test_delete_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -1702,7 +1697,6 @@ async def test_delete_product_set_field_headers_async(): type(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. @@ -1716,7 +1710,7 @@ async def test_delete_product_set_field_headers_async(): def test_delete_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1724,7 +1718,6 @@ def test_delete_product_set_flattened(): ) 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",) @@ -1733,12 +1726,11 @@ def test_delete_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1750,7 +1742,9 @@ def test_delete_product_set_flattened_error(): @pytest.mark.asyncio async def test_delete_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1768,13 +1762,14 @@ async def test_delete_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1788,7 +1783,7 @@ def test_create_product( transport: str = "grpc", request_type=product_search_service.CreateProductRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1804,25 +1799,18 @@ def test_create_product( 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" @@ -1834,7 +1822,7 @@ def test_create_product_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1842,7 +1830,6 @@ def test_create_product_empty_call(): client.create_product() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.CreateProductRequest() @@ -1852,7 +1839,7 @@ async def test_create_product_async( request_type=product_search_service.CreateProductRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1870,24 +1857,18 @@ async def test_create_product_async( 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] == 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" @@ -1897,17 +1878,17 @@ async def test_create_product_async_from_dict(): def test_create_product_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -1922,11 +1903,14 @@ def test_create_product_field_headers(): @pytest.mark.asyncio async def test_create_product_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -1934,7 +1918,6 @@ async def test_create_product_field_headers_async(): 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. @@ -1948,13 +1931,12 @@ async def test_create_product_field_headers_async(): def test_create_product_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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( @@ -1967,16 +1949,13 @@ def test_create_product_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1991,7 +1970,9 @@ def test_create_product_flattened_error(): @pytest.mark.asyncio async def test_create_product_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -2013,17 +1994,16 @@ async def test_create_product_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2040,7 +2020,7 @@ def test_list_products( transport: str = "grpc", request_type=product_search_service.ListProductsRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2053,19 +2033,15 @@ def test_list_products( 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" @@ -2077,7 +2053,7 @@ def test_list_products_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2085,7 +2061,6 @@ def test_list_products_empty_call(): client.list_products() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.ListProductsRequest() @@ -2095,7 +2070,7 @@ async def test_list_products_async( request_type=product_search_service.ListProductsRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2110,18 +2085,15 @@ async def test_list_products_async( 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] == product_search_service.ListProductsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -2131,17 +2103,17 @@ async def test_list_products_async_from_dict(): def test_list_products_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -2156,11 +2128,14 @@ def test_list_products_field_headers(): @pytest.mark.asyncio async def test_list_products_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -2168,7 +2143,6 @@ async def test_list_products_field_headers_async(): 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. @@ -2182,13 +2156,12 @@ async def test_list_products_field_headers_async(): def test_list_products_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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",) @@ -2197,12 +2170,11 @@ def test_list_products_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2214,7 +2186,9 @@ def test_list_products_flattened_error(): @pytest.mark.asyncio async def test_list_products_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -2232,13 +2206,14 @@ async def test_list_products_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2249,7 +2224,7 @@ async def test_list_products_flattened_error_async(): def test_list_products_pager(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_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: @@ -2292,7 +2267,7 @@ def test_list_products_pager(): def test_list_products_pages(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_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: @@ -2327,7 +2302,7 @@ def test_list_products_pages(): @pytest.mark.asyncio async def test_list_products_async_pager(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2369,7 +2344,7 @@ async def test_list_products_async_pager(): @pytest.mark.asyncio async def test_list_products_async_pages(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2410,7 +2385,7 @@ def test_get_product( transport: str = "grpc", request_type=product_search_service.GetProductRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2426,25 +2401,18 @@ def test_get_product( 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" @@ -2456,7 +2424,7 @@ def test_get_product_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2464,7 +2432,6 @@ def test_get_product_empty_call(): client.get_product() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.GetProductRequest() @@ -2474,7 +2441,7 @@ async def test_get_product_async( request_type=product_search_service.GetProductRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2492,24 +2459,18 @@ async def test_get_product_async( 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] == 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" @@ -2519,17 +2480,17 @@ async def test_get_product_async_from_dict(): def test_get_product_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -2544,11 +2505,14 @@ def test_get_product_field_headers(): @pytest.mark.asyncio async def test_get_product_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -2556,7 +2520,6 @@ async def test_get_product_field_headers_async(): 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. @@ -2570,13 +2533,12 @@ async def test_get_product_field_headers_async(): def test_get_product_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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",) @@ -2585,12 +2547,11 @@ def test_get_product_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2602,7 +2563,9 @@ def test_get_product_flattened_error(): @pytest.mark.asyncio async def test_get_product_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -2620,13 +2583,14 @@ async def test_get_product_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2640,7 +2604,7 @@ def test_update_product( transport: str = "grpc", request_type=product_search_service.UpdateProductRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2656,25 +2620,18 @@ def test_update_product( 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" @@ -2686,7 +2643,7 @@ def test_update_product_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2694,7 +2651,6 @@ def test_update_product_empty_call(): client.update_product() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.UpdateProductRequest() @@ -2704,7 +2660,7 @@ async def test_update_product_async( request_type=product_search_service.UpdateProductRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2722,24 +2678,18 @@ async def test_update_product_async( 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] == 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" @@ -2749,17 +2699,17 @@ async def test_update_product_async_from_dict(): def test_update_product_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -2776,11 +2726,14 @@ def test_update_product_field_headers(): @pytest.mark.asyncio async def test_update_product_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -2788,7 +2741,6 @@ async def test_update_product_field_headers_async(): 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. @@ -2804,32 +2756,29 @@ async def test_update_product_field_headers_async(): def test_update_product_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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"]), + update_mask=field_mask_pb2.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"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_product_flattened_error(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2837,13 +2786,15 @@ def test_update_product_flattened_error(): client.update_product( product_search_service.UpdateProductRequest(), product=product_search_service.Product(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_product_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -2857,22 +2808,22 @@ async def test_update_product_flattened_async(): # 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"]), + update_mask=field_mask_pb2.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"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_product_flattened_error_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2880,7 +2831,7 @@ async def test_update_product_flattened_error_async(): await client.update_product( product_search_service.UpdateProductRequest(), product=product_search_service.Product(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -2888,7 +2839,7 @@ def test_delete_product( transport: str = "grpc", request_type=product_search_service.DeleteProductRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2899,13 +2850,11 @@ def test_delete_product( 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. @@ -2920,7 +2869,7 @@ def test_delete_product_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2928,7 +2877,6 @@ def test_delete_product_empty_call(): client.delete_product() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.DeleteProductRequest() @@ -2938,7 +2886,7 @@ async def test_delete_product_async( request_type=product_search_service.DeleteProductRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2949,13 +2897,11 @@ async def test_delete_product_async( with mock.patch.object(type(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] == product_search_service.DeleteProductRequest() # Establish that the response is the type that we expect. @@ -2968,17 +2914,17 @@ async def test_delete_product_async_from_dict(): def test_delete_product_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -2993,17 +2939,19 @@ def test_delete_product_field_headers(): @pytest.mark.asyncio async def test_delete_product_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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 = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_product(request) # Establish that the underlying gRPC stub method was called. @@ -3017,13 +2965,12 @@ async def test_delete_product_field_headers_async(): def test_delete_product_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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",) @@ -3032,12 +2979,11 @@ def test_delete_product_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3049,7 +2995,9 @@ def test_delete_product_flattened_error(): @pytest.mark.asyncio async def test_delete_product_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -3065,13 +3013,14 @@ async def test_delete_product_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3086,7 +3035,7 @@ def test_create_reference_image( request_type=product_search_service.CreateReferenceImageRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3101,21 +3050,16 @@ def test_create_reference_image( 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" @@ -3127,7 +3071,7 @@ def test_create_reference_image_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3137,7 +3081,6 @@ def test_create_reference_image_empty_call(): client.create_reference_image() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.CreateReferenceImageRequest() @@ -3147,7 +3090,7 @@ async def test_create_reference_image_async( request_type=product_search_service.CreateReferenceImageRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3162,20 +3105,16 @@ async def test_create_reference_image_async( 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] == 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" @@ -3185,11 +3124,12 @@ async def test_create_reference_image_async_from_dict(): def test_create_reference_image_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -3197,7 +3137,6 @@ def test_create_reference_image_field_headers(): 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. @@ -3212,11 +3151,14 @@ def test_create_reference_image_field_headers(): @pytest.mark.asyncio async def test_create_reference_image_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -3226,7 +3168,6 @@ async def test_create_reference_image_field_headers_async(): 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. @@ -3240,7 +3181,7 @@ async def test_create_reference_image_field_headers_async(): def test_create_reference_image_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3248,7 +3189,6 @@ def test_create_reference_image_flattened(): ) 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( @@ -3261,18 +3201,15 @@ def test_create_reference_image_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3287,7 +3224,9 @@ def test_create_reference_image_flattened_error(): @pytest.mark.asyncio async def test_create_reference_image_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3311,19 +3250,18 @@ async def test_create_reference_image_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3341,7 +3279,7 @@ def test_delete_reference_image( request_type=product_search_service.DeleteReferenceImageRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3354,13 +3292,11 @@ def test_delete_reference_image( ) 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. @@ -3375,7 +3311,7 @@ def test_delete_reference_image_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3385,7 +3321,6 @@ def test_delete_reference_image_empty_call(): client.delete_reference_image() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.DeleteReferenceImageRequest() @@ -3395,7 +3330,7 @@ async def test_delete_reference_image_async( request_type=product_search_service.DeleteReferenceImageRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3408,13 +3343,11 @@ async def test_delete_reference_image_async( ) 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] == product_search_service.DeleteReferenceImageRequest() # Establish that the response is the type that we expect. @@ -3427,11 +3360,12 @@ async def test_delete_reference_image_async_from_dict(): def test_delete_reference_image_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -3439,7 +3373,6 @@ def test_delete_reference_image_field_headers(): 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. @@ -3454,11 +3387,14 @@ def test_delete_reference_image_field_headers(): @pytest.mark.asyncio async def test_delete_reference_image_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -3466,7 +3402,6 @@ async def test_delete_reference_image_field_headers_async(): type(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. @@ -3480,7 +3415,7 @@ async def test_delete_reference_image_field_headers_async(): def test_delete_reference_image_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3488,7 +3423,6 @@ def test_delete_reference_image_flattened(): ) 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",) @@ -3497,12 +3431,11 @@ def test_delete_reference_image_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3514,7 +3447,9 @@ def test_delete_reference_image_flattened_error(): @pytest.mark.asyncio async def test_delete_reference_image_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3532,13 +3467,14 @@ async def test_delete_reference_image_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3553,7 +3489,7 @@ def test_list_reference_images( request_type=product_search_service.ListReferenceImagesRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3568,21 +3504,16 @@ def test_list_reference_images( 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" @@ -3594,7 +3525,7 @@ def test_list_reference_images_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3604,7 +3535,6 @@ def test_list_reference_images_empty_call(): client.list_reference_images() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.ListReferenceImagesRequest() @@ -3614,7 +3544,7 @@ async def test_list_reference_images_async( request_type=product_search_service.ListReferenceImagesRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3631,20 +3561,16 @@ async def test_list_reference_images_async( 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] == product_search_service.ListReferenceImagesRequest() # 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" @@ -3654,11 +3580,12 @@ async def test_list_reference_images_async_from_dict(): def test_list_reference_images_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -3666,7 +3593,6 @@ def test_list_reference_images_field_headers(): 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. @@ -3681,11 +3607,14 @@ def test_list_reference_images_field_headers(): @pytest.mark.asyncio async def test_list_reference_images_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -3695,7 +3624,6 @@ async def test_list_reference_images_field_headers_async(): 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. @@ -3709,7 +3637,7 @@ async def test_list_reference_images_field_headers_async(): def test_list_reference_images_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3717,7 +3645,6 @@ def test_list_reference_images_flattened(): ) 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",) @@ -3726,12 +3653,11 @@ def test_list_reference_images_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3743,7 +3669,9 @@ def test_list_reference_images_flattened_error(): @pytest.mark.asyncio async def test_list_reference_images_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3763,13 +3691,14 @@ async def test_list_reference_images_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3780,7 +3709,7 @@ async def test_list_reference_images_flattened_error_async(): def test_list_reference_images_pager(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3828,7 +3757,7 @@ def test_list_reference_images_pager(): def test_list_reference_images_pages(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3866,7 +3795,7 @@ def test_list_reference_images_pages(): @pytest.mark.asyncio async def test_list_reference_images_async_pager(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3913,7 +3842,7 @@ async def test_list_reference_images_async_pager(): @pytest.mark.asyncio async def test_list_reference_images_async_pages(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3958,7 +3887,7 @@ def test_get_reference_image( request_type=product_search_service.GetReferenceImageRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3973,21 +3902,16 @@ def test_get_reference_image( 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" @@ -3999,7 +3923,7 @@ def test_get_reference_image_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4009,7 +3933,6 @@ def test_get_reference_image_empty_call(): client.get_reference_image() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.GetReferenceImageRequest() @@ -4019,7 +3942,7 @@ async def test_get_reference_image_async( request_type=product_search_service.GetReferenceImageRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4034,20 +3957,16 @@ async def test_get_reference_image_async( 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] == 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" @@ -4057,11 +3976,12 @@ async def test_get_reference_image_async_from_dict(): def test_get_reference_image_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -4069,7 +3989,6 @@ def test_get_reference_image_field_headers(): 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. @@ -4084,11 +4003,14 @@ def test_get_reference_image_field_headers(): @pytest.mark.asyncio async def test_get_reference_image_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -4098,7 +4020,6 @@ async def test_get_reference_image_field_headers_async(): 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. @@ -4112,7 +4033,7 @@ async def test_get_reference_image_field_headers_async(): def test_get_reference_image_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4120,7 +4041,6 @@ def test_get_reference_image_flattened(): ) 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",) @@ -4129,12 +4049,11 @@ def test_get_reference_image_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4146,7 +4065,9 @@ def test_get_reference_image_flattened_error(): @pytest.mark.asyncio async def test_get_reference_image_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4166,13 +4087,14 @@ async def test_get_reference_image_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4187,7 +4109,7 @@ def test_add_product_to_product_set( request_type=product_search_service.AddProductToProductSetRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4200,13 +4122,11 @@ def test_add_product_to_product_set( ) 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. @@ -4221,7 +4141,7 @@ def test_add_product_to_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4231,7 +4151,6 @@ def test_add_product_to_product_set_empty_call(): client.add_product_to_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.AddProductToProductSetRequest() @@ -4241,7 +4160,7 @@ async def test_add_product_to_product_set_async( request_type=product_search_service.AddProductToProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4254,13 +4173,11 @@ async def test_add_product_to_product_set_async( ) 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] == product_search_service.AddProductToProductSetRequest() # Establish that the response is the type that we expect. @@ -4273,11 +4190,12 @@ async def test_add_product_to_product_set_async_from_dict(): def test_add_product_to_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -4285,7 +4203,6 @@ def test_add_product_to_product_set_field_headers(): 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. @@ -4300,11 +4217,14 @@ def test_add_product_to_product_set_field_headers(): @pytest.mark.asyncio async def test_add_product_to_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -4312,7 +4232,6 @@ async def test_add_product_to_product_set_field_headers_async(): type(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. @@ -4326,7 +4245,7 @@ async def test_add_product_to_product_set_field_headers_async(): def test_add_product_to_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4334,7 +4253,6 @@ def test_add_product_to_product_set_flattened(): ) 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( @@ -4345,14 +4263,12 @@ def test_add_product_to_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4366,7 +4282,9 @@ def test_add_product_to_product_set_flattened_error(): @pytest.mark.asyncio async def test_add_product_to_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4386,15 +4304,15 @@ async def test_add_product_to_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4411,7 +4329,7 @@ def test_remove_product_from_product_set( request_type=product_search_service.RemoveProductFromProductSetRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4424,13 +4342,11 @@ def test_remove_product_from_product_set( ) 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. @@ -4445,7 +4361,7 @@ def test_remove_product_from_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4455,7 +4371,6 @@ def test_remove_product_from_product_set_empty_call(): client.remove_product_from_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.RemoveProductFromProductSetRequest() @@ -4465,7 +4380,7 @@ async def test_remove_product_from_product_set_async( request_type=product_search_service.RemoveProductFromProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4478,13 +4393,11 @@ async def test_remove_product_from_product_set_async( ) 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] == product_search_service.RemoveProductFromProductSetRequest() # Establish that the response is the type that we expect. @@ -4497,11 +4410,12 @@ async def test_remove_product_from_product_set_async_from_dict(): def test_remove_product_from_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -4509,7 +4423,6 @@ def test_remove_product_from_product_set_field_headers(): 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. @@ -4524,11 +4437,14 @@ def test_remove_product_from_product_set_field_headers(): @pytest.mark.asyncio async def test_remove_product_from_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -4536,7 +4452,6 @@ async def test_remove_product_from_product_set_field_headers_async(): type(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. @@ -4550,7 +4465,7 @@ async def test_remove_product_from_product_set_field_headers_async(): def test_remove_product_from_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4558,7 +4473,6 @@ def test_remove_product_from_product_set_flattened(): ) 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( @@ -4569,14 +4483,12 @@ def test_remove_product_from_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4590,7 +4502,9 @@ def test_remove_product_from_product_set_flattened_error(): @pytest.mark.asyncio async def test_remove_product_from_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4610,15 +4524,15 @@ async def test_remove_product_from_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4635,7 +4549,7 @@ def test_list_products_in_product_set( request_type=product_search_service.ListProductsInProductSetRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4650,19 +4564,15 @@ def test_list_products_in_product_set( 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" @@ -4674,7 +4584,7 @@ def test_list_products_in_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4684,7 +4594,6 @@ def test_list_products_in_product_set_empty_call(): client.list_products_in_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.ListProductsInProductSetRequest() @@ -4694,7 +4603,7 @@ async def test_list_products_in_product_set_async( request_type=product_search_service.ListProductsInProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4711,18 +4620,15 @@ async def test_list_products_in_product_set_async( 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] == product_search_service.ListProductsInProductSetRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsInProductSetAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -4732,11 +4638,12 @@ async def test_list_products_in_product_set_async_from_dict(): def test_list_products_in_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -4744,7 +4651,6 @@ def test_list_products_in_product_set_field_headers(): 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. @@ -4759,11 +4665,14 @@ def test_list_products_in_product_set_field_headers(): @pytest.mark.asyncio async def test_list_products_in_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -4773,7 +4682,6 @@ async def test_list_products_in_product_set_field_headers_async(): 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. @@ -4787,7 +4695,7 @@ async def test_list_products_in_product_set_field_headers_async(): def test_list_products_in_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4795,7 +4703,6 @@ def test_list_products_in_product_set_flattened(): ) 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",) @@ -4804,12 +4711,11 @@ def test_list_products_in_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4821,7 +4727,9 @@ def test_list_products_in_product_set_flattened_error(): @pytest.mark.asyncio async def test_list_products_in_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4841,13 +4749,14 @@ async def test_list_products_in_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4858,7 +4767,7 @@ async def test_list_products_in_product_set_flattened_error_async(): def test_list_products_in_product_set_pager(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4903,7 +4812,7 @@ def test_list_products_in_product_set_pager(): def test_list_products_in_product_set_pages(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4940,7 +4849,7 @@ def test_list_products_in_product_set_pages(): @pytest.mark.asyncio async def test_list_products_in_product_set_async_pager(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4984,7 +4893,7 @@ async def test_list_products_in_product_set_async_pager(): @pytest.mark.asyncio async def test_list_products_in_product_set_async_pages(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -5030,7 +4939,7 @@ def test_import_product_sets( request_type=product_search_service.ImportProductSetsRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5043,13 +4952,11 @@ def test_import_product_sets( ) 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. @@ -5064,7 +4971,7 @@ def test_import_product_sets_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5074,7 +4981,6 @@ def test_import_product_sets_empty_call(): client.import_product_sets() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.ImportProductSetsRequest() @@ -5084,7 +4990,7 @@ async def test_import_product_sets_async( request_type=product_search_service.ImportProductSetsRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5099,13 +5005,11 @@ async def test_import_product_sets_async( 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] == product_search_service.ImportProductSetsRequest() # Establish that the response is the type that we expect. @@ -5118,11 +5022,12 @@ async def test_import_product_sets_async_from_dict(): def test_import_product_sets_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -5130,7 +5035,6 @@ def test_import_product_sets_field_headers(): 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. @@ -5145,11 +5049,14 @@ def test_import_product_sets_field_headers(): @pytest.mark.asyncio async def test_import_product_sets_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -5159,7 +5066,6 @@ async def test_import_product_sets_field_headers_async(): 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. @@ -5173,7 +5079,7 @@ async def test_import_product_sets_field_headers_async(): def test_import_product_sets_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -5181,7 +5087,6 @@ def test_import_product_sets_flattened(): ) 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( @@ -5197,9 +5102,7 @@ def test_import_product_sets_flattened(): # 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( @@ -5210,7 +5113,7 @@ def test_import_product_sets_flattened(): def test_import_product_sets_flattened_error(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5228,7 +5131,9 @@ def test_import_product_sets_flattened_error(): @pytest.mark.asyncio async def test_import_product_sets_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -5255,9 +5160,7 @@ async def test_import_product_sets_flattened_async(): # 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( @@ -5269,7 +5172,9 @@ async def test_import_product_sets_flattened_async(): @pytest.mark.asyncio async def test_import_product_sets_flattened_error_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5288,16 +5193,16 @@ async def test_import_product_sets_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ProductSearchGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ProductSearchGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ProductSearchClient( @@ -5307,7 +5212,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ProductSearchGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ProductSearchClient( @@ -5318,7 +5223,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ProductSearchGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ProductSearchClient(transport=transport) assert client.transport is transport @@ -5327,13 +5232,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ProductSearchGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ProductSearchGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -5348,23 +5253,23 @@ def test_transport_get_channel(): ) 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) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_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(),) + client = ProductSearchClient(credentials=ga_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): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ProductSearchTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -5376,7 +5281,7 @@ def test_product_search_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ProductSearchTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -5411,15 +5316,40 @@ def test_product_search_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 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" + google.auth, "load_credentials_from_file", autospec=True + ) 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 = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductSearchTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_product_search_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) 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) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ProductSearchTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -5435,19 +5365,36 @@ def test_product_search_base_transport_with_credentials_file(): 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( + with mock.patch.object(google.auth, "default", autospec=True) 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) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ProductSearchTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 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) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ProductSearchClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_product_search_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) ProductSearchClient() adc.assert_called_once_with( scopes=( @@ -5458,14 +5405,44 @@ def test_product_search_auth_adc(): ) -def test_product_search_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_product_search_transport_auth_adc(transport_class): # 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" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_product_search_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -5475,6 +5452,121 @@ def test_product_search_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ProductSearchGrpcTransport, grpc_helpers), + (transports.ProductSearchGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_product_search_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + scopes=["1", "2"], + default_host="vision.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ProductSearchGrpcTransport, grpc_helpers), + (transports.ProductSearchGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_product_search_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ProductSearchGrpcTransport, grpc_helpers), + (transports.ProductSearchGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_product_search_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -5483,7 +5575,7 @@ def test_product_search_transport_auth_adc(): ], ) def test_product_search_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -5525,7 +5617,7 @@ def test_product_search_grpc_transport_client_cert_source_for_mtls(transport_cla def test_product_search_host_no_port(): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="vision.googleapis.com" ), @@ -5535,7 +5627,7 @@ def test_product_search_host_no_port(): def test_product_search_host_with_port(): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="vision.googleapis.com:8000" ), @@ -5589,9 +5681,9 @@ def test_product_search_transport_channel_mtls_with_client_cert_source(transport mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -5673,7 +5765,7 @@ def test_product_search_transport_channel_mtls_with_adc(transport_class): def test_product_search_grpc_lro_client(): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -5686,7 +5778,7 @@ def test_product_search_grpc_lro_client(): def test_product_search_grpc_lro_async_client(): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -5701,7 +5793,6 @@ def test_product_path(): project = "squid" location = "clam" product = "whelk" - expected = "projects/{project}/locations/{location}/products/{product}".format( project=project, location=location, product=product, ) @@ -5726,7 +5817,6 @@ def test_product_set_path(): project = "cuttlefish" location = "mussel" product_set = "winkle" - expected = "projects/{project}/locations/{location}/productSets/{product_set}".format( project=project, location=location, product_set=product_set, ) @@ -5752,7 +5842,6 @@ def test_reference_image_path(): location = "clam" product = "whelk" reference_image = "octopus" - expected = "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( project=project, location=location, @@ -5781,7 +5870,6 @@ def test_parse_reference_image_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -5802,7 +5890,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = ProductSearchClient.common_folder_path(folder) assert expected == actual @@ -5821,7 +5908,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = ProductSearchClient.common_organization_path(organization) assert expected == actual @@ -5840,7 +5926,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = ProductSearchClient.common_project_path(project) assert expected == actual @@ -5860,7 +5945,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -5887,7 +5971,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ProductSearchTransport, "_prep_wrapped_messages" ) as prep: client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -5896,6 +5980,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ProductSearchClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_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 index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/vision_v1p4beta1/__init__.py +++ b/tests/unit/gapic/vision_v1p4beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/vision_v1p4beta1/test_image_annotator.py b/tests/unit/gapic/vision_v1p4beta1/test_image_annotator.py index 4fda801f..0b274348 100644 --- a/tests/unit/gapic/vision_v1p4beta1/test_image_annotator.py +++ b/tests/unit/gapic/vision_v1p4beta1/test_image_annotator.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,29 +23,59 @@ 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 exceptions as core_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 import credentials as ga_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.services.image_annotator.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.vision_v1p4beta1.services.image_annotator.transports.base import ( + _GOOGLE_AUTH_VERSION, +) 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 +from google.type import latlng_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -97,7 +126,7 @@ def test__get_default_mtls_endpoint(): "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient,] ) def test_image_annotator_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -114,7 +143,7 @@ def test_image_annotator_client_from_service_account_info(client_class): "client_class", [ImageAnnotatorClient, ImageAnnotatorAsyncClient,] ) def test_image_annotator_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -167,7 +196,7 @@ def test_image_annotator_client_client_options( ): # 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()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -455,7 +484,7 @@ def test_batch_annotate_images( transport: str = "grpc", request_type=image_annotator.BatchAnnotateImagesRequest ): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -468,17 +497,14 @@ def test_batch_annotate_images( ) 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) @@ -490,7 +516,7 @@ def test_batch_annotate_images_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -500,7 +526,6 @@ def test_batch_annotate_images_empty_call(): client.batch_annotate_images() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.BatchAnnotateImagesRequest() @@ -510,7 +535,7 @@ async def test_batch_annotate_images_async( request_type=image_annotator.BatchAnnotateImagesRequest, ): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -525,13 +550,11 @@ async def test_batch_annotate_images_async( 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] == image_annotator.BatchAnnotateImagesRequest() # Establish that the response is the type that we expect. @@ -544,7 +567,7 @@ async def test_batch_annotate_images_async_from_dict(): def test_batch_annotate_images_flattened(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -552,7 +575,6 @@ def test_batch_annotate_images_flattened(): ) 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( @@ -567,7 +589,6 @@ def test_batch_annotate_images_flattened(): # 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") @@ -576,7 +597,7 @@ def test_batch_annotate_images_flattened(): def test_batch_annotate_images_flattened_error(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -593,7 +614,9 @@ def test_batch_annotate_images_flattened_error(): @pytest.mark.asyncio async def test_batch_annotate_images_flattened_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -619,7 +642,6 @@ async def test_batch_annotate_images_flattened_async(): # 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") @@ -629,7 +651,9 @@ async def test_batch_annotate_images_flattened_async(): @pytest.mark.asyncio async def test_batch_annotate_images_flattened_error_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -648,7 +672,7 @@ def test_batch_annotate_files( transport: str = "grpc", request_type=image_annotator.BatchAnnotateFilesRequest ): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -661,17 +685,14 @@ def test_batch_annotate_files( ) 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) @@ -683,7 +704,7 @@ def test_batch_annotate_files_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -693,7 +714,6 @@ def test_batch_annotate_files_empty_call(): client.batch_annotate_files() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.BatchAnnotateFilesRequest() @@ -703,7 +723,7 @@ async def test_batch_annotate_files_async( request_type=image_annotator.BatchAnnotateFilesRequest, ): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -718,13 +738,11 @@ async def test_batch_annotate_files_async( 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] == image_annotator.BatchAnnotateFilesRequest() # Establish that the response is the type that we expect. @@ -737,7 +755,7 @@ async def test_batch_annotate_files_async_from_dict(): def test_batch_annotate_files_flattened(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -745,7 +763,6 @@ def test_batch_annotate_files_flattened(): ) 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( @@ -762,7 +779,6 @@ def test_batch_annotate_files_flattened(): # 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( @@ -773,7 +789,7 @@ def test_batch_annotate_files_flattened(): def test_batch_annotate_files_flattened_error(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -792,7 +808,9 @@ def test_batch_annotate_files_flattened_error(): @pytest.mark.asyncio async def test_batch_annotate_files_flattened_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -820,7 +838,6 @@ async def test_batch_annotate_files_flattened_async(): # 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( @@ -832,7 +849,9 @@ async def test_batch_annotate_files_flattened_async(): @pytest.mark.asyncio async def test_batch_annotate_files_flattened_error_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -854,7 +873,7 @@ def test_async_batch_annotate_images( request_type=image_annotator.AsyncBatchAnnotateImagesRequest, ): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -867,13 +886,11 @@ def test_async_batch_annotate_images( ) 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. @@ -888,7 +905,7 @@ def test_async_batch_annotate_images_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -898,7 +915,6 @@ def test_async_batch_annotate_images_empty_call(): client.async_batch_annotate_images() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.AsyncBatchAnnotateImagesRequest() @@ -908,7 +924,7 @@ async def test_async_batch_annotate_images_async( request_type=image_annotator.AsyncBatchAnnotateImagesRequest, ): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -923,13 +939,11 @@ async def test_async_batch_annotate_images_async( 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] == image_annotator.AsyncBatchAnnotateImagesRequest() # Establish that the response is the type that we expect. @@ -942,7 +956,7 @@ async def test_async_batch_annotate_images_async_from_dict(): def test_async_batch_annotate_images_flattened(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -950,7 +964,6 @@ def test_async_batch_annotate_images_flattened(): ) 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( @@ -968,20 +981,18 @@ def test_async_batch_annotate_images_flattened(): # 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(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1001,7 +1012,9 @@ def test_async_batch_annotate_images_flattened_error(): @pytest.mark.asyncio async def test_async_batch_annotate_images_flattened_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1030,13 +1043,11 @@ async def test_async_batch_annotate_images_flattened_async(): # 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") ) @@ -1044,7 +1055,9 @@ async def test_async_batch_annotate_images_flattened_async(): @pytest.mark.asyncio async def test_async_batch_annotate_images_flattened_error_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1066,7 +1079,7 @@ def test_async_batch_annotate_files( transport: str = "grpc", request_type=image_annotator.AsyncBatchAnnotateFilesRequest ): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1079,13 +1092,11 @@ def test_async_batch_annotate_files( ) 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. @@ -1100,7 +1111,7 @@ def test_async_batch_annotate_files_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1110,7 +1121,6 @@ def test_async_batch_annotate_files_empty_call(): client.async_batch_annotate_files() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == image_annotator.AsyncBatchAnnotateFilesRequest() @@ -1120,7 +1130,7 @@ async def test_async_batch_annotate_files_async( request_type=image_annotator.AsyncBatchAnnotateFilesRequest, ): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1135,13 +1145,11 @@ async def test_async_batch_annotate_files_async( 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] == image_annotator.AsyncBatchAnnotateFilesRequest() # Establish that the response is the type that we expect. @@ -1154,7 +1162,7 @@ async def test_async_batch_annotate_files_async_from_dict(): def test_async_batch_annotate_files_flattened(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1162,7 +1170,6 @@ def test_async_batch_annotate_files_flattened(): ) 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( @@ -1179,7 +1186,6 @@ def test_async_batch_annotate_files_flattened(): # 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( @@ -1190,7 +1196,7 @@ def test_async_batch_annotate_files_flattened(): def test_async_batch_annotate_files_flattened_error(): - client = ImageAnnotatorClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1209,7 +1215,9 @@ def test_async_batch_annotate_files_flattened_error(): @pytest.mark.asyncio async def test_async_batch_annotate_files_flattened_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1237,7 +1245,6 @@ async def test_async_batch_annotate_files_flattened_async(): # 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( @@ -1249,7 +1256,9 @@ async def test_async_batch_annotate_files_flattened_async(): @pytest.mark.asyncio async def test_async_batch_annotate_files_flattened_error_async(): - client = ImageAnnotatorAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ImageAnnotatorAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1269,16 +1278,16 @@ async def test_async_batch_annotate_files_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImageAnnotatorClient( @@ -1288,7 +1297,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ImageAnnotatorClient( @@ -1299,7 +1308,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ImageAnnotatorClient(transport=transport) assert client.transport is transport @@ -1308,13 +1317,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ImageAnnotatorGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ImageAnnotatorGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1329,23 +1338,23 @@ def test_transport_get_channel(): ) 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) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_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(),) + client = ImageAnnotatorClient(credentials=ga_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): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ImageAnnotatorTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1357,7 +1366,7 @@ def test_image_annotator_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ImageAnnotatorTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1378,15 +1387,40 @@ def test_image_annotator_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 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" + google.auth, "load_credentials_from_file", autospec=True + ) 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 = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ImageAnnotatorTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_image_annotator_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) 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) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1402,19 +1436,36 @@ def test_image_annotator_base_transport_with_credentials_file(): 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( + with mock.patch.object(google.auth, "default", autospec=True) 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) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ImageAnnotatorTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 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) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ImageAnnotatorClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_image_annotator_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) ImageAnnotatorClient() adc.assert_called_once_with( scopes=( @@ -1425,14 +1476,44 @@ def test_image_annotator_auth_adc(): ) -def test_image_annotator_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_image_annotator_transport_auth_adc(transport_class): # 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" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageAnnotatorGrpcTransport, + transports.ImageAnnotatorGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_image_annotator_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -1442,6 +1523,121 @@ def test_image_annotator_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ImageAnnotatorGrpcTransport, grpc_helpers), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_image_annotator_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + scopes=["1", "2"], + default_host="vision.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ImageAnnotatorGrpcTransport, grpc_helpers), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_image_annotator_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ImageAnnotatorGrpcTransport, grpc_helpers), + (transports.ImageAnnotatorGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_image_annotator_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -1450,7 +1646,7 @@ def test_image_annotator_transport_auth_adc(): ], ) def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1492,7 +1688,7 @@ def test_image_annotator_grpc_transport_client_cert_source_for_mtls(transport_cl def test_image_annotator_host_no_port(): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="vision.googleapis.com" ), @@ -1502,7 +1698,7 @@ def test_image_annotator_host_no_port(): def test_image_annotator_host_with_port(): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="vision.googleapis.com:8000" ), @@ -1558,9 +1754,9 @@ def test_image_annotator_transport_channel_mtls_with_client_cert_source( mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1642,7 +1838,7 @@ def test_image_annotator_transport_channel_mtls_with_adc(transport_class): def test_image_annotator_grpc_lro_client(): client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -1655,7 +1851,7 @@ def test_image_annotator_grpc_lro_client(): def test_image_annotator_grpc_lro_async_client(): client = ImageAnnotatorAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -1670,7 +1866,6 @@ def test_product_path(): project = "squid" location = "clam" product = "whelk" - expected = "projects/{project}/locations/{location}/products/{product}".format( project=project, location=location, product=product, ) @@ -1695,7 +1890,6 @@ def test_product_set_path(): project = "cuttlefish" location = "mussel" product_set = "winkle" - expected = "projects/{project}/locations/{location}/productSets/{product_set}".format( project=project, location=location, product_set=product_set, ) @@ -1718,7 +1912,6 @@ def test_parse_product_set_path(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1739,7 +1932,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = ImageAnnotatorClient.common_folder_path(folder) assert expected == actual @@ -1758,7 +1950,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = ImageAnnotatorClient.common_organization_path(organization) assert expected == actual @@ -1777,7 +1968,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = ImageAnnotatorClient.common_project_path(project) assert expected == actual @@ -1797,7 +1987,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1824,7 +2013,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ImageAnnotatorTransport, "_prep_wrapped_messages" ) as prep: client = ImageAnnotatorClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1833,6 +2022,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ImageAnnotatorClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_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 index b8418d77..b35d8c02 100644 --- a/tests/unit/gapic/vision_v1p4beta1/test_product_search.py +++ b/tests/unit/gapic/vision_v1p4beta1/test_product_search.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,16 +23,16 @@ 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 exceptions as core_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 import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.vision_v1p4beta1.services.product_search import ( ProductSearchAsyncClient, @@ -41,14 +40,44 @@ 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.services.product_search.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.vision_v1p4beta1.services.product_search.transports.base import ( + _GOOGLE_AUTH_VERSION, +) 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 +from google.protobuf import any_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import status_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -99,7 +128,7 @@ def test__get_default_mtls_endpoint(): "client_class", [ProductSearchClient, ProductSearchAsyncClient,] ) def test_product_search_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -116,7 +145,7 @@ def test_product_search_client_from_service_account_info(client_class): "client_class", [ProductSearchClient, ProductSearchAsyncClient,] ) def test_product_search_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -169,7 +198,7 @@ def test_product_search_client_client_options( ): # 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()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -457,7 +486,7 @@ def test_create_product_set( transport: str = "grpc", request_type=product_search_service.CreateProductSetRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -472,21 +501,16 @@ def test_create_product_set( 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" @@ -498,7 +522,7 @@ def test_create_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -508,7 +532,6 @@ def test_create_product_set_empty_call(): client.create_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.CreateProductSetRequest() @@ -518,7 +541,7 @@ async def test_create_product_set_async( request_type=product_search_service.CreateProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -535,20 +558,16 @@ async def test_create_product_set_async( 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] == 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" @@ -558,11 +577,12 @@ async def test_create_product_set_async_from_dict(): def test_create_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -570,7 +590,6 @@ def test_create_product_set_field_headers(): 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. @@ -585,11 +604,14 @@ def test_create_product_set_field_headers(): @pytest.mark.asyncio async def test_create_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -599,7 +621,6 @@ async def test_create_product_set_field_headers_async(): 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. @@ -613,7 +634,7 @@ async def test_create_product_set_field_headers_async(): def test_create_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -621,7 +642,6 @@ def test_create_product_set_flattened(): ) 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( @@ -634,18 +654,15 @@ def test_create_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -660,7 +677,9 @@ def test_create_product_set_flattened_error(): @pytest.mark.asyncio async def test_create_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -684,19 +703,18 @@ async def test_create_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -713,7 +731,7 @@ def test_list_product_sets( transport: str = "grpc", request_type=product_search_service.ListProductSetsRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -728,19 +746,15 @@ def test_list_product_sets( 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" @@ -752,7 +766,7 @@ def test_list_product_sets_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -762,7 +776,6 @@ def test_list_product_sets_empty_call(): client.list_product_sets() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.ListProductSetsRequest() @@ -772,7 +785,7 @@ async def test_list_product_sets_async( request_type=product_search_service.ListProductSetsRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -789,18 +802,15 @@ async def test_list_product_sets_async( 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] == product_search_service.ListProductSetsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductSetsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -810,11 +820,12 @@ async def test_list_product_sets_async_from_dict(): def test_list_product_sets_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -822,7 +833,6 @@ def test_list_product_sets_field_headers(): 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. @@ -837,11 +847,14 @@ def test_list_product_sets_field_headers(): @pytest.mark.asyncio async def test_list_product_sets_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -851,7 +864,6 @@ async def test_list_product_sets_field_headers_async(): 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. @@ -865,7 +877,7 @@ async def test_list_product_sets_field_headers_async(): def test_list_product_sets_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -873,7 +885,6 @@ def test_list_product_sets_flattened(): ) 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",) @@ -882,12 +893,11 @@ def test_list_product_sets_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -899,7 +909,9 @@ def test_list_product_sets_flattened_error(): @pytest.mark.asyncio async def test_list_product_sets_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -919,13 +931,14 @@ async def test_list_product_sets_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -936,7 +949,7 @@ async def test_list_product_sets_flattened_error_async(): def test_list_product_sets_pager(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -982,7 +995,7 @@ def test_list_product_sets_pager(): def test_list_product_sets_pages(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1020,7 +1033,7 @@ def test_list_product_sets_pages(): @pytest.mark.asyncio async def test_list_product_sets_async_pager(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1065,7 +1078,7 @@ async def test_list_product_sets_async_pager(): @pytest.mark.asyncio async def test_list_product_sets_async_pages(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1109,7 +1122,7 @@ def test_get_product_set( transport: str = "grpc", request_type=product_search_service.GetProductSetRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1122,21 +1135,16 @@ def test_get_product_set( 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" @@ -1148,7 +1156,7 @@ def test_get_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1156,7 +1164,6 @@ def test_get_product_set_empty_call(): client.get_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.GetProductSetRequest() @@ -1166,7 +1173,7 @@ async def test_get_product_set_async( request_type=product_search_service.GetProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1181,20 +1188,16 @@ async def test_get_product_set_async( 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] == 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" @@ -1204,17 +1207,17 @@ async def test_get_product_set_async_from_dict(): def test_get_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -1229,11 +1232,14 @@ def test_get_product_set_field_headers(): @pytest.mark.asyncio async def test_get_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -1241,7 +1247,6 @@ async def test_get_product_set_field_headers_async(): 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. @@ -1255,13 +1260,12 @@ async def test_get_product_set_field_headers_async(): def test_get_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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",) @@ -1270,12 +1274,11 @@ def test_get_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1287,7 +1290,9 @@ def test_get_product_set_flattened_error(): @pytest.mark.asyncio async def test_get_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -1305,13 +1310,14 @@ async def test_get_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1325,7 +1331,7 @@ def test_update_product_set( transport: str = "grpc", request_type=product_search_service.UpdateProductSetRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1340,21 +1346,16 @@ def test_update_product_set( 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" @@ -1366,7 +1367,7 @@ def test_update_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1376,7 +1377,6 @@ def test_update_product_set_empty_call(): client.update_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.UpdateProductSetRequest() @@ -1386,7 +1386,7 @@ async def test_update_product_set_async( request_type=product_search_service.UpdateProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1403,20 +1403,16 @@ async def test_update_product_set_async( 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] == 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" @@ -1426,11 +1422,12 @@ async def test_update_product_set_async_from_dict(): def test_update_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -1438,7 +1435,6 @@ def test_update_product_set_field_headers(): 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. @@ -1455,11 +1451,14 @@ def test_update_product_set_field_headers(): @pytest.mark.asyncio async def test_update_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -1469,7 +1468,6 @@ async def test_update_product_set_field_headers_async(): 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. @@ -1485,7 +1483,7 @@ async def test_update_product_set_field_headers_async(): def test_update_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1493,28 +1491,25 @@ def test_update_product_set_flattened(): ) 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"]), + update_mask=field_mask_pb2.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"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_product_set_flattened_error(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1522,13 +1517,15 @@ def test_update_product_set_flattened_error(): 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"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1544,24 +1541,24 @@ async def test_update_product_set_flattened_async(): # 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"]), + update_mask=field_mask_pb2.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"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_product_set_flattened_error_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1569,7 +1566,7 @@ async def test_update_product_set_flattened_error_async(): 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"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -1577,7 +1574,7 @@ def test_delete_product_set( transport: str = "grpc", request_type=product_search_service.DeleteProductSetRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1590,13 +1587,11 @@ def test_delete_product_set( ) 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. @@ -1611,7 +1606,7 @@ def test_delete_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1621,7 +1616,6 @@ def test_delete_product_set_empty_call(): client.delete_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.DeleteProductSetRequest() @@ -1631,7 +1625,7 @@ async def test_delete_product_set_async( request_type=product_search_service.DeleteProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1644,13 +1638,11 @@ async def test_delete_product_set_async( ) 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] == product_search_service.DeleteProductSetRequest() # Establish that the response is the type that we expect. @@ -1663,11 +1655,12 @@ async def test_delete_product_set_async_from_dict(): def test_delete_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -1675,7 +1668,6 @@ def test_delete_product_set_field_headers(): 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. @@ -1690,11 +1682,14 @@ def test_delete_product_set_field_headers(): @pytest.mark.asyncio async def test_delete_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -1702,7 +1697,6 @@ async def test_delete_product_set_field_headers_async(): type(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. @@ -1716,7 +1710,7 @@ async def test_delete_product_set_field_headers_async(): def test_delete_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1724,7 +1718,6 @@ def test_delete_product_set_flattened(): ) 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",) @@ -1733,12 +1726,11 @@ def test_delete_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1750,7 +1742,9 @@ def test_delete_product_set_flattened_error(): @pytest.mark.asyncio async def test_delete_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1768,13 +1762,14 @@ async def test_delete_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1788,7 +1783,7 @@ def test_create_product( transport: str = "grpc", request_type=product_search_service.CreateProductRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1804,25 +1799,18 @@ def test_create_product( 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" @@ -1834,7 +1822,7 @@ def test_create_product_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1842,7 +1830,6 @@ def test_create_product_empty_call(): client.create_product() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.CreateProductRequest() @@ -1852,7 +1839,7 @@ async def test_create_product_async( request_type=product_search_service.CreateProductRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1870,24 +1857,18 @@ async def test_create_product_async( 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] == 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" @@ -1897,17 +1878,17 @@ async def test_create_product_async_from_dict(): def test_create_product_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -1922,11 +1903,14 @@ def test_create_product_field_headers(): @pytest.mark.asyncio async def test_create_product_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -1934,7 +1918,6 @@ async def test_create_product_field_headers_async(): 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. @@ -1948,13 +1931,12 @@ async def test_create_product_field_headers_async(): def test_create_product_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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( @@ -1967,16 +1949,13 @@ def test_create_product_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1991,7 +1970,9 @@ def test_create_product_flattened_error(): @pytest.mark.asyncio async def test_create_product_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -2013,17 +1994,16 @@ async def test_create_product_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2040,7 +2020,7 @@ def test_list_products( transport: str = "grpc", request_type=product_search_service.ListProductsRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2053,19 +2033,15 @@ def test_list_products( 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" @@ -2077,7 +2053,7 @@ def test_list_products_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2085,7 +2061,6 @@ def test_list_products_empty_call(): client.list_products() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.ListProductsRequest() @@ -2095,7 +2070,7 @@ async def test_list_products_async( request_type=product_search_service.ListProductsRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2110,18 +2085,15 @@ async def test_list_products_async( 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] == product_search_service.ListProductsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -2131,17 +2103,17 @@ async def test_list_products_async_from_dict(): def test_list_products_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -2156,11 +2128,14 @@ def test_list_products_field_headers(): @pytest.mark.asyncio async def test_list_products_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -2168,7 +2143,6 @@ async def test_list_products_field_headers_async(): 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. @@ -2182,13 +2156,12 @@ async def test_list_products_field_headers_async(): def test_list_products_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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",) @@ -2197,12 +2170,11 @@ def test_list_products_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2214,7 +2186,9 @@ def test_list_products_flattened_error(): @pytest.mark.asyncio async def test_list_products_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -2232,13 +2206,14 @@ async def test_list_products_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2249,7 +2224,7 @@ async def test_list_products_flattened_error_async(): def test_list_products_pager(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_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: @@ -2292,7 +2267,7 @@ def test_list_products_pager(): def test_list_products_pages(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_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: @@ -2327,7 +2302,7 @@ def test_list_products_pages(): @pytest.mark.asyncio async def test_list_products_async_pager(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2369,7 +2344,7 @@ async def test_list_products_async_pager(): @pytest.mark.asyncio async def test_list_products_async_pages(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2410,7 +2385,7 @@ def test_get_product( transport: str = "grpc", request_type=product_search_service.GetProductRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2426,25 +2401,18 @@ def test_get_product( 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" @@ -2456,7 +2424,7 @@ def test_get_product_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2464,7 +2432,6 @@ def test_get_product_empty_call(): client.get_product() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.GetProductRequest() @@ -2474,7 +2441,7 @@ async def test_get_product_async( request_type=product_search_service.GetProductRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2492,24 +2459,18 @@ async def test_get_product_async( 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] == 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" @@ -2519,17 +2480,17 @@ async def test_get_product_async_from_dict(): def test_get_product_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -2544,11 +2505,14 @@ def test_get_product_field_headers(): @pytest.mark.asyncio async def test_get_product_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -2556,7 +2520,6 @@ async def test_get_product_field_headers_async(): 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. @@ -2570,13 +2533,12 @@ async def test_get_product_field_headers_async(): def test_get_product_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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",) @@ -2585,12 +2547,11 @@ def test_get_product_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2602,7 +2563,9 @@ def test_get_product_flattened_error(): @pytest.mark.asyncio async def test_get_product_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -2620,13 +2583,14 @@ async def test_get_product_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2640,7 +2604,7 @@ def test_update_product( transport: str = "grpc", request_type=product_search_service.UpdateProductRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2656,25 +2620,18 @@ def test_update_product( 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" @@ -2686,7 +2643,7 @@ def test_update_product_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2694,7 +2651,6 @@ def test_update_product_empty_call(): client.update_product() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.UpdateProductRequest() @@ -2704,7 +2660,7 @@ async def test_update_product_async( request_type=product_search_service.UpdateProductRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2722,24 +2678,18 @@ async def test_update_product_async( 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] == 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" @@ -2749,17 +2699,17 @@ async def test_update_product_async_from_dict(): def test_update_product_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -2776,11 +2726,14 @@ def test_update_product_field_headers(): @pytest.mark.asyncio async def test_update_product_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -2788,7 +2741,6 @@ async def test_update_product_field_headers_async(): 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. @@ -2804,32 +2756,29 @@ async def test_update_product_field_headers_async(): def test_update_product_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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"]), + update_mask=field_mask_pb2.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"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) def test_update_product_flattened_error(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2837,13 +2786,15 @@ def test_update_product_flattened_error(): client.update_product( product_search_service.UpdateProductRequest(), product=product_search_service.Product(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio async def test_update_product_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -2857,22 +2808,22 @@ async def test_update_product_flattened_async(): # 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"]), + update_mask=field_mask_pb2.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"]) + assert args[0].update_mask == field_mask_pb2.FieldMask(paths=["paths_value"]) @pytest.mark.asyncio async def test_update_product_flattened_error_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2880,7 +2831,7 @@ async def test_update_product_flattened_error_async(): await client.update_product( product_search_service.UpdateProductRequest(), product=product_search_service.Product(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -2888,7 +2839,7 @@ def test_delete_product( transport: str = "grpc", request_type=product_search_service.DeleteProductRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2899,13 +2850,11 @@ def test_delete_product( 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. @@ -2920,7 +2869,7 @@ def test_delete_product_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2928,7 +2877,6 @@ def test_delete_product_empty_call(): client.delete_product() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.DeleteProductRequest() @@ -2938,7 +2886,7 @@ async def test_delete_product_async( request_type=product_search_service.DeleteProductRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2949,13 +2897,11 @@ async def test_delete_product_async( with mock.patch.object(type(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] == product_search_service.DeleteProductRequest() # Establish that the response is the type that we expect. @@ -2968,17 +2914,17 @@ async def test_delete_product_async_from_dict(): def test_delete_product_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -2993,17 +2939,19 @@ def test_delete_product_field_headers(): @pytest.mark.asyncio async def test_delete_product_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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 = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_product(request) # Establish that the underlying gRPC stub method was called. @@ -3017,13 +2965,12 @@ async def test_delete_product_field_headers_async(): def test_delete_product_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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",) @@ -3032,12 +2979,11 @@ def test_delete_product_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3049,7 +2995,9 @@ def test_delete_product_flattened_error(): @pytest.mark.asyncio async def test_delete_product_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -3065,13 +3013,14 @@ async def test_delete_product_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3086,7 +3035,7 @@ def test_create_reference_image( request_type=product_search_service.CreateReferenceImageRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3101,21 +3050,16 @@ def test_create_reference_image( 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" @@ -3127,7 +3071,7 @@ def test_create_reference_image_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3137,7 +3081,6 @@ def test_create_reference_image_empty_call(): client.create_reference_image() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.CreateReferenceImageRequest() @@ -3147,7 +3090,7 @@ async def test_create_reference_image_async( request_type=product_search_service.CreateReferenceImageRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3162,20 +3105,16 @@ async def test_create_reference_image_async( 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] == 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" @@ -3185,11 +3124,12 @@ async def test_create_reference_image_async_from_dict(): def test_create_reference_image_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -3197,7 +3137,6 @@ def test_create_reference_image_field_headers(): 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. @@ -3212,11 +3151,14 @@ def test_create_reference_image_field_headers(): @pytest.mark.asyncio async def test_create_reference_image_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -3226,7 +3168,6 @@ async def test_create_reference_image_field_headers_async(): 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. @@ -3240,7 +3181,7 @@ async def test_create_reference_image_field_headers_async(): def test_create_reference_image_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3248,7 +3189,6 @@ def test_create_reference_image_flattened(): ) 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( @@ -3261,18 +3201,15 @@ def test_create_reference_image_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3287,7 +3224,9 @@ def test_create_reference_image_flattened_error(): @pytest.mark.asyncio async def test_create_reference_image_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3311,19 +3250,18 @@ async def test_create_reference_image_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3341,7 +3279,7 @@ def test_delete_reference_image( request_type=product_search_service.DeleteReferenceImageRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3354,13 +3292,11 @@ def test_delete_reference_image( ) 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. @@ -3375,7 +3311,7 @@ def test_delete_reference_image_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3385,7 +3321,6 @@ def test_delete_reference_image_empty_call(): client.delete_reference_image() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.DeleteReferenceImageRequest() @@ -3395,7 +3330,7 @@ async def test_delete_reference_image_async( request_type=product_search_service.DeleteReferenceImageRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3408,13 +3343,11 @@ async def test_delete_reference_image_async( ) 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] == product_search_service.DeleteReferenceImageRequest() # Establish that the response is the type that we expect. @@ -3427,11 +3360,12 @@ async def test_delete_reference_image_async_from_dict(): def test_delete_reference_image_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -3439,7 +3373,6 @@ def test_delete_reference_image_field_headers(): 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. @@ -3454,11 +3387,14 @@ def test_delete_reference_image_field_headers(): @pytest.mark.asyncio async def test_delete_reference_image_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -3466,7 +3402,6 @@ async def test_delete_reference_image_field_headers_async(): type(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. @@ -3480,7 +3415,7 @@ async def test_delete_reference_image_field_headers_async(): def test_delete_reference_image_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3488,7 +3423,6 @@ def test_delete_reference_image_flattened(): ) 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",) @@ -3497,12 +3431,11 @@ def test_delete_reference_image_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3514,7 +3447,9 @@ def test_delete_reference_image_flattened_error(): @pytest.mark.asyncio async def test_delete_reference_image_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3532,13 +3467,14 @@ async def test_delete_reference_image_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3553,7 +3489,7 @@ def test_list_reference_images( request_type=product_search_service.ListReferenceImagesRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3568,21 +3504,16 @@ def test_list_reference_images( 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" @@ -3594,7 +3525,7 @@ def test_list_reference_images_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -3604,7 +3535,6 @@ def test_list_reference_images_empty_call(): client.list_reference_images() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.ListReferenceImagesRequest() @@ -3614,7 +3544,7 @@ async def test_list_reference_images_async( request_type=product_search_service.ListReferenceImagesRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3631,20 +3561,16 @@ async def test_list_reference_images_async( 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] == product_search_service.ListReferenceImagesRequest() # 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" @@ -3654,11 +3580,12 @@ async def test_list_reference_images_async_from_dict(): def test_list_reference_images_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -3666,7 +3593,6 @@ def test_list_reference_images_field_headers(): 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. @@ -3681,11 +3607,14 @@ def test_list_reference_images_field_headers(): @pytest.mark.asyncio async def test_list_reference_images_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -3695,7 +3624,6 @@ async def test_list_reference_images_field_headers_async(): 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. @@ -3709,7 +3637,7 @@ async def test_list_reference_images_field_headers_async(): def test_list_reference_images_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3717,7 +3645,6 @@ def test_list_reference_images_flattened(): ) 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",) @@ -3726,12 +3653,11 @@ def test_list_reference_images_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3743,7 +3669,9 @@ def test_list_reference_images_flattened_error(): @pytest.mark.asyncio async def test_list_reference_images_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3763,13 +3691,14 @@ async def test_list_reference_images_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -3780,7 +3709,7 @@ async def test_list_reference_images_flattened_error_async(): def test_list_reference_images_pager(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3828,7 +3757,7 @@ def test_list_reference_images_pager(): def test_list_reference_images_pages(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3866,7 +3795,7 @@ def test_list_reference_images_pages(): @pytest.mark.asyncio async def test_list_reference_images_async_pager(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3913,7 +3842,7 @@ async def test_list_reference_images_async_pager(): @pytest.mark.asyncio async def test_list_reference_images_async_pages(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -3958,7 +3887,7 @@ def test_get_reference_image( request_type=product_search_service.GetReferenceImageRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -3973,21 +3902,16 @@ def test_get_reference_image( 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" @@ -3999,7 +3923,7 @@ def test_get_reference_image_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4009,7 +3933,6 @@ def test_get_reference_image_empty_call(): client.get_reference_image() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.GetReferenceImageRequest() @@ -4019,7 +3942,7 @@ async def test_get_reference_image_async( request_type=product_search_service.GetReferenceImageRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4034,20 +3957,16 @@ async def test_get_reference_image_async( 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] == 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" @@ -4057,11 +3976,12 @@ async def test_get_reference_image_async_from_dict(): def test_get_reference_image_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -4069,7 +3989,6 @@ def test_get_reference_image_field_headers(): 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. @@ -4084,11 +4003,14 @@ def test_get_reference_image_field_headers(): @pytest.mark.asyncio async def test_get_reference_image_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -4098,7 +4020,6 @@ async def test_get_reference_image_field_headers_async(): 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. @@ -4112,7 +4033,7 @@ async def test_get_reference_image_field_headers_async(): def test_get_reference_image_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4120,7 +4041,6 @@ def test_get_reference_image_flattened(): ) 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",) @@ -4129,12 +4049,11 @@ def test_get_reference_image_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4146,7 +4065,9 @@ def test_get_reference_image_flattened_error(): @pytest.mark.asyncio async def test_get_reference_image_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4166,13 +4087,14 @@ async def test_get_reference_image_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4187,7 +4109,7 @@ def test_add_product_to_product_set( request_type=product_search_service.AddProductToProductSetRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4200,13 +4122,11 @@ def test_add_product_to_product_set( ) 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. @@ -4221,7 +4141,7 @@ def test_add_product_to_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4231,7 +4151,6 @@ def test_add_product_to_product_set_empty_call(): client.add_product_to_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.AddProductToProductSetRequest() @@ -4241,7 +4160,7 @@ async def test_add_product_to_product_set_async( request_type=product_search_service.AddProductToProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4254,13 +4173,11 @@ async def test_add_product_to_product_set_async( ) 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] == product_search_service.AddProductToProductSetRequest() # Establish that the response is the type that we expect. @@ -4273,11 +4190,12 @@ async def test_add_product_to_product_set_async_from_dict(): def test_add_product_to_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -4285,7 +4203,6 @@ def test_add_product_to_product_set_field_headers(): 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. @@ -4300,11 +4217,14 @@ def test_add_product_to_product_set_field_headers(): @pytest.mark.asyncio async def test_add_product_to_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -4312,7 +4232,6 @@ async def test_add_product_to_product_set_field_headers_async(): type(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. @@ -4326,7 +4245,7 @@ async def test_add_product_to_product_set_field_headers_async(): def test_add_product_to_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4334,7 +4253,6 @@ def test_add_product_to_product_set_flattened(): ) 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( @@ -4345,14 +4263,12 @@ def test_add_product_to_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4366,7 +4282,9 @@ def test_add_product_to_product_set_flattened_error(): @pytest.mark.asyncio async def test_add_product_to_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4386,15 +4304,15 @@ async def test_add_product_to_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4411,7 +4329,7 @@ def test_remove_product_from_product_set( request_type=product_search_service.RemoveProductFromProductSetRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4424,13 +4342,11 @@ def test_remove_product_from_product_set( ) 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. @@ -4445,7 +4361,7 @@ def test_remove_product_from_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4455,7 +4371,6 @@ def test_remove_product_from_product_set_empty_call(): client.remove_product_from_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.RemoveProductFromProductSetRequest() @@ -4465,7 +4380,7 @@ async def test_remove_product_from_product_set_async( request_type=product_search_service.RemoveProductFromProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4478,13 +4393,11 @@ async def test_remove_product_from_product_set_async( ) 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] == product_search_service.RemoveProductFromProductSetRequest() # Establish that the response is the type that we expect. @@ -4497,11 +4410,12 @@ async def test_remove_product_from_product_set_async_from_dict(): def test_remove_product_from_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -4509,7 +4423,6 @@ def test_remove_product_from_product_set_field_headers(): 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. @@ -4524,11 +4437,14 @@ def test_remove_product_from_product_set_field_headers(): @pytest.mark.asyncio async def test_remove_product_from_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -4536,7 +4452,6 @@ async def test_remove_product_from_product_set_field_headers_async(): type(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. @@ -4550,7 +4465,7 @@ async def test_remove_product_from_product_set_field_headers_async(): def test_remove_product_from_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4558,7 +4473,6 @@ def test_remove_product_from_product_set_flattened(): ) 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( @@ -4569,14 +4483,12 @@ def test_remove_product_from_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4590,7 +4502,9 @@ def test_remove_product_from_product_set_flattened_error(): @pytest.mark.asyncio async def test_remove_product_from_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4610,15 +4524,15 @@ async def test_remove_product_from_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4635,7 +4549,7 @@ def test_list_products_in_product_set( request_type=product_search_service.ListProductsInProductSetRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4650,19 +4564,15 @@ def test_list_products_in_product_set( 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" @@ -4674,7 +4584,7 @@ def test_list_products_in_product_set_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -4684,7 +4594,6 @@ def test_list_products_in_product_set_empty_call(): client.list_products_in_product_set() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.ListProductsInProductSetRequest() @@ -4694,7 +4603,7 @@ async def test_list_products_in_product_set_async( request_type=product_search_service.ListProductsInProductSetRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -4711,18 +4620,15 @@ async def test_list_products_in_product_set_async( 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] == product_search_service.ListProductsInProductSetRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProductsInProductSetAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -4732,11 +4638,12 @@ async def test_list_products_in_product_set_async_from_dict(): def test_list_products_in_product_set_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -4744,7 +4651,6 @@ def test_list_products_in_product_set_field_headers(): 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. @@ -4759,11 +4665,14 @@ def test_list_products_in_product_set_field_headers(): @pytest.mark.asyncio async def test_list_products_in_product_set_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -4773,7 +4682,6 @@ async def test_list_products_in_product_set_field_headers_async(): 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. @@ -4787,7 +4695,7 @@ async def test_list_products_in_product_set_field_headers_async(): def test_list_products_in_product_set_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4795,7 +4703,6 @@ def test_list_products_in_product_set_flattened(): ) 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",) @@ -4804,12 +4711,11 @@ def test_list_products_in_product_set_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4821,7 +4727,9 @@ def test_list_products_in_product_set_flattened_error(): @pytest.mark.asyncio async def test_list_products_in_product_set_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4841,13 +4749,14 @@ async def test_list_products_in_product_set_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -4858,7 +4767,7 @@ async def test_list_products_in_product_set_flattened_error_async(): def test_list_products_in_product_set_pager(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4903,7 +4812,7 @@ def test_list_products_in_product_set_pager(): def test_list_products_in_product_set_pages(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4940,7 +4849,7 @@ def test_list_products_in_product_set_pages(): @pytest.mark.asyncio async def test_list_products_in_product_set_async_pager(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -4984,7 +4893,7 @@ async def test_list_products_in_product_set_async_pager(): @pytest.mark.asyncio async def test_list_products_in_product_set_async_pages(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials,) + client = ProductSearchAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -5030,7 +4939,7 @@ def test_import_product_sets( request_type=product_search_service.ImportProductSetsRequest, ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5043,13 +4952,11 @@ def test_import_product_sets( ) 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. @@ -5064,7 +4971,7 @@ def test_import_product_sets_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5074,7 +4981,6 @@ def test_import_product_sets_empty_call(): client.import_product_sets() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.ImportProductSetsRequest() @@ -5084,7 +4990,7 @@ async def test_import_product_sets_async( request_type=product_search_service.ImportProductSetsRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5099,13 +5005,11 @@ async def test_import_product_sets_async( 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] == product_search_service.ImportProductSetsRequest() # Establish that the response is the type that we expect. @@ -5118,11 +5022,12 @@ async def test_import_product_sets_async_from_dict(): def test_import_product_sets_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -5130,7 +5035,6 @@ def test_import_product_sets_field_headers(): 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. @@ -5145,11 +5049,14 @@ def test_import_product_sets_field_headers(): @pytest.mark.asyncio async def test_import_product_sets_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -5159,7 +5066,6 @@ async def test_import_product_sets_field_headers_async(): 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. @@ -5173,7 +5079,7 @@ async def test_import_product_sets_field_headers_async(): def test_import_product_sets_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -5181,7 +5087,6 @@ def test_import_product_sets_flattened(): ) 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( @@ -5197,9 +5102,7 @@ def test_import_product_sets_flattened(): # 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( @@ -5210,7 +5113,7 @@ def test_import_product_sets_flattened(): def test_import_product_sets_flattened_error(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5228,7 +5131,9 @@ def test_import_product_sets_flattened_error(): @pytest.mark.asyncio async def test_import_product_sets_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -5255,9 +5160,7 @@ async def test_import_product_sets_flattened_async(): # 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( @@ -5269,7 +5172,9 @@ async def test_import_product_sets_flattened_async(): @pytest.mark.asyncio async def test_import_product_sets_flattened_error_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5289,7 +5194,7 @@ def test_purge_products( transport: str = "grpc", request_type=product_search_service.PurgeProductsRequest ): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5300,13 +5205,11 @@ def test_purge_products( 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. @@ -5321,7 +5224,7 @@ def test_purge_products_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -5329,7 +5232,6 @@ def test_purge_products_empty_call(): client.purge_products() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == product_search_service.PurgeProductsRequest() @@ -5339,7 +5241,7 @@ async def test_purge_products_async( request_type=product_search_service.PurgeProductsRequest, ): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -5352,13 +5254,11 @@ async def test_purge_products_async( 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] == product_search_service.PurgeProductsRequest() # Establish that the response is the type that we expect. @@ -5371,17 +5271,17 @@ async def test_purge_products_async_from_dict(): def test_purge_products_field_headers(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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. @@ -5396,11 +5296,14 @@ def test_purge_products_field_headers(): @pytest.mark.asyncio async def test_purge_products_field_headers_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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. @@ -5408,7 +5311,6 @@ async def test_purge_products_field_headers_async(): 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. @@ -5422,13 +5324,12 @@ async def test_purge_products_field_headers_async(): def test_purge_products_flattened(): - client = ProductSearchClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchClient(credentials=ga_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",) @@ -5437,12 +5338,11 @@ def test_purge_products_flattened(): # 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(),) + client = ProductSearchClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5454,7 +5354,9 @@ def test_purge_products_flattened_error(): @pytest.mark.asyncio async def test_purge_products_flattened_async(): - client = ProductSearchAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = ProductSearchAsyncClient( + credentials=ga_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: @@ -5472,13 +5374,14 @@ async def test_purge_products_flattened_async(): # 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(),) + client = ProductSearchAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -5491,16 +5394,16 @@ async def test_purge_products_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.ProductSearchGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.ProductSearchGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ProductSearchClient( @@ -5510,7 +5413,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.ProductSearchGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = ProductSearchClient( @@ -5521,7 +5424,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.ProductSearchGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = ProductSearchClient(transport=transport) assert client.transport is transport @@ -5530,13 +5433,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.ProductSearchGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.ProductSearchGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -5551,23 +5454,23 @@ def test_transport_get_channel(): ) 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) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_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(),) + client = ProductSearchClient(credentials=ga_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): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.ProductSearchTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -5579,7 +5482,7 @@ def test_product_search_base_transport(): ) as Transport: Transport.return_value = None transport = transports.ProductSearchTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -5615,15 +5518,40 @@ def test_product_search_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 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" + google.auth, "load_credentials_from_file", autospec=True ) 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) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProductSearchTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_product_search_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) 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 = (ga_credentials.AnonymousCredentials(), None) transport = transports.ProductSearchTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -5639,19 +5567,36 @@ def test_product_search_base_transport_with_credentials_file(): 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( + with mock.patch.object(google.auth, "default", autospec=True) 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) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.ProductSearchTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 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) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + ProductSearchClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_product_search_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) ProductSearchClient() adc.assert_called_once_with( scopes=( @@ -5662,14 +5607,44 @@ def test_product_search_auth_adc(): ) -def test_product_search_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_product_search_transport_auth_adc(transport_class): # 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" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProductSearchGrpcTransport, + transports.ProductSearchGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_product_search_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=( "https://www.googleapis.com/auth/cloud-platform", @@ -5679,6 +5654,121 @@ def test_product_search_transport_auth_adc(): ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ProductSearchGrpcTransport, grpc_helpers), + (transports.ProductSearchGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_product_search_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + scopes=["1", "2"], + default_host="vision.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ProductSearchGrpcTransport, grpc_helpers), + (transports.ProductSearchGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_product_search_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/cloud-vision", + ), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.ProductSearchGrpcTransport, grpc_helpers), + (transports.ProductSearchGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_product_search_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vision.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [ @@ -5687,7 +5777,7 @@ def test_product_search_transport_auth_adc(): ], ) def test_product_search_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -5729,7 +5819,7 @@ def test_product_search_grpc_transport_client_cert_source_for_mtls(transport_cla def test_product_search_host_no_port(): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="vision.googleapis.com" ), @@ -5739,7 +5829,7 @@ def test_product_search_host_no_port(): def test_product_search_host_with_port(): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="vision.googleapis.com:8000" ), @@ -5793,9 +5883,9 @@ def test_product_search_transport_channel_mtls_with_client_cert_source(transport mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -5877,7 +5967,7 @@ def test_product_search_transport_channel_mtls_with_adc(transport_class): def test_product_search_grpc_lro_client(): client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -5890,7 +5980,7 @@ def test_product_search_grpc_lro_client(): def test_product_search_grpc_lro_async_client(): client = ProductSearchAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -5905,7 +5995,6 @@ def test_product_path(): project = "squid" location = "clam" product = "whelk" - expected = "projects/{project}/locations/{location}/products/{product}".format( project=project, location=location, product=product, ) @@ -5930,7 +6019,6 @@ def test_product_set_path(): project = "cuttlefish" location = "mussel" product_set = "winkle" - expected = "projects/{project}/locations/{location}/productSets/{product_set}".format( project=project, location=location, product_set=product_set, ) @@ -5956,7 +6044,6 @@ def test_reference_image_path(): location = "clam" product = "whelk" reference_image = "octopus" - expected = "projects/{project}/locations/{location}/products/{product}/referenceImages/{reference_image}".format( project=project, location=location, @@ -5985,7 +6072,6 @@ def test_parse_reference_image_path(): def test_common_billing_account_path(): billing_account = "winkle" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -6006,7 +6092,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "scallop" - expected = "folders/{folder}".format(folder=folder,) actual = ProductSearchClient.common_folder_path(folder) assert expected == actual @@ -6025,7 +6110,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "squid" - expected = "organizations/{organization}".format(organization=organization,) actual = ProductSearchClient.common_organization_path(organization) assert expected == actual @@ -6044,7 +6128,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "whelk" - expected = "projects/{project}".format(project=project,) actual = ProductSearchClient.common_project_path(project) assert expected == actual @@ -6064,7 +6147,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "oyster" location = "nudibranch" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -6091,7 +6173,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.ProductSearchTransport, "_prep_wrapped_messages" ) as prep: client = ProductSearchClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -6100,6 +6182,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = ProductSearchClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info)